text
stringlengths
65
6.05M
lang
stringclasses
8 values
type
stringclasses
2 values
id
stringlengths
64
64
// ZOA_CREATED! DO NOT EDIT IT! -- /* * Copyright 2009-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.io; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; /** * Provides a very simple API for accessing resources within an application server. * * @author Ben Gunter */ import com.process.ZoaExp; import com.process.ZoaThreadLocal; public abstract class VFS { private static final Log log = LogFactory.getLog(ResolverUtil.class); /** The built-in implementations. */ public static final Class<?>[] IMPLEMENTATIONS = { JBoss6VFS.class, DefaultVFS.class }; /** The list to which implementations are added by {@link #addImplClass(Class)}. */ public static final List<Class<? extends VFS>> USER_IMPLEMENTATIONS = new ArrayList<Class<? extends VFS>>(); /** Singleton instance. */ private static VFS instance; /** * Get the singleton {@link VFS} instance. If no {@link VFS} implementation can be found for the * current environment, then this method returns null. */ @SuppressWarnings("unchecked") public static VFS getInstance() { ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1001 187 0 8135540"); if ((ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 1 8135540")|| true) && (instance != null? (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 0 0 1 0 ","8135540",true,1) || true): (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 0 0 0 0 ","8135540",false,0) && false))){ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 2 8135540"); return instance; } ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 3 8135540"); // Try the user implementations first, then the built-ins List<Class<? extends VFS>> impls = new ArrayList<Class<? extends VFS>>(); impls.addAll(USER_IMPLEMENTATIONS); impls.addAll(Arrays.asList((Class<? extends VFS>[]) IMPLEMENTATIONS)); // Try each implementation class until a valid one is found VFS vfs = null; int zoa_cond_n4_0 = 2; int zoa_cond_n4_1 = 2; //zoa_cond_n4_0#vfs == null$zoa_cond_n4_1#vfs.isValid() for (int i = 0; (ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 4 8135540")|| true) && ((vfs == null?(zoa_cond_n4_0 != (zoa_cond_n4_0 = 1)):(zoa_cond_n4_0 == (zoa_cond_n4_0 = 0))) || !(vfs.isValid()?(zoa_cond_n4_1 != (zoa_cond_n4_1 = 1)):(zoa_cond_n4_1 == (zoa_cond_n4_1 = 0)))? (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 3 1 1 2 ","8135540",true,zoa_cond_n4_0,zoa_cond_n4_1) || true): (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 3 1 0 2 ","8135540",false,zoa_cond_n4_0,zoa_cond_n4_1) && false)); i++){zoa_cond_n4_0 = 2; zoa_cond_n4_1 = 2; ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 5 8135540"); { Class<? extends VFS> impl = impls.get(i); try {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 6 8135540"); vfs = impl.newInstance(); int zoa_cond_n7_0 = 2; int zoa_cond_n7_1 = 2; //zoa_cond_n7_0#vfs == null$zoa_cond_n7_1#vfs.isValid() if ((ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 7 8135540")|| true) && ((vfs == null?(zoa_cond_n7_0 != (zoa_cond_n7_0 = 1)):(zoa_cond_n7_0 == (zoa_cond_n7_0 = 0))) || !(vfs.isValid()?(zoa_cond_n7_1 != (zoa_cond_n7_1 = 1)):(zoa_cond_n7_1 == (zoa_cond_n7_1 = 0)))? (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 6 2 1 2 ","8135540",true,zoa_cond_n7_0,zoa_cond_n7_1) || true): (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 6 2 0 2 ","8135540",false,zoa_cond_n7_0,zoa_cond_n7_1) && false))){ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 8 8135540"); { log.debug("VFS implementation " + impl.getName() + " is not valid in this environment."); } } } catch (InstantiationException e) {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 10 8135540"); log.error("Failed to instantiate " + impl, e); return null; } catch (IllegalAccessException e) {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 11 8135540"); log.error("Failed to instantiate " + impl, e); return null; } }} ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 13 8135540"); log.debug("Using VFS adapter " + vfs.getClass().getName()); return VFS.instance = vfs; } /** * Adds the specified class to the list of {@link VFS} implementations. Classes added in this * manner are tried in the order they are added and before any of the built-in implementations. * * @param clazz The {@link VFS} implementation class to add. */ public static void addImplClass(Class<? extends VFS> clazz) { ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1001 187 14 8135540"); if ((ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 15 8135540")|| true) && (clazz != null? (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 7 3 1 0 ","8135540",true,1) || true): (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 7 3 0 0 ","8135540",false,0) && false))){ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 16 8135540"); USER_IMPLEMENTATIONS.add(clazz); } } /** Get a class by name. If the class is not found then return null. */ protected static Class<?> getClass(String className) { ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1001 187 18 8135540"); try {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 19 8135540"); return Thread.currentThread().getContextClassLoader().loadClass(className); // return ReflectUtil.findClass(className); } catch (ClassNotFoundException e) {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 20 8135540"); log.debug("Class not found: " + className); return null; } } /** * Get a method by name and parameter types. If the method is not found then return null. * * @param clazz The class to which the method belongs. * @param methodName The name of the method. * @param parameterTypes The types of the parameters accepted by the method. */ protected static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) { ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1001 187 22 8135540"); try {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 23 8135540"); if ((ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 24 8135540")|| true) && (clazz == null? (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 8 4 1 0 ","8135540",true,1) || true): (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 8 4 0 0 ","8135540",false,0) && false))){ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 25 8135540"); return null; } else { ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 26 8135540"); return clazz.getMethod(methodName, parameterTypes); } } catch (SecurityException e) {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 28 8135540"); log.error("Security exception looking for method " + clazz.getName() + "." + methodName + ". Cause: " + e); return null; } catch (NoSuchMethodException e) {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 29 8135540"); log.error("Method not found " + clazz.getName() + "." + methodName + "." + methodName + ". Cause: " + e); return null; } } /** * Invoke a method on an object and return whatever it returns. * * @param method The method to invoke. * @param object The instance or class (for static methods) on which to invoke the method. * @param parameters The parameters to pass to the method. * @return Whatever the method returns. * @throws IOException If I/O errors occur * @throws StripesRuntimeException If anything else goes wrong */ @SuppressWarnings("unchecked") protected static <T> T invoke(Method method, Object object, Object... parameters) throws IOException, RuntimeException { ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1001 187 31 8135540"); try {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 32 8135540"); return (T) method.invoke(object, parameters); } catch (IllegalArgumentException e) {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 33 8135540"); throw new RuntimeException(e); } catch (IllegalAccessException e) {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 34 8135540"); throw new RuntimeException(e); } catch (InvocationTargetException e) {ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 35 8135540"); if ((ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 36 8135540")|| true) && (e.getTargetException() instanceof IOException? (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 9 5 1 0 ","8135540",true,1) || true): (ZoaExp.ZoaMCDC(ZoaThreadLocal.G_Ins().G_CInf() + " 187 9 5 0 0 ","8135540",false,0) && false))){ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 37 8135540"); throw (IOException) e.getTargetException(); } else { ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 38 8135540"); throw new RuntimeException(e); } } } /** * Get a list of {@link URL}s from the context classloader for all the resources found at the * specified path. * * @param path The resource path. * @return A list of {@link URL}s, as returned by {@link ClassLoader#getResources(String)}. * @throws IOException If I/O errors occur */ protected static List<URL> getResources(String path) throws IOException { ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1001 187 41 8135540"); return Collections.list(Thread.currentThread().getContextClassLoader().getResources(path)); } /** Return true if the {@link VFS} implementation is valid for the current environment. */ public abstract boolean isValid(); /** * Recursively list the full resource path of all the resources that are children of the * resource identified by a URL. * * @param url The URL that identifies the resource to list. * @param forPath The path to the resource that is identified by the URL. Generally, this is the * value passed to {@link #getResources(String)} to get the resource URL. * @return A list containing the names of the child resources. * @throws IOException If I/O errors occur */ protected abstract List<String> list(URL url, String forPath) throws IOException; /** * Recursively list the full resource path of all the resources that are children of all the * resources found at the specified path. * * @param path The path of the resource(s) to list. * @return A list containing the names of the child resources. * @throws IOException If I/O errors occur */ public List<String> list(String path) throws IOException { ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1001 187 42 8135540"); List<String> names = new ArrayList<String>(); for (URL url : /* TRUE */getResources(path)){ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 43 8135540");ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 44 8135540"); { names.addAll(list(url, path)); }} ZoaExp.N(ZoaThreadLocal.G_Ins().G_CInf() + " 1000 187 45 8135540"); return names; } }
Java
CL
a46a18c2bf80328d847af241de95e96b8d92d44ed10465ddcb8bdbc2808398de
package ca.mec.productimage.dao; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import org.json.JSONException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; @ExtendWith(SpringExtension.class) class ImageColorDAOTest { @Mock private RestTemplate restTemplate; @InjectMocks private ImageColorDAO imageColorDAO; @Value("${imgix.color.pallette.parameter}") private String palletteParameter; @Test void getColors() throws JSONException { String res = "{colors:[{hex: \"#0d0d11\"}, {hex: \"#383739\"}, {hex: \"#534539\"}, " + "{hex: \"#808183\"}, {hex: \"#a7a7a8\"}, {hex: \"#c39474\"} ]}"; Mockito.when(restTemplate.getForEntity(anyString(), any())) .thenReturn(new ResponseEntity(res, HttpStatus.OK)); ResponseEntity<String> responseEntity = restTemplate.getForEntity( "https://mec.imgix.net/medias/sys_master/fallback/fallback/9066744676382/6005445-ASG01-fallback.jpg?"+palletteParameter, String.class); Assertions.assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); JSONAssert.assertEquals(res, responseEntity.getBody(), JSONCompareMode.LENIENT); } }
Java
CL
4033d0aa7a3d587c3849344dcbbd1fc4952f88f5c692385a48570ce97be58621
package controllers; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityTransaction; import org.joda.time.DateTime; import com.google.gson.Gson; import messages.Messages; import models.JsonPeticionModificacion; import models.Participacion; import models.Registro; import models.RegistroModificacion; import models.SolicitudGenerica; import play.db.jpa.JPA; import play.db.jpa.Model; import play.mvc.Util; import tables.TableRecord; import tags.ComboItem; import utils.ModelUtils; import utils.PeticionModificacion; import utils.PeticionModificacion.ValorCampoModificado; import controllers.fap.JustificacionFapController; import controllers.fap.ModificacionFAPController; import controllers.gen.ActivarModificacionSolicitudesControllerGen; import enumerado.fap.gen.EstadosModificacionEnum; import enumerado.fap.gen.TiposParticipacionEnum; public class ActivarModificacionSolicitudesController extends ActivarModificacionSolicitudesControllerGen { public static List<ComboItem> fechaARestaurar() { List<ComboItem> result = new ArrayList<ComboItem>(); Map<String, Long> ids = (Map<String, Long>) tags.TagMapStack.top("idParams"); if ((ids == null) || (ids.get("idSolicitud") == null)) return result; SolicitudGenerica solicitud = getSolicitudGenerica(ids.get("idSolicitud")); int i=1; ComboItem ultimoRegistrado = null; if ((solicitud.registro != null) && (solicitud.registro.fasesRegistro.registro) && (!solicitud.registroModificacion.isEmpty())) ultimoRegistrado = new ComboItem(solicitud.registroModificacion.get(0).id.toString(), solicitud.registro.informacionRegistro.fechaRegistro.toString("dd/MM/yyyy")+" Presentación Inicial"); for (RegistroModificacion rm: solicitud.registroModificacion){ if ((rm.registro != null) && (rm.registro.fasesRegistro.registro)) ultimoRegistrado = new ComboItem(rm.id.toString(), rm.registro.informacionRegistro.fechaRegistro.toString("dd/MM/yyyy")+" "+String.valueOf(i)+"º Modificación"); i++; } result.add(ultimoRegistrado); return result; } @Util // Este @Util es necesario porque en determinadas circunstancias crear(..) llama a editar(..). public static void formRestaurarModificacion(Long idSolicitud, SolicitudGenerica solicitud, String restaurarBtn) { checkAuthenticity(); Long idRegistroModificacion = null; if (!permisoFormRestaurarModificacion("editar")) { Messages.error("No tiene permisos suficientes para realizar la acción"); } if (!Messages.hasErrors()) { Long idRecuperar = null; if (!solicitud.fechaARestaurarStr.isEmpty()) idRegistroModificacion = Long.parseLong(solicitud.fechaARestaurarStr); if (idRegistroModificacion != null) { SolicitudGenerica dbSolicitud = SolicitudGenerica.findById(idSolicitud); boolean recuperarPresentacion = true; for (RegistroModificacion rm: dbSolicitud.registroModificacion){ //Comprobar si se han creado elementos nuevos que haya que borrar if ((rm.estado.equals(EstadosModificacionEnum.expirada.name())) ||(rm.estado.equals(EstadosModificacionEnum.enCurso.name()))){ rm.enRecuperacion = true; idRecuperar = rm.id; ModelUtils.restaurarBorrados(rm.id, idSolicitud); ModelUtils.restaurarSolicitud(idRecuperar, idSolicitud, false); } rm.enRecuperacion = false; } for (RegistroModificacion rm: dbSolicitud.registroModificacion){ if (rm.estado.equals(EstadosModificacionEnum.expirada.name()) || rm.estado.equals(EstadosModificacionEnum.enCurso.name())){ rm.enRecuperacion = true; ModelUtils.eliminarCreados(rm.id, idSolicitud); } rm.enRecuperacion = false; } ModelUtils.finalizarDeshacerModificacion(idSolicitud); if (!Messages.hasErrors()) { try { ModificacionFAPController.invoke(ModificacionFAPController.class, "postRestaurarSolicitud", idSolicitud); }catch (Throwable e1) { log.error("Hubo un problema al invocar el métodos postRestaurarSolicitud: "+e1); Messages.error("Error al postrestaurarlasolicitud"); } if ((dbSolicitud.solicitante.isPersonaFisica()) && (!dbSolicitud.solicitante.representado)){ //esto es si es física Participacion par = Participacion.find("select participacion from Participacion participacion where participacion.tipo=? and participacion.solicitud.id=?", TiposParticipacionEnum.representante.name(), idSolicitud).first(); if (par != null){ par.delete(); } } } log.info("Acción Editar de página: " + "gen/ActivarModificacionSolicitudes/ActivarModificacionSolicitudes.html" + " , intentada con éxito"); } else { Messages.error("Hubo un fallo al intentar recuperar el Registro correspondiente"); } } else log.info("Acción Editar de página: " + "gen/ActivarModificacionSolicitudes/ActivarModificacionSolicitudes.html" + " , intentada sin éxito (Problemas de Validación)"); ActivarModificacionSolicitudesController.formRestaurarModificacionRender(idSolicitud); } public static void tablatablaModificaciones(Long idSolicitud) { java.util.List<RegistroModificacion> rows = RegistroModificacion.find("select registroModificacion from SolicitudGenerica solicitud join solicitud.registroModificacion registroModificacion where solicitud.id=?", idSolicitud).fetch(); List<RegistroModificacion> rowsFiltered = new ArrayList<RegistroModificacion>(); Map<String, Long> ids = (Map<String, Long>) tags.TagMapStack.top("idParams"); for (RegistroModificacion registroModificacion : rows) { Map<String, Object> vars = new HashMap<String, Object>(); vars.put("registroModificacion", registroModificacion); if (secure.checkAcceso("filaTablaModificaciones", "leer", ids, vars)) { rowsFiltered.add(registroModificacion); } } tables.TableRenderResponse<RegistroModificacion> response = new tables.TableRenderResponse<RegistroModificacion>(rowsFiltered, false, false, false, "crearYEditarModificacionSolicitud", "", "adminOrGestorOrRevisor", getAccion(), ids); for (TableRecord<RegistroModificacion> registroModificacion : response.rows) { if ((registroModificacion.objeto.estado.equals("enCurso")) || (registroModificacion.objeto.estado.equals("expirada"))) { registroModificacion.permisoEditar = true; } else { registroModificacion.permisoEditar = false; registroModificacion.permisoLeer = false; } } renderJSON(response.toJSON("fechaCreacion", "fechaRegistro", "fechaCancelacion", "fechaLimite", "estadoValue", "registro.justificante.enlaceDescarga", "id")); } }
Java
CL
3a7c3269786944817621cf7feff2005ba0bfe581ad8d0dc7d5aec822f5289b60
package payments; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.mock.http.MockHttpOutputMessage; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import payments.attributes.*; import payments.attributes.amount.Amount; import payments.attributes.amount.Currency; import payments.attributes.amount.fx.ForeignExchange; import payments.attributes.amount.fx.ForeignExchangeRepository; import payments.attributes.details.PaymentDetails; import payments.attributes.details.PaymentDetailsScheme; import payments.attributes.details.PaymentDetailsType; import payments.attributes.parties.*; import payments.attributes.scheme.SchemePayment; import payments.attributes.scheme.SchemePaymentSubtype; import payments.attributes.scheme.SchemePaymentType; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.io.IOException; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.util.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @WebAppConfiguration public class PaymentsControllerTest { private MockMvc mockMvc; @Autowired private PaymentsRepository paymentsRepository; @Autowired private PartyRepository partyRepository; @Autowired private ChargesRepository chargesRepository; @Autowired private ForeignExchangeRepository foreignExchangeRepository; @Autowired private WebApplicationContext context; private HttpMessageConverter jsonMapper; private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType()); private Payment payment; @Autowired void setConverters(HttpMessageConverter<?>[] converters) { this.jsonMapper = Arrays.stream(converters) .filter(messageConverter -> messageConverter instanceof MappingJackson2HttpMessageConverter) .findAny() .orElse(null); } @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); this.paymentsRepository.deleteAllInBatch(); payment = this.generatePayment(); this.paymentsRepository.save(payment); } @Test public void getSingleExistingPayment() throws Exception { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); this.mockMvc.perform(get("/payments/" + this.payment.getId())) .andExpect(status().isOk()) .andExpect(jsonPath("$.payment.attributes.amount", is(payment.getAttributes().getAmount().toString()))) .andExpect(jsonPath("$.payment.attributes.currency", is(payment.getAttributes().getAmount().getCurrency().toString()))) // Beneficiary party .andExpect(jsonPath("$.payment.attributes.beneficiary_party.account_name", is(payment.getAttributes().getParties().getBeneficiary().getAccount().getName()))) .andExpect(jsonPath("$.payment.attributes.beneficiary_party.account_number", is(payment.getAttributes().getParties().getBeneficiary().getAccount().getNumber()))) .andExpect(jsonPath("$.payment.attributes.beneficiary_party.account_number_code", is(payment.getAttributes().getParties().getBeneficiary().getAccount().getNumberCode()))) .andExpect(jsonPath("$.payment.attributes.beneficiary_party.account_type", is(payment.getAttributes().getParties().getBeneficiary().getAccount().getType()))) .andExpect(jsonPath("$.payment.attributes.beneficiary_party.address", is(payment.getAttributes().getParties().getBeneficiary().getAddress()))) .andExpect(jsonPath("$.payment.attributes.beneficiary_party.bank_id", is(payment.getAttributes().getParties().getBeneficiary().getBank().getId()))) .andExpect(jsonPath("$.payment.attributes.beneficiary_party.bank_id_code", is(payment.getAttributes().getParties().getBeneficiary().getBank().getIdCode()))) .andExpect(jsonPath("$.payment.attributes.beneficiary_party.name", is(payment.getAttributes().getParties().getBeneficiary().getName()))) // Debtor party .andExpect(jsonPath("$.payment.attributes.debtor_party.account_name", is(payment.getAttributes().getParties().getDebtor().getAccount().getName()))) .andExpect(jsonPath("$.payment.attributes.debtor_party.account_number", is(payment.getAttributes().getParties().getDebtor().getAccount().getNumber()))) .andExpect(jsonPath("$.payment.attributes.debtor_party.account_number_code", is(payment.getAttributes().getParties().getDebtor().getAccount().getNumberCode()))) .andExpect(jsonPath("$.payment.attributes.debtor_party.address", is(payment.getAttributes().getParties().getDebtor().getAddress()))) .andExpect(jsonPath("$.payment.attributes.debtor_party.bank_id", is(payment.getAttributes().getParties().getDebtor().getBank().getId()))) .andExpect(jsonPath("$.payment.attributes.debtor_party.bank_id_code", is(payment.getAttributes().getParties().getDebtor().getBank().getIdCode()))) .andExpect(jsonPath("$.payment.attributes.debtor_party.name", is(payment.getAttributes().getParties().getDebtor().getName()))) // Sponsor party .andExpect(jsonPath("$.payment.attributes.sponsor_party.account_number", is(payment.getAttributes().getParties().getSponsor().getAccount().getNumber()))) .andExpect(jsonPath("$.payment.attributes.sponsor_party.bank_id", is(payment.getAttributes().getParties().getSponsor().getBank().getId()))) .andExpect(jsonPath("$.payment.attributes.sponsor_party.bank_id_code", is(payment.getAttributes().getParties().getSponsor().getBank().getIdCode()))) // Charges .andExpect(jsonPath("$.payment.attributes.charges_information.bearer_code", is(payment.getAttributes().getCharges().getBearerCode()))) .andExpect(jsonPath("$.payment.attributes.charges_information.sender_charges[0].amount", is(payment.getAttributes().getCharges().getSenderCharges().get(0).toString()))) .andExpect(jsonPath("$.payment.attributes.charges_information.sender_charges[0].currency", is(payment.getAttributes().getCharges().getSenderCharges().get(0).getCurrency().toString()))) .andExpect(jsonPath("$.payment.attributes.charges_information.sender_charges[1].amount", is(payment.getAttributes().getCharges().getSenderCharges().get(1).toString()))) .andExpect(jsonPath("$.payment.attributes.charges_information.sender_charges[1].currency", is(payment.getAttributes().getCharges().getSenderCharges().get(1).getCurrency().toString()))) .andExpect(jsonPath("$.payment.attributes.charges_information.receiver_charges_amount", is(payment.getAttributes().getCharges().getReceiverCharges().toString()))) .andExpect(jsonPath("$.payment.attributes.charges_information.receiver_charges_currency", is(payment.getAttributes().getCharges().getReceiverCharges().getCurrency().toString()))) // References .andExpect(jsonPath("$.payment.attributes.reference", is(payment.getAttributes().getReferences().getRoot()))) .andExpect(jsonPath("$.payment.attributes.end_to_end_reference", is(payment.getAttributes().getReferences().getEndToEnd()))) .andExpect(jsonPath("$.payment.attributes.numeric_reference", is(payment.getAttributes().getReferences().getNumeric()))) // Payment details .andExpect(jsonPath("$.payment.attributes.payment_id", is(payment.getAttributes().getPaymentDetails().getId()))) .andExpect(jsonPath("$.payment.attributes.payment_purpose", is(payment.getAttributes().getPaymentDetails().getPurpose()))) .andExpect(jsonPath("$.payment.attributes.payment_scheme", is(payment.getAttributes().getPaymentDetails().getScheme().toString()))) .andExpect(jsonPath("$.payment.attributes.payment_type", is(payment.getAttributes().getPaymentDetails().getType().toString()))) // Foreign Exchange .andExpect(jsonPath("$.payment.attributes.fx.contract_reference", is(payment.getAttributes().getForeignExchange().getContractReference()))) .andExpect(jsonPath("$.payment.attributes.fx.exchange_rate", is(payment.getAttributes().getForeignExchange().getExchangeRateAsString()))) .andExpect(jsonPath("$.payment.attributes.fx.original_amount", is(payment.getAttributes().getForeignExchange().getOriginalAmount().toString()))) .andExpect(jsonPath("$.payment.attributes.fx.original_currency", is(payment.getAttributes().getForeignExchange().getOriginalAmount().getCurrency().toString()))) // Scheme Payment .andExpect(jsonPath("$.payment.attributes.scheme_payment_type", is(payment.getAttributes().getSchemePayment().getType().toString()))) .andExpect(jsonPath("$.payment.attributes.scheme_payment_sub_type", is(payment.getAttributes().getSchemePayment().getSubtype().toString()))) .andExpect(jsonPath("$.payment.attributes.processing_date", is(dateFormat.format(payment.getAttributes().getProcessingDate())))) .andExpect(jsonPath("$.payment.id", is(this.payment.getId().toString()))) .andExpect(jsonPath("$.payment.version", is(this.payment.getVersion()))) .andExpect(jsonPath("$.payment.type", is(this.payment.getType().toString()))) .andExpect(jsonPath("$.links[0].href", containsString("/payments/" + this.payment.getId()))); } @Test public void getSingleNonExistingPayment() throws Exception { this.mockMvc.perform(get("/payments/" + UUID.randomUUID())) .andExpect(status().isNotFound()); } @Test public void getListOfPayments() throws Exception { this.mockMvc.perform(get("/payments")) .andExpect(status().isOk()) .andExpect(jsonPath("$.links[0].href", containsString("/payments"))) .andExpect(jsonPath("$.content[0].payment.id", is(this.payment.getId().toString()))); } @Test public void createNewPayment() throws Exception { Payment payment = new Payment(); String paymentJson = this.encodeToJson(payment); long entityCount = this.paymentsRepository.count(); this.mockMvc.perform(post("/payments").contentType(this.contentType).content(paymentJson)) .andExpect(status().isCreated()); assertEquals(entityCount + 1, this.paymentsRepository.count()); } @Test public void updateExistingPayment() throws Exception { Payment payment = this.paymentsRepository.save(this.generatePayment()); payment.setOrganisationId(UUID.randomUUID()); String paymentJson = this.encodeToJson(payment); this.mockMvc.perform(put("/payments/" + payment.getId()).contentType(this.contentType).content(paymentJson)) .andExpect(status().isOk()); } @Test public void updateNonExistingPayment() throws Exception { this.mockMvc.perform(put("/payments/" + UUID.randomUUID())) .andExpect(status().isNotFound()); } @Test public void deleteExistingPayment() throws Exception { Payment payment = this.paymentsRepository.save(this.generatePayment()); long entityCount = this.paymentsRepository.count(); this.mockMvc.perform(delete("/payments/" + payment.getId())) .andExpect(status().isOk()); assertEquals(entityCount - 1, this.paymentsRepository.count()); } @Test public void deleteNonExistingPayment() throws Exception { long entityCount = this.paymentsRepository.count(); this.mockMvc.perform(delete("/payments/" + UUID.randomUUID())) .andExpect(status().isNotFound()); assertEquals(entityCount, this.paymentsRepository.count()); } private String encodeToJson(Object o) throws IOException { MockHttpOutputMessage message = new MockHttpOutputMessage(); this.jsonMapper.write(o, MediaType.APPLICATION_JSON, message); return message.getBodyAsString(); } private Payment generatePayment() { String fullName = "First Middle Last"; String address = "42 Main St London EC42 G4D"; Amount amount = new Amount(BigInteger.valueOf(2), 56, Currency.GBP); Account beneficiaryAccount = new Account("F Last", "accNum", "accCode", 42); Bank beneficiaryBank = new Bank("beneficiaryBankId", "beneficiaryBankIdCode"); Party beneficiary = new Party(beneficiaryAccount, address, beneficiaryBank, fullName); this.partyRepository.save(beneficiary); Account debtorAccount = new Account("debtorName", "debtorAccNum", "debtorCode"); Bank debtorBank = new Bank("debtorBankId", "debtorBankIdCode"); Party debtor = new Party(debtorAccount, "111 The Circle", debtorBank, "Debt Name"); this.partyRepository.save(debtor); Account sponsorAccount = new Account("sponsorAccNum"); Bank sponsorBank = new Bank("sponsorBankId", "sponsorBankIdCode"); Party sponsor = new Party(sponsorAccount, sponsorBank); this.partyRepository.save(sponsor); Parties parties = new Parties(beneficiary, debtor, sponsor); References references = new References("rootRef", "e2eRef", "numRef"); Date processingDate = new GregorianCalendar(2017, Calendar.JANUARY, 24).getTime(); PaymentDetails paymentDetails = new PaymentDetails("payId", "payPurpose", PaymentDetailsScheme.FPS, PaymentDetailsType.Credit); List<Amount> senderAmounts = Arrays.asList( new Amount(BigInteger.valueOf(5), 10, Currency.GBP), new Amount(BigInteger.valueOf(10), 20, Currency.GBP) ); Amount receiverAmount = new Amount(BigInteger.valueOf(1), 30, Currency.GBP); Charges charges = new Charges("bearerCode", senderAmounts, receiverAmount); this.chargesRepository.save(charges); ForeignExchange foreignExchange = new ForeignExchange("contractRef", 2.0, new Amount(BigInteger.valueOf(200), 42, Currency.GBP)); this.foreignExchangeRepository.save(foreignExchange); SchemePayment schemePayment = new SchemePayment(SchemePaymentType.ImmediatePayment, SchemePaymentSubtype.InternetBanking); Attributes attributes = new AttributesBuilder() .withAmount(amount) .withCharges(charges) .withForeignExchange(foreignExchange) .withParties(parties) .withPaymentDetails(paymentDetails) .withProcessingDate(processingDate) .withReferences(references) .withSchemePayment(schemePayment) .build(); return new Payment(UUID.randomUUID(), 42, PaymentType.Payment, attributes); } }
Java
CL
4a5772f9c40ad168d09db4284e1a0e53712c8e33be11affed613058a8e8d2d4e
package kotlinx.coroutines.flow; import kotlin.Metadata; import kotlin.jvm.functions.Function2; @Metadata(mo51341bv = {1, 0, 3}, mo51342d1 = {"\u0000\u0019\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002*\u0001\u0000\b\n\u0018\u00002\b\u0012\u0004\u0012\u00028\u00000\u0001J\u001f\u0010\u0002\u001a\u00020\u00032\f\u0010\u0004\u001a\b\u0012\u0004\u0012\u00028\u00000\u0005H–@ø\u0001\u0000¢\u0006\u0002\u0010\u0006‚\u0002\u0004\n\u0002\b\u0019¨\u0006\u0007¸\u0006\u0000"}, mo51343d2 = {"kotlinx/coroutines/flow/internal/SafeCollector_commonKt$unsafeFlow$1", "Lkotlinx/coroutines/flow/Flow;", "collect", "", "collector", "Lkotlinx/coroutines/flow/FlowCollector;", "(Lkotlinx/coroutines/flow/FlowCollector;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", "kotlinx-coroutines-core"}, mo51344k = 1, mo51345mv = {1, 4, 0}) /* compiled from: SafeCollector.common.kt */ public final class FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1 implements Flow<T> { final /* synthetic */ Function2 $action$inlined; final /* synthetic */ Flow $this_onStart$inlined; /* JADX WARNING: Removed duplicated region for block: B:19:0x0066 */ /* JADX WARNING: Removed duplicated region for block: B:27:0x00ad A[RETURN] */ /* JADX WARNING: Removed duplicated region for block: B:8:0x0025 */ /* Code decompiled incorrectly, please refer to instructions dump. */ public java.lang.Object collect(kotlinx.coroutines.flow.FlowCollector r8, kotlin.coroutines.Continuation r9) { /* r7 = this; boolean r0 = r9 instanceof kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1.C49191 if (r0 == 0) goto L_0x0014 r0 = r9 kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1$1 r0 = (kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1.C49191) r0 int r1 = r0.label r2 = -2147483648(0xffffffff80000000, float:-0.0) r1 = r1 & r2 if (r1 == 0) goto L_0x0014 int r9 = r0.label int r9 = r9 - r2 r0.label = r9 goto L_0x0019 L_0x0014: kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1$1 r0 = new kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1$1 r0.<init>(r7, r9) L_0x0019: java.lang.Object r9 = r0.result java.lang.Object r1 = kotlin.coroutines.intrinsics.IntrinsicsKt.getCOROUTINE_SUSPENDED() int r2 = r0.label r3 = 2 r4 = 1 if (r2 == 0) goto L_0x0066 if (r2 == r4) goto L_0x004a if (r2 != r3) goto L_0x0042 java.lang.Object r8 = r0.L$4 kotlinx.coroutines.flow.internal.SafeCollector r8 = (kotlinx.coroutines.flow.internal.SafeCollector) r8 java.lang.Object r8 = r0.L$3 kotlinx.coroutines.flow.FlowCollector r8 = (kotlinx.coroutines.flow.FlowCollector) r8 java.lang.Object r8 = r0.L$2 kotlin.coroutines.Continuation r8 = (kotlin.coroutines.Continuation) r8 java.lang.Object r8 = r0.L$1 kotlinx.coroutines.flow.FlowCollector r8 = (kotlinx.coroutines.flow.FlowCollector) r8 java.lang.Object r8 = r0.L$0 kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1 r8 = (kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1) r8 kotlin.ResultKt.throwOnFailure(r9) goto L_0x00ae L_0x0042: java.lang.IllegalStateException r8 = new java.lang.IllegalStateException java.lang.String r9 = "call to 'resume' before 'invoke' with coroutine" r8.<init>(r9) throw r8 L_0x004a: java.lang.Object r8 = r0.L$4 kotlinx.coroutines.flow.internal.SafeCollector r8 = (kotlinx.coroutines.flow.internal.SafeCollector) r8 java.lang.Object r2 = r0.L$3 kotlinx.coroutines.flow.FlowCollector r2 = (kotlinx.coroutines.flow.FlowCollector) r2 java.lang.Object r4 = r0.L$2 kotlin.coroutines.Continuation r4 = (kotlin.coroutines.Continuation) r4 java.lang.Object r5 = r0.L$1 kotlinx.coroutines.flow.FlowCollector r5 = (kotlinx.coroutines.flow.FlowCollector) r5 java.lang.Object r6 = r0.L$0 kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1 r6 = (kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1) r6 kotlin.ResultKt.throwOnFailure(r9) // Catch:{ all -> 0x0063 } r9 = r4 goto L_0x0096 L_0x0063: r9 = move-exception r5 = r8 goto L_0x00b2 L_0x0066: kotlin.ResultKt.throwOnFailure(r9) r9 = r0 kotlin.coroutines.Continuation r9 = (kotlin.coroutines.Continuation) r9 kotlin.coroutines.CoroutineContext r2 = r0.getContext() kotlinx.coroutines.flow.internal.SafeCollector r5 = new kotlinx.coroutines.flow.internal.SafeCollector r5.<init>(r8, r2) kotlin.jvm.functions.Function2 r2 = r7.$action$inlined // Catch:{ all -> 0x00b1 } r0.L$0 = r7 // Catch:{ all -> 0x00b1 } r0.L$1 = r8 // Catch:{ all -> 0x00b1 } r0.L$2 = r9 // Catch:{ all -> 0x00b1 } r0.L$3 = r8 // Catch:{ all -> 0x00b1 } r0.L$4 = r5 // Catch:{ all -> 0x00b1 } r0.label = r4 // Catch:{ all -> 0x00b1 } r4 = 6 kotlin.jvm.internal.InlineMarker.mark((int) r4) // Catch:{ all -> 0x00b1 } java.lang.Object r2 = r2.invoke(r5, r0) // Catch:{ all -> 0x00b1 } r4 = 7 kotlin.jvm.internal.InlineMarker.mark((int) r4) // Catch:{ all -> 0x00b1 } if (r2 != r1) goto L_0x0092 return r1 L_0x0092: r6 = r7 r2 = r8 r8 = r5 r5 = r2 L_0x0096: r8.releaseIntercepted() kotlinx.coroutines.flow.Flow r4 = r6.$this_onStart$inlined r0.L$0 = r6 r0.L$1 = r5 r0.L$2 = r9 r0.L$3 = r2 r0.L$4 = r8 r0.label = r3 java.lang.Object r8 = r4.collect(r2, r0) if (r8 != r1) goto L_0x00ae return r1 L_0x00ae: kotlin.Unit r8 = kotlin.Unit.INSTANCE return r8 L_0x00b1: r9 = move-exception L_0x00b2: r5.releaseIntercepted() throw r9 */ throw new UnsupportedOperationException("Method not decompiled: kotlinx.coroutines.flow.FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1.collect(kotlinx.coroutines.flow.FlowCollector, kotlin.coroutines.Continuation):java.lang.Object"); } public FlowKt__EmittersKt$onStart$$inlined$unsafeFlow$1(Flow flow, Function2 function2) { this.$this_onStart$inlined = flow; this.$action$inlined = function2; } }
Java
CL
16a8b7015ee2045262e1f9c5cf27cfe6ad89f3f13e992515659d47de91785c6a
package com.rudilucas.ideas.security.ldap; import static java.util.Collections.singletonList; import javax.naming.InvalidNameException; import javax.naming.ldap.LdapName; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DirContextOperations; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.ldap.authentication.LdapAuthenticationProvider; import org.springframework.security.ldap.authentication.LdapAuthenticator; import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator; public class MockLdapAuthenticationProvider extends LdapAuthenticationProvider { public MockLdapAuthenticationProvider(LdapAuthenticator authenticator, LdapAuthoritiesPopulator authoritiesPopulator) { super(authenticator, authoritiesPopulator); } @Override protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken authentication) { DirContextOperations context = null; try { context = new DirContextAdapter(new LdapName("CN=" + authentication.getName())); } catch (InvalidNameException e) { e.printStackTrace(); } return context; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), singletonList(new SimpleGrantedAuthority("ROLE_USER"))); } @Override protected Authentication createSuccessfulAuthentication(UsernamePasswordAuthenticationToken authentication, UserDetails user) { return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), user.getAuthorities()); } }
Java
CL
31923bd181596db8cf3f6c925572ce4ab39b2d2e7d36c53bbc1190f6ff60af3d
package hb.legsandbuttocksworkout.homeworkout.gym.buttlegs.buttlegspro.buttlegschallenge.setting; import android.app.Activity; import android.content.DialogInterface; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.widget.AppCompatImageView; import android.support.v7.widget.AppCompatTextView; import android.support.v7.widget.SwitchCompat; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.View.OnClickListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.NumberPicker; import android.widget.RelativeLayout; import com.afollestad.materialdialogs.MaterialDialog; import com.afollestad.materialdialogs.MaterialDialog.ListCallbackSingleChoice; import com.bumptech.glide.Glide; import java.util.ArrayList; import java.util.Collection; import hb.legsandbuttocksworkout.homeworkout.gym.buttlegs.buttlegspro.buttlegschallenge.BuildConfig; import hb.legsandbuttocksworkout.homeworkout.gym.buttlegs.buttlegspro.buttlegschallenge.R; import hb.legsandbuttocksworkout.homeworkout.gym.buttlegs.buttlegspro.buttlegschallenge.base.BackBaseActivity; import hb.legsandbuttocksworkout.homeworkout.gym.buttlegs.buttlegspro.buttlegschallenge.utils.ResourceService; import hb.legsandbuttocksworkout.homeworkout.gym.buttlegs.buttlegspro.buttlegschallenge.utils.RestartAppModel; import hb.legsandbuttocksworkout.homeworkout.gym.buttlegs.buttlegspro.buttlegschallenge.utils.SharedPrefsService; import hb.legsandbuttocksworkout.homeworkout.gym.buttlegs.buttlegspro.buttlegschallenge.utils.TypeFaceService; import hb.legsandbuttocksworkout.homeworkout.gym.buttlegs.buttlegspro.buttlegschallenge.utils.WeightMetricDialog; import biz.kasual.materialnumberpicker.MaterialNumberPicker.Builder; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class SettingActivity extends BackBaseActivity implements ListCallbackSingleChoice { @BindView(R.id.contentSetting) RelativeLayout contentSetting; @BindView(R.id.genderLayout) LinearLayout genderLayout; private int genderPosition; private Typeface rBold; private Typeface rLight; private Typeface rRegular; int readyDuration = 0; @BindView(R.id.readyTime) AppCompatTextView readyTime; @BindView(R.id.readyTimeLayout) FrameLayout readyTimeLayout; int restDuration = 0; @BindView(R.id.restTime) AppCompatTextView restTime; @BindView(R.id.restTimeLayout) FrameLayout restTimeLayout; @BindView(R.id.sGender) AppCompatTextView sGender; @BindView(R.id.sGenderImage) AppCompatImageView sGenderImage; @BindView(R.id.sReadyTime) AppCompatTextView sReadyTime; @BindView(R.id.sRestTime) AppCompatTextView sRestTime; @BindView(R.id.sSound) AppCompatTextView sSound; @BindView(R.id.sWeekStart) AppCompatTextView sWeekStart; @BindView(R.id.sWeight) AppCompatTextView sWeight; @BindView(R.id.sWeightMetricText) AppCompatTextView sWeightMetricText; @BindView(R.id.settingContent) LinearLayout settingContent; @BindView(R.id.settingToolbarText) AppCompatTextView settingToolbarText; @BindView(R.id.settingVersionName) AppCompatTextView settingVersionName; @BindView(R.id.soundLayout) LinearLayout soundLayout; @BindView(R.id.soundSwitch) SwitchCompat soundSwitch; @BindView(R.id.sstPersonal) AppCompatTextView sstPersonal; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.weekStart) AppCompatTextView weekStart; @BindView(R.id.weekStartLayout) LinearLayout weekStartLayout; String[] weekStartList; private int weekStartPosition; @BindView(R.id.weightLayout) FrameLayout weightLayout; @BindView(R.id.imgGender) ImageView Imggender; protected void onCreate(Bundle savedInstanceState) { CharSequence string; super.onCreate(savedInstanceState); setContentView((int) R.layout.activity_settings); ButterKnife.bind((Activity) this); setToolbar(); initFonts(); String versionName = BuildConfig.VERSION_NAME; this.genderPosition = SharedPrefsService.getInstance().getGender(this) - 1; this.weekStartPosition = SharedPrefsService.getInstance().getWeekStart(this); this.restDuration = SharedPrefsService.getInstance().getRestTime(this); this.restTime.setText(this.restDuration + getResources().getString(R.string.seconds_short)); this.readyDuration = SharedPrefsService.getInstance().getReadyTime(this); this.readyTime.setText(this.readyDuration + getResources().getString(R.string.seconds_short)); this.weekStartList = getResources().getStringArray(R.array.week_start); this.weekStart.setText(this.weekStartList[this.weekStartPosition]); AppCompatTextView appCompatTextView = this.sWeightMetricText; if (SharedPrefsService.getInstance().getWeightMetric(this) != 1) { string = getString(R.string.kg); } else { string = getString(R.string.lb); } appCompatTextView.setText(string); this.settingVersionName.setText("v" + versionName); this.contentSetting.setVisibility(0); this.genderLayout.setOnClickListener(new OnClickListener() { public void onClick(View v) { SettingActivity.this.genderDialog(); } }); this.weightLayout.setOnClickListener(new OnClickListener() { public void onClick(View v) { WeightMetricDialog.getInstance().show(SettingActivity.this, SettingActivity.this); } }); this.soundSwitch.setChecked(SharedPrefsService.getInstance().getSoundStatus(this)); this.soundSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (b) { SharedPrefsService.getInstance().setSoundStatus(SettingActivity.this, true); } else { SharedPrefsService.getInstance().setSoundStatus(SettingActivity.this, false); } } }); this.restTimeLayout.setOnClickListener(new OnClickListener() { public void onClick(View view) { SettingActivity.this.restTimePicker(true); } }); this.readyTimeLayout.setOnClickListener(new OnClickListener() { public void onClick(View view) { SettingActivity.this.restTimePicker(false); } }); switch (this.genderPosition) { case 0: Glide.with((FragmentActivity) this).load(Integer.valueOf(ResourceService.getInstance().getdrawableResourceId("boy", this))).into(this.sGenderImage); Glide.with((FragmentActivity) this).load(Integer.valueOf(ResourceService.getInstance().getdrawableResourceId("boy", this))).into(this.Imggender); return; case 1: Glide.with((FragmentActivity) this).load(Integer.valueOf(ResourceService.getInstance().getdrawableResourceId("girl", this))).into(this.sGenderImage); Glide.with((FragmentActivity) this).load(Integer.valueOf(ResourceService.getInstance().getdrawableResourceId("girl", this))).into(this.Imggender); return; default: return; } } private void setToolbar() { setSupportActionBar(this.toolbar); ActionBar supportActionBar = getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayHomeAsUpEnabled(true); supportActionBar.setDisplayShowTitleEnabled(false); } } private void initFonts() { this.rLight = TypeFaceService.getInstance().getRobotoLight(this); this.rRegular = TypeFaceService.getInstance().getRobotoRegular(this); this.rBold = TypeFaceService.getInstance().getRobotoBold(this); setFonts(); } private void setFonts() { this.sWeight.setTypeface(this.rRegular); this.sWeightMetricText.setTypeface(this.rRegular); this.sGender.setTypeface(this.rRegular); this.weekStart.setTypeface(this.rRegular); this.sWeekStart.setTypeface(this.rRegular); this.sSound.setTypeface(this.rRegular); this.sstPersonal.setTypeface(this.rRegular); this.restTime.setTypeface(this.rRegular); this.sRestTime.setTypeface(this.rRegular); this.settingVersionName.setTypeface(this.rRegular); this.settingToolbarText.setTypeface(this.rLight); } private void genderDialog() { Collection langList = new ArrayList(); langList.add(getString(R.string.male).toUpperCase()); langList.add(getString(R.string.female).toUpperCase()); new MaterialDialog.Builder(this).title((int) R.string.setting_ch_gender).items(langList).itemsCallbackSingleChoice(this.genderPosition, new ListCallbackSingleChoice() { public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { SharedPrefsService.getInstance().setGender(SettingActivity.this, which + 1); RestartAppModel.getInstance().settingsChanged(true); SettingActivity.this.finish(); return true; } }).positiveText((int) R.string.setting_ok).negativeText((int) R.string.setting_cancel).show(); } private void WeekStartDialog() { new MaterialDialog.Builder(this).title((int) R.string.setting_ch_weekstart).items(this.weekStartList).itemsCallbackSingleChoice(this.weekStartPosition, new ListCallbackSingleChoice() { public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { SharedPrefsService.getInstance().setWeekStart(SettingActivity.this, which); RestartAppModel.getInstance().settingsChanged(true); SettingActivity.this.weekStart.setText(SettingActivity.this.weekStartList[which]); return true; } }).positiveText((int) R.string.setting_ok).negativeText((int) R.string.setting_cancel).show(); } private void restTimePicker(final boolean isRest) { final int defaltDuration = isRest ? this.restDuration : this.readyDuration; runOnUiThread(new Runnable() { public void run() { final NumberPicker numberPicker = new Builder(SettingActivity.this.getApplicationContext()).minValue(3).maxValue(60).defaultValue(defaltDuration).backgroundColor(-1).separatorColor(0).textColor(ViewCompat.MEASURED_STATE_MASK).textSize(20.0f).enableFocusability(false).wrapSelectorWheel(true).build(); new AlertDialog.Builder(SettingActivity.this).setTitle((isRest ? SettingActivity.this.getString(R.string.setting_rest_duration) : SettingActivity.this.getString(R.string.setting_ready_duration)) + "(" + SettingActivity.this.getString(R.string.seconds_short) + ")").setView(numberPicker).setPositiveButton(SettingActivity.this.getString(17039370), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (isRest) { SettingActivity.this.restDuration = numberPicker.getValue(); SharedPrefsService.getInstance().setRestTime(SettingActivity.this, SettingActivity.this.restDuration); SettingActivity.this.restTime.setText(SettingActivity.this.restDuration + SettingActivity.this.getResources().getString(R.string.seconds_short)); return; } SettingActivity.this.readyDuration = numberPicker.getValue(); SharedPrefsService.getInstance().setReadyTime(SettingActivity.this, SettingActivity.this.readyDuration); SettingActivity.this.readyTime.setText(SettingActivity.this.readyDuration + SettingActivity.this.getResources().getString(R.string.seconds_short)); } }).setNegativeButton(SettingActivity.this.getString(17039360), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).show(); } }); } @OnClick({R.id.weekStart, R.id.weekStartLayout}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.weekStartLayout: WeekStartDialog(); return; default: return; } } public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) { this.sWeightMetricText.setText(which != 1 ? getString(R.string.kg) : getString(R.string.lb)); SharedPrefsService.getInstance().setWeightMetric(this, which); RestartAppModel.getInstance().settingsChanged(true); return true; } }
Java
CL
582b1e8ed9db988df544152397bfd5e5bdd5ff6f17bb0d369ed676952cfa07de
package com.loopme; import android.app.Activity; import android.view.View; import android.widget.FrameLayout; import com.loopme.ad.AdSpotDimensions; import com.loopme.ad.LoopMeAd; import com.loopme.common.LoopMeError; import com.loopme.controllers.display.DisplayControllerLoopMe; import com.loopme.time.TimersType; import com.loopme.tracker.partners.LoopMeTracker; /** * The `LoopMeBanner` class provides facilities to display a custom size ads * during natural transition points in your application. * <p> * It is recommended to implement `LoopMeBanner.Listener` to stay informed about ad state changes, * such as when an ad has been loaded or has failed to load its content, when video ad has been watched completely, * when an ad has been presented or dismissed from the screen, and when an ad has expired or received a tap. */ public class LoopMeBannerGeneral extends LoopMeAd { private static final String LOG_TAG = LoopMeBannerGeneral.class.getSimpleName(); public static final String TEST_MPU_BANNER = "test_mpu"; private Listener mAdListener; private volatile FrameLayout mBannerView; private boolean mIsVideoFinished; public void setMinimizedMode(MinimizedMode mode) { if (isLoopMeController()) { ((DisplayControllerLoopMe) mDisplayController).setMinimizedMode(mode); } } public interface Listener { void onLoopMeBannerLoadSuccess(LoopMeBannerGeneral banner); void onLoopMeBannerLoadFail(LoopMeBannerGeneral banner, LoopMeError error); void onLoopMeBannerShow(LoopMeBannerGeneral banner); void onLoopMeBannerHide(LoopMeBannerGeneral banner); void onLoopMeBannerClicked(LoopMeBannerGeneral banner); void onLoopMeBannerLeaveApp(LoopMeBannerGeneral banner); void onLoopMeBannerVideoDidReachEnd(LoopMeBannerGeneral banner); void onLoopMeBannerExpired(LoopMeBannerGeneral banner); } public LoopMeBannerGeneral(Activity activity, String appKey) { super(activity, appKey); Logging.out(LOG_TAG, "Start creating banner with app key: " + appKey); } public static LoopMeBannerGeneral getInstance(String appKey, Activity activity) { return new LoopMeBannerGeneral(activity, appKey); } @Override public void destroy() { runOnUiThread(new Runnable() { @Override public void run() { dismiss(); LoopMeBannerGeneral.super.destroy(); } }); } /** * @param frameLayout - @link FrameLayout (container for ad) where ad will be displayed. */ public void bindView(FrameLayout frameLayout) { if (frameLayout != null) { mBannerView = frameLayout; mContainerView = frameLayout; } else { LoopMeTracker.post("Bind view is null"); } } public FrameLayout getBannerView() { return mBannerView; } public boolean isViewBinded() { return mBannerView != null; } public void setListener(Listener listener) { if (listener != null) { mAdListener = listener; } else { Logging.out(LOG_TAG, "Warning listener is null."); } } public Listener getListener() { return mAdListener; } @Override public void removeListener() { mAdListener = null; } void showNativeVideo() { if (isPrepared()) { showInternal(); Logging.out(LOG_TAG, "Banner did start showing ad (native)"); } else { LoopMeTracker.post("Banner is not ready"); } } @Override public void show() { if (isPrepared()) { showInternal(); getDisplayController().postImpression(); if (isLoopMeAd() || isMraidAd()) { resume(); } else if (isVastAd() || isVpaidAd() && mDisplayController != null) { getDisplayController().onPlay(0); } Logging.out(LOG_TAG, "Banner did start showing ad"); } else { Logging.out(LOG_TAG, "Banner is not ready"); } } private boolean isPrepared() { return isReady() && isViewBinded() && !isShowing(); } private void showInternal() { setAdState(Constants.AdState.SHOWING); stopTimer(TimersType.EXPIRATION_TIMER); mContainerView = mBannerView; buildAdView(); mBannerView.setVisibility(View.VISIBLE); onLoopMeBannerShow(); } @Override public void pause() { if (isLoopMeController()) { ((DisplayControllerLoopMe) mDisplayController).setWebViewState(Constants.WebviewState.HIDDEN); } else { super.pause(); } } public void switchToMinimizedMode() { if (isLoopMeBannerShowing() && isVideoNotFinished()) { DisplayControllerLoopMe displayControllerLoopMe = (DisplayControllerLoopMe) getDisplayController(); if (displayControllerLoopMe.isMinimizedModeEnable()) { displayControllerLoopMe.switchToMinimizedMode(); } else { pause(); } } } private boolean isLoopMeBannerShowing() { return isLoopMeController() && isShowing(); } private boolean isVideoNotFinished() { return !mIsVideoFinished; } private boolean isLoopMeController() { return getDisplayController() instanceof DisplayControllerLoopMe; } public void playbackFinishedWithError() { mIsVideoFinished = true; } public void switchToNormalMode() { if (isLoopMeAd() && getDisplayController() != null && isShowing()) { ((DisplayControllerLoopMe) getDisplayController()).switchToNormalMode(); } } @Override public Constants.AdFormat getAdFormat() { return Constants.AdFormat.BANNER; } @Override public AdSpotDimensions getAdSpotDimensions() { if (mBannerView != null) { int width = mBannerView.getLayoutParams().width; int height = mBannerView.getLayoutParams().height; return new AdSpotDimensions(width, height); } return new AdSpotDimensions(0, 0); } /** * Triggered when banner ad failed to load ad content * * @param error - error of unsuccesful ad loading attempt */ private void onLoopMeBannerLoadFail(final LoopMeError error) { stopTimer(TimersType.FETCHER_TIMER); setReady(false); setAdState(Constants.AdState.NONE); destroyDisplayController(); if (mAdListener != null) { mAdListener.onLoopMeBannerLoadFail(this, error); } else { Logging.out(LOG_TAG, "Warning: empty listener"); } Logging.out(LOG_TAG, "Ad fails to load: " + error.getMessage()); } /** * Triggered when the banner has successfully loaded the ad content */ private void onLoopMeBannerSuccessLoad() { stopTimer(TimersType.FETCHER_TIMER); long currentTime = System.currentTimeMillis(); long loadingTime = currentTime - mStartLoadingTime; setReady(true); setAdState(Constants.AdState.NONE); if (mAdListener != null) { mAdListener.onLoopMeBannerLoadSuccess(this); } else { Logging.out(LOG_TAG, "Warning: empty listener"); } Logging.out(LOG_TAG, "Ad successfully loaded (" + loadingTime + "ms)"); } /** * Triggered when the banner ad appears on the screen */ private void onLoopMeBannerShow() { mIsVideoFinished = false; if (mAdListener != null) { mAdListener.onLoopMeBannerShow(this); } Logging.out(LOG_TAG, "Ad appeared on screen"); } /** * Triggered when the banner ad disappears on the screen */ private void onLoopMeBannerHide() { setReady(false); setAdState(Constants.AdState.NONE); destroyDisplayController(); if (mAdListener != null) { mAdListener.onLoopMeBannerHide(this); } Logging.out(LOG_TAG, "Ad disappeared from screen"); } /** * Triggered when the user taps the banner ad and the banner is about to perform extra actions * Those actions may lead to displaying a modal browser or leaving your application. */ void onLoopMeBannerClicked() { if (mAdListener != null) { mAdListener.onLoopMeBannerClicked(this); } Logging.out(LOG_TAG, "Ad received click event"); } /** * Triggered when your application is about to go to the background, initiated by the SDK. * This may happen in various ways, f.e if user wants open the SDK's browser web page in native browser or clicks * on `mailto:` links... */ void onLoopMeBannerLeaveApp() { if (mAdListener != null) { mAdListener.onLoopMeBannerLeaveApp(LoopMeBannerGeneral.this); } Logging.out(LOG_TAG, "Leaving application"); } /** * Triggered only when banner's video was played until the end. * It won't be sent if the video was skipped or the banner was dissmissed during the displaying process */ private void onLoopMeBannerVideoDidReachEnd() { mIsVideoFinished = true; switchToNormalMode(); if (mAdListener != null) { mAdListener.onLoopMeBannerVideoDidReachEnd(this); } Logging.out(LOG_TAG, "Video did reach end"); } /** * Triggered when the banner's loaded ad content is expired. * Expiration happens when loaded ad content wasn't displayed during some period of time, approximately one hour. * Once the banner is presented on the screen, the expiration is no longer tracked and banner won't * receive this message */ private void onLoopMeBannerExpired() { setReady(false); setAdState(Constants.AdState.NONE); destroyDisplayController(); if (mAdListener != null) { mAdListener.onLoopMeBannerExpired(this); } Logging.out(LOG_TAG, "Ad content is expired"); } @Override public void onAdExpired() { onLoopMeBannerExpired(); } @Override public void onAdLoadSuccess() { onLoopMeBannerSuccessLoad(); } @Override public void onAdAlreadyLoaded() { if (mAdListener != null) { mAdListener.onLoopMeBannerLoadSuccess(this); } else { Logging.out(LOG_TAG, "Warning: empty listener"); } } @Override public void onAdLoadFail(final LoopMeError error) { mHandler.post(new Runnable() { @Override public void run() { onLoopMeBannerLoadFail(error); } }); } @Override public void onAdLeaveApp() { onLoopMeBannerLeaveApp(); } @Override public void onAdClicked() { onLoopMeBannerClicked(); } @Override public void onAdVideoDidReachEnd() { onLoopMeBannerVideoDidReachEnd(); } @Override public void dismiss() { Logging.out(LOG_TAG, "Banner will be dismissed"); if (isShowing() || isNoneState()) { dismissController(); destroyBannerView(); onLoopMeBannerHide(); } else { Logging.out(LOG_TAG, "Can't dismiss ad, it's not displaying"); } } private void dismissController() { if (mDisplayController instanceof DisplayControllerLoopMe) { ((DisplayControllerLoopMe) mDisplayController).dismiss(); } } private void destroyBannerView() { if (mBannerView != null) { mBannerView.setVisibility(View.GONE); mBannerView.removeAllViews(); } } }
Java
CL
e0fb5caa5f9a8ff0ce632e49b26aaac961cd8056c92a44a9a97a465f9e0562ff
package com.ado.trader.entities; import com.ado.trader.entities.components.Area; import com.ado.trader.entities.components.Name; import com.ado.trader.entities.components.Position; import com.ado.trader.entities.components.SerializableComponent; import com.ado.trader.entities.components.WallSprite; import com.ado.trader.map.Chunk; import com.ado.trader.utils.FileLogger; import com.ado.trader.utils.GameServices; import com.ado.trader.utils.IdGenerator; import com.artemis.Component; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.World; import com.artemis.managers.GroupManager; import com.artemis.managers.TagManager; import com.artemis.utils.Bag; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.badlogic.gdx.utils.TimeUtils; //Contains entity templates and creates entities. public class EntityFactory{ private static ArrayMap<String, ArrayMap<String, JsonValue>> entityData; private static Json j; public EntityFactory(TextureAtlas atlas){ entityData = new ArrayMap<String, ArrayMap<String, JsonValue>>(); j = new Json(); JsonValue cfg = j.fromJson(null, Gdx.files.internal("data/entities/classTags.cfg")); //load entity component class tags for(JsonValue v = cfg.child; v != null; v = v.next){ if(v.name.matches("note")) continue; try { j.addClassTag(v.name, Class.forName(v.asString())); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /*loads entity profiles. *need to load external profiles */ loadInternalProfiles(); loadCustomProfiles(); } //create first entity from profile takes ~4ms and 0ms for every entity of the same type after that. public static Entity createEntity(String id){ long start = TimeUtils.nanoTime(); World w = GameServices.getWorld(); TagManager tagMan = w.getSystem(TagManager.class); GroupManager groupMan = w.getSystem(GroupManager.class); String[] split = id.split("\\."); JsonValue jsonData = entityData.get(split[0]).get(split[1]); Entity e = w.createEntity(); for(JsonValue c = jsonData.child; c != null; c = c.next){ if(c.name.matches("tag")){ tagMan.register(c.asString(), e); }else if(c.name.matches("group")){ String[] groups = c.asStringArray(); for(String g: groups){ groupMan.add(e, g); } }else{ SerializableComponent component; if(split[0].matches(IdGenerator.WALL) && c.name.matches("sprite")){ component = new WallSprite(); }else{ Class<? extends Component> className = j.getClass(c.name); component = (SerializableComponent) e.edit().create(className); } component.load(c); e.edit().add(component); } } //all entities get a Position component e.edit().add(new Position()); start = TimeUtils.timeSinceNanos(start); return e; } private void loadInternalProfiles(){ FileHandle baseFile = Gdx.files.internal("data/entities/BaseProfiles.dat"); if(baseFile.exists()){ Array<JsonValue> data = j.fromJson(null, baseFile); for(JsonValue e: data){ loadProfile(e); } } } private void loadCustomProfiles(){ FileHandle entityDir = Gdx.files.external("adoGame/editor/entities/"); if(entityDir.exists()){ FileHandle[] list = entityDir.list("dat"); for(FileHandle f: list){ JsonValue profile = j.fromJson(null, f); loadProfile(profile); } } } public void loadProfile(JsonValue entryData){ String[] idSplit = entryData.getString("baseid").split("\\."); if(!entityData.containsKey(idSplit[0])){ entityData.put(idSplit[0], new ArrayMap<String, JsonValue>()); } entityData.get(idSplit[0]).put(idSplit[1], entryData); } public static void saveEntity(int id, Json json){ Entity e = GameServices.getWorld().getEntity(id); json.writeObjectStart(); Bag<Component> bag = new Bag<>(); bag = e.getComponents(bag); for(Component c: bag){ json.writeValue(c, c.getClass()); } json.writeObjectEnd(); } public static void deleteWall(Chunk chunk, int tileX, int tileY){ Entity e = GameServices.getWorld().getEntity(chunk.getWalls().map[tileX][tileY]); chunk.getWalls().map[tileX][tileY] = null; e.deleteFromWorld(); } public static void deleteEntity(Chunk chunk, int tileX, int tileY, String name){ for(int c = 0; c < chunk.getEntities().map[tileX][tileY].length; c++){ if(chunk.getEntities().map[tileX][tileY][c] == null) continue; Entity e = GameServices.getWorld().getEntity(chunk.getEntities().map[tileX][tileY][c]); ComponentMapper<Name> nameMap = GameServices.getWorld().getMapper(Name.class); ComponentMapper<Area> areaMap = GameServices.getWorld().getMapper(Area.class); if(nameMap.get(e).getName().matches(name)){ chunk.getEntities().map[tileX][tileY][c] = null; if(areaMap.has(e)){ for(Vector2 vec: areaMap.get(e).area){ chunk.getEntities().map[(int)(tileX + vec.x)][(int)(tileY + vec.y)][c] = null; } } e.deleteFromWorld(); } } } public static ArrayMap<String, ArrayMap<String, JsonValue>> getEntityData() { return entityData; } }
Java
CL
af77aaa793dd1b1ecbb27ca22b17e931b8a364ff0596722f61c0ad3e3fbed747
// Portions Copyright (c) 2006 - 2008, Clark & Parsia, LLC. <http://www.clarkparsia.com> // Clark & Parsia, LLC parts of this source code are available under the terms of the Affero General Public License v3. // // Please see LICENSE.txt for full license terms, including the availability of proprietary exceptions. // Questions, comments, or requests for clarification: licensing@clarkparsia.com package org.mindswap.pellet.datatypes; import org.mindswap.pellet.utils.ATermUtils; import org.mindswap.pellet.utils.GenericIntervalList; import org.mindswap.pellet.utils.Namespaces; import aterm.ATermAppl; /** * @author Evren Sirin */ @SuppressWarnings("deprecation") public class XSDInteger extends XSDDecimal implements AtomicDatatype, XSDAtomicType { public static XSDInteger instance = new XSDInteger( ATermUtils.makeTermAppl( Namespaces.XSD + "integer" ) ); protected XSDInteger( ATermAppl name ) { super( name, false ); } public BaseXSDAtomicType create( GenericIntervalList intervals ) { XSDInteger type = new XSDInteger( null ); type.values = intervals; return type; } }
Java
CL
1f960d9661306e932723531412458c03c75e91f9b6cd5839632215c3b18260c6
package model.decorators; import helpers.Gensim; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import metamap.MetaMapEntry; import model.PubMedFile; import org.apache.spark.mllib.linalg.Vector; import org.apache.spark.mllib.linalg.Vectors; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import common.Config; import common.Constants; import common.Utils; public class ContentDecorator { protected Element xml; protected String abstractText; protected String articleTitle; public String meshHeadings = ""; // public int sourceTrustLevel; public List<String> sources; public String language; public int pubYear; private boolean cached = false; PubMedFile parent; public MetaMapEntry titleMetaMap; public MetaMapEntry abstractMetaMap; public String gensimAbstractVector = ""; public String gensimTitleVector = ""; public String gensimMeshVector = ""; public ContentDecorator(PubMedFile parent) { this.parent = parent; this.sources = new ArrayList<String>(); } public void parseXml() { if (this.xml.getNodeName() == "PubmedArticle") { this.parseMedlineXml(); } else if (this.xml.getNodeName() == "PubmedBookArticle") { this.parseBookXml(); } else throw new RuntimeException("Unrecognized file format \n"); this.abstractText = abstractText.replaceAll("[\n\r]", "").replaceAll("\\s+", " "); } public void parseBookXml() { XPath xpath = Constants.xPathfactory.newXPath(); Element bookDocument = (Element) this.xml.getElementsByTagName( "BookDocument").item(0); Element book = (Element) bookDocument.getElementsByTagName("Book") .item(0); Element pubDate = (Element) book.getElementsByTagName("PubDate") .item(0); if (pubDate != null) // pubDate is optional for Medline articles this.pubYear = Integer.parseInt(pubDate .getElementsByTagName("Year").item(0).getTextContent()); if (book.getElementsByTagName("PublicationType").getLength() > 0) { Element pubType = (Element) book.getElementsByTagName( "PublicationType").item(0); } Element articleAbstract = (Element) bookDocument.getElementsByTagName( "Abstract").item(0); if (articleAbstract != null) // Abstract is optional for Medline // articles this.abstractText = articleAbstract.getTextContent() .replaceAll("[\n\r]", "").replaceAll("\\s+", " "); else this.abstractText = ""; Element articleTitle = (Element) book.getElementsByTagName( "ArticleTitle").item(0); if (articleTitle != null) // Abstract is optional for Medline // articles this.articleTitle = articleTitle.getTextContent(); else this.articleTitle = ""; XPathExpression expr; try { expr = xpath.compile("/ItemList[@ListType='Synonyms']/Item"); NodeList synonymeList = (NodeList) expr.evaluate(book, XPathConstants.NODESET); for (int i = 0; i < synonymeList.getLength(); i++) { Node currentNode = synonymeList.item(i); this.meshHeadings += ", " + currentNode; } } catch (XPathExpressionException e) { e.printStackTrace(); } } public void parseMedlineXml() { Element medline = (Element) this.xml.getElementsByTagName( "MedlineCitation").item(0); Element article = (Element) medline.getElementsByTagName("Article") .item(0); Element articleAbstract = (Element) article.getElementsByTagName( "Abstract").item(0); if (articleAbstract != null) // Abstract is optional for Medline // articles this.abstractText = articleAbstract.getTextContent(); else this.abstractText = ""; Element articleTitle = (Element) article.getElementsByTagName( "ArticleTitle").item(0); if (articleTitle != null) // Abstract is optional for Medline // // articles this.articleTitle = articleTitle.getTextContent(); else this.articleTitle = ""; Element pubDate = (Element) medline.getElementsByTagName("DateCreated") .item(0); if (pubDate != null) { // pubDate is optional for Medline articles Element year = (Element) pubDate.getElementsByTagName("Year").item( 0); this.pubYear = Integer.parseInt(year.getTextContent()); } if (article.getElementsByTagName("PublicationTypeList").getLength() > 0) { NodeList articlePublicationTypeList = article .getElementsByTagName("PublicationTypeList").item(0) .getChildNodes(); for (int i = 0; i < articlePublicationTypeList.getLength(); i++) { Node a = (Node) articlePublicationTypeList.item(i); if (a.getNodeName() == "PublicationType") this.sources.add(articlePublicationTypeList.item(i) .getTextContent()); } } Element articleLanguage = (Element) article.getElementsByTagName( "Language").item(0); this.language = articleLanguage.getTextContent(); if (medline.getElementsByTagName("MeshHeadingList").getLength() > 0) { NodeList articleMeshHeadingList = medline .getElementsByTagName("MeshHeadingList").item(0) .getChildNodes(); for (int i = 0; i < articleMeshHeadingList.getLength(); i++) { Node currentNode = articleMeshHeadingList.item(i); if (currentNode.getNodeName() == "MeshHeading") { NodeList subarticleMeshHeadingList = currentNode .getChildNodes(); if (subarticleMeshHeadingList.getLength() > 0) { for (int j = 0; j < subarticleMeshHeadingList .getLength(); j++) { Node currentNode2 = subarticleMeshHeadingList .item(j); if (currentNode2.getNodeName() == "QualifierName" || currentNode2.getNodeName() == "DescriptorName") { this.meshHeadings += "," + currentNode2.getTextContent(); } } } } } } } public Element getAuthorList(Element book) { NodeList authorListList = book.getElementsByTagName("AuthorList"); if (authorListList.getLength() > 1) for (int i = 0; i < authorListList.getLength(); i++) { Node node = authorListList.item(i); if (node.hasAttributes()) { Attr attr = (Attr) node.getAttributes() .getNamedItem("type"); if (attr.equals("authors")) return (Element) node; } } return (Element) authorListList.item(0); } public Element getXml() { return xml; } public void setXml(Element xml) { this.xml = xml; } public String getAbstractText() { return abstractText; } public String getTitle() { return this.articleTitle; } public void setAbstractText(String abstractText) { this.abstractText = abstractText; } public void uncache() { this.xml = null; this.abstractText = ""; this.articleTitle = ""; this.language = ""; this.meshHeadings = ""; this.titleMetaMap = null; this.abstractMetaMap = null; this.cached = false; this.gensimAbstractVector = ""; this.gensimMeshVector = ""; this.gensimTitleVector = ""; } public boolean isOffline() { File file = new File(Config.originalArticleXmlDir + "\\" + this.parent.PID + ".xml"); return file.exists(); } public boolean hasMetaMapAbstract() { File file = new File(Config.metaMapOutputArticlesDir + "\\" + this.parent.PID + ".txt"); return file.exists(); } public boolean hasMetaMapTitle() { File file = new File(Config.metaMapOutputTitlesDir + "\\" + this.parent.PID + ".txt"); return file.exists(); } public String getGensim(String dir) { String line; try { line = Utils.readFile(new File( dir + "/" + this.parent.PID), StandardCharsets.ISO_8859_1); return line; } catch (IOException e) { return ""; } } public void cache() { // Load Gensim vector this.gensimAbstractVector = getGensim(Config.gensimOutputArticlesAbstractsDir); this.gensimTitleVector = getGensim(Config.gensimOutputArticlesTitlesDir); this.gensimMeshVector = getGensim(Config.gensimOutputArticlesMeshDir); // TODO get the files metamap that had errors! if (this.hasMetaMapTitle()) { this.titleMetaMap = new MetaMapEntry(Config.metaMapOutputTitlesDir + "\\" + this.parent.PID + ".txt"); } if (this.hasMetaMapAbstract()) { this.abstractMetaMap = new MetaMapEntry( Config.metaMapOutputArticlesDir + "\\" + this.parent.PID + ".txt"); } if (this.isOffline()) { try { File file = new File(Config.originalArticleXmlDir + "\\" + this.parent.PID + ".xml"); String xml = Utils.readFile(file, StandardCharsets.UTF_8); DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StringBuilder xmlStringBuilder = new StringBuilder(); xmlStringBuilder.append(xml); ByteArrayInputStream input = new ByteArrayInputStream( xmlStringBuilder.toString().getBytes("UTF-8")); Document doc = builder.parse(input); Element root = doc.getDocumentElement(); doc.getDocumentElement().normalize(); this.xml = root; this.parseXml(); this.cached = true; } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); throw new RuntimeException( "Document on disk is corrupted or not available: PID (" + parent.PID + ") " + e.getMessage()); } } else { throw new RuntimeException("Document was not downloaded yet, PID (" + parent.PID + ")"); } } }
Java
CL
217984487964744579c72b6a067129a9fed3af283beb026fcc132bc2791da97a
/* This file is part of Volantis Mobility Server. Volantis Mobility Server 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. Volantis Mobility Server 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 Volantis Mobility Server.  If not, see <http://www.gnu.org/licenses/>. */ /* ---------------------------------------------------------------------------- * (c) Volantis Systems Ltd 2003. * ---------------------------------------------------------------------------- */ package com.volantis.mcs.eclipse.ab.core; import com.volantis.mcs.eclipse.ab.ABPlugin; import java.util.ResourceBundle; public class CoreMessages { private static final String BUNDLE_NAME = "com.volantis.mcs.eclipse.ab.core.CoreMessages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); private CoreMessages() { } /** * @param key * @return the string mapping to the supplied key */ public static String getString(String key) { String s = null; try { s = RESOURCE_BUNDLE.getString(key); } catch (Exception e) { ABPlugin.logError(CoreMessages.class, e); } return s; } public static ResourceBundle getResourceBundle() { return RESOURCE_BUNDLE; } } /* =========================================================================== Change History =========================================================================== $Log$ 28-Feb-05 7094/1 emma VBM:2005021517 mergevbm from MCS 3.3 - fixing chkpii problem 24-Feb-05 7096/1 emma VBM:2005021517 Renaming Core and Wizard.properties, updating generation of policies.properties to work with chkpii 08-Dec-04 6416/3 ianw VBM:2004120703 New Build 08-Dec-04 6416/1 ianw VBM:2004120703 New Build 23-Mar-04 3362/1 steve VBM:2003082208 Move API doclet to Synergetics and myriads of javadoc fixes 10-Oct-03 1512/1 allan VBM:2003100702 Generic policy wizard with first wizard page =========================================================================== */
Java
CL
dea6fcfa8dae8d81202a2d729254e1e2dce4a9d71fe320a874ba67f8114bc349
package com.mathparser.ast.generalnodes; import com.mathparser.ast.Node; import com.mathparser.ast.Type; import com.mathparser.ast.doublenodes.DoubleSubtraction; import com.mathparser.ast.intnodes.IntSubtraction; public class GeneralSubtraction extends BinaryGeneralNode { /** * Constructor for src.main.java.com.mathparser.ast.generalnodes.GeneralSubtraction. * * @param left a node * @param right a node */ public GeneralSubtraction(final Node left, final Node right) { super(left, right); wrap(getChildrenType() != Type.DOUBLE ? new IntSubtraction(leftChild, rightChild) : new DoubleSubtraction(leftChild, rightChild)); } }
Java
CL
3d636c7aacacd65dab06f380a11369e5df0c6ee17c40176138168d114675e98e
package ca.albertlockett.trading.trends; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import org.ta4j.core.Bar; import org.ta4j.core.TimeSeries; /** * Find supports and resistance points in a trendline */ public class InflectionPointFinder { private TimeSeries series; private boolean isSupport = true; // whether finding supports or resistance private int smoothingFactor = 1; // private int clusterGap = 3; public InflectionPointFinder(TimeSeries series, boolean isSupport) { this.isSupport = isSupport; this.series = series; } public InflectionPointFinder(TimeSeries series, boolean isSupport, int smoothingFactor) { this.isSupport = isSupport; this.series = series; this.smoothingFactor = smoothingFactor; } public List<Integer> find() { List<Double> points = this.getPoints(); List<Integer> reversalIndexes = this.findReversalIndexes(points); List<Integer> localExtremes = this.findExtremeInClusteredReversal(reversalIndexes); return localExtremes; } /** * Get list of points. Eventually, this could return list of close, open, high or low depending on how the class is * configured */ private List<Double> getPoints() { return this.series.getBarData() .stream() .map(this::getPoint) .collect(Collectors.toList()); } /** * Get single point from a bar. Same eventual goal as getPoints() from comment */ public Double getPoint(Bar bar) { return bar.getMinPrice().doubleValue(); } public Double calculateLHSAverageValueAtPoint(List<Double> points, int index) { if (index < this.smoothingFactor) { return null; } int j = 0; double[] values = new double[smoothingFactor]; for (int i = index - 1 ; i >= index - this.smoothingFactor; i--) { values[j++] = points.get(i); } return DoubleStream.of(values).sum() / (double) this.smoothingFactor; } public Double calculateRHSAverageValueAtPoint(List<Double> points, int index) { if (index + this.smoothingFactor >= points.size()) { return null; } int j = 0; double[] values = new double[smoothingFactor]; for (int i = index + 1; i <= index + smoothingFactor; i++) { values[j++] = points.get(i); } return DoubleStream.of(values).sum() / (double) this.smoothingFactor; } /** * find points where, looking forward/backwards and averaging, a reversal seems to have happened */ private List<Integer> findReversalIndexes(List<Double> points) { List<Integer> reversalIndexes = new ArrayList<>(); for (int i = 0; i < points.size(); i++) { Double lhsAverageValue = this.calculateLHSAverageValueAtPoint(points, i); if (lhsAverageValue == null) { continue; } Double rhsAverageValue = this.calculateRHSAverageValueAtPoint(points, i); if (rhsAverageValue == null) { continue; } double lhsSlope = (points.get(i) - lhsAverageValue) / this.smoothingFactor; double rhsSlope = (rhsAverageValue - points.get(i)) / this.smoothingFactor; if (this.isSupport) { if (lhsSlope < 0 && rhsSlope > 0) { reversalIndexes.add(i); } } else { if (lhsSlope > 0 && rhsSlope < 0) { reversalIndexes.add(i); } } } return reversalIndexes; } private Integer findIndexOfExtreme(List<Integer> indexes) { List<Double> points = indexes .stream() .map(i -> this.series.getBar(i)) .map(this::getPoint) .collect(Collectors.toList()); int extremeIndex = 0; for (int i = 1; i < points.size(); i++) { if (this.isSupport) { if (points.get(i) < points.get(extremeIndex)) { extremeIndex = i; } } else { if (points.get(i) > points.get(extremeIndex)) { extremeIndex = i; } } } return indexes.get(extremeIndex); } private List<Integer> findExtremeInClusteredReversal(List<Integer> reversalIndexes) { int clusterIndex = 0; List<List<Integer>> clusters = new ArrayList<>(); clusters.add(new ArrayList<>()); for (Integer index : reversalIndexes) { List<Integer> currentCluster = clusters.get(clusterIndex); // if this is the initial iteration, add to cluster if (clusterIndex == 0 && currentCluster.size() == 0) { currentCluster.add(index); continue; } Integer lastIndex = currentCluster.get(currentCluster.size() - 1); if (index - lastIndex <= this.clusterGap) { currentCluster.add(index); continue; } List<Integer> newCluster = new ArrayList<>(); newCluster.add(index); clusters.add(newCluster); clusterIndex++; } return clusters .stream() .map(this::findIndexOfExtreme) .collect(Collectors.toList()); } }
Java
CL
d6489bb55c034b5b567ceeb28a5a0a1971df7ba9c6748c36278f3ccd2e4de899
/* * Copyright (C) 2020 Florian Stober * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.codecrafter47.taboverlay.config.dsl.customplaceholder; import de.codecrafter47.taboverlay.config.context.Context; import de.codecrafter47.taboverlay.config.dsl.yaml.MarkedIntegerProperty; import de.codecrafter47.taboverlay.config.dsl.yaml.MarkedPropertyBase; import de.codecrafter47.taboverlay.config.placeholder.PlaceholderArg; import de.codecrafter47.taboverlay.config.placeholder.PlaceholderBuilder; import de.codecrafter47.taboverlay.config.template.TemplateCreationContext; import lombok.Getter; import lombok.Setter; import java.util.List; @Getter @Setter public abstract class CustomPlaceholderConfiguration extends MarkedPropertyBase { private MarkedIntegerProperty parameters = new MarkedIntegerProperty(0); public abstract PlaceholderBuilder<?, ?> bindArgs(PlaceholderBuilder<Context, ?> builder, List<PlaceholderArg> args, TemplateCreationContext tcc); String replaceParameters(String template, List<PlaceholderArg> args) { for (int i = 0; i < parameters.getValue(); i++) { StringBuilder replacement; if (i < args.size()) { replacement = new StringBuilder(args.get(i).getText()); if (i == parameters.getValue() - 1) { for (int j = i + 1; j < args.size(); j++) { replacement.append(" ").append(args.get(j).getText()); } } } else { replacement = new StringBuilder(); } template = template.replace("%" + i, replacement.toString()); } return template; } }
Java
CL
c5f643dd255b157fc83b64971446e937c543aa0185a90de547ec3a7834863ab6
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.transaction.itests; import static org.ops4j.pax.exam.CoreOptions.*; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption; import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.modifyBundle; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Customizer; import org.ops4j.pax.exam.Inject; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.container.def.options.VMOption; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.exam.options.BootClasspathLibraryOption; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.ops4j.pax.exam.options.MavenArtifactUrlReference; import org.ops4j.pax.exam.options.TimeoutOption; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.Version; import org.osgi.util.tracker.ServiceTracker; @RunWith(JUnit4TestRunner.class) public abstract class AbstractIntegrationTest { public static final long DEFAULT_TIMEOUT = 30000; private List<ServiceTracker> srs; @Before public void setUp() { srs = new ArrayList<ServiceTracker>(); } @After public void tearDown() throws Exception { closeServiceTrackers(); } private void closeServiceTrackers() { for (ServiceTracker st : srs) { if (st != null) { st.close(); } } } @Inject protected BundleContext bundleContext; @org.ops4j.pax.exam.junit.Configuration public static Option[] configuration() { Option[] options = options( bootDelegationPackages("javax.transaction", "javax.transaction.*"), vmOption("-Dorg.osgi.framework.system.packages=javax.accessibility,javax.activation,javax.activity,javax.annotation,javax.annotation.processing,javax.crypto,javax.crypto.interfaces,javax.crypto.spec,javax.imageio,javax.imageio.event,javax.imageio.metadata,javax.imageio.plugins.bmp,javax.imageio.plugins.jpeg,javax.imageio.spi,javax.imageio.stream,javax.jws,javax.jws.soap,javax.lang.model,javax.lang.model.element,javax.lang.model.type,javax.lang.model.util,javax.management,javax.management.loading,javax.management.modelmbean,javax.management.monitor,javax.management.openmbean,javax.management.relation,javax.management.remote,javax.management.remote.rmi,javax.management.timer,javax.naming,javax.naming.directory,javax.naming.event,javax.naming.ldap,javax.naming.spi,javax.net,javax.net.ssl,javax.print,javax.print.attribute,javax.print.attribute.standard,javax.print.event,javax.rmi,javax.rmi.CORBA,javax.rmi.ssl,javax.script,javax.security.auth,javax.security.auth.callback,javax.security.auth.kerberos,javax.security.auth.login,javax.security.auth.spi,javax.security.auth.x500,javax.security.cert,javax.security.sasl,javax.sound.midi,javax.sound.midi.spi,javax.sound.sampled,javax.sound.sampled.spi,javax.sql,javax.sql.rowset,javax.sql.rowset.serial,javax.sql.rowset.spi,javax.swing,javax.swing.border,javax.swing.colorchooser,javax.swing.event,javax.swing.filechooser,javax.swing.plaf,javax.swing.plaf.basic,javax.swing.plaf.metal,javax.swing.plaf.multi,javax.swing.plaf.synth,javax.swing.table,javax.swing.text,javax.swing.text.html,javax.swing.text.html.parser,javax.swing.text.rtf,javax.swing.tree,javax.swing.undo,javax.tools,javax.xml,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.bind.util,javax.xml.crypto,javax.xml.crypto.dom,javax.xml.crypto.dsig,javax.xml.crypto.dsig.dom,javax.xml.crypto.dsig.keyinfo,javax.xml.crypto.dsig.spec,javax.xml.datatype,javax.xml.namespace,javax.xml.parsers,javax.xml.soap,javax.xml.stream,javax.xml.stream.events,javax.xml.stream.util,javax.xml.transform,javax.xml.transform.dom,javax.xml.transform.sax,javax.xml.transform.stax,javax.xml.transform.stream,javax.xml.validation,javax.xml.ws,javax.xml.ws.handler,javax.xml.ws.handler.soap,javax.xml.ws.http,javax.xml.ws.soap,javax.xml.ws.spi,javax.xml.xpath,org.ietf.jgss,org.omg.CORBA,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA.TypeCodePackage,org.omg.CORBA.portable,org.omg.CORBA_2_3,org.omg.CORBA_2_3.portable,org.omg.CosNaming,org.omg.CosNaming.NamingContextExtPackage,org.omg.CosNaming.NamingContextPackage,org.omg.Dynamic,org.omg.DynamicAny,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage,org.omg.IOP,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage,org.omg.Messaging,org.omg.PortableInterceptor,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.PortableServer,org.omg.PortableServer.CurrentPackage,org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.ServantLocatorPackage,org.omg.PortableServer.portable,org.omg.SendingContext,org.omg.stub.java.rmi,org.w3c.dom,org.w3c.dom.bootstrap,org.w3c.dom.css,org.w3c.dom.events,org.w3c.dom.html,org.w3c.dom.ls,org.w3c.dom.ranges,org.w3c.dom.stylesheets,org.w3c.dom.traversal,org.w3c.dom.views,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers,javax.transaction;partial=true;mandatory:=partial,javax.transaction.xa;partial=true;mandatory:=partial"), // Log mavenBundle("org.ops4j.pax.logging", "pax-logging-api"), mavenBundle("org.ops4j.pax.logging", "pax-logging-service"), // this is how you set the default log level when using pax // logging (logProfile) systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG"), // Bundles mavenBundle("org.osgi", "org.osgi.compendium"), mavenBundle("asm", "asm-all"), mavenBundle("org.apache.derby", "derby"), mavenBundle("org.apache.aries", "org.apache.aries.util"), mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint"), mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.manager"), mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.blueprint"), mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.wrappers"), mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.testbundle"), mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.testds"), //new VMOption( "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000" ), //new TimeoutOption( 0 ), equinox().version("3.5.0")); options = updateOptions(options); return options; } protected static MavenArtifactProvisionOption mavenBundle(String groupId, String artifactId) { return CoreOptions.mavenBundle().groupId(groupId).artifactId(artifactId) .versionAsInProject(); } protected Bundle getBundle(String symbolicName) { return getBundle(symbolicName, null); } protected Bundle getBundle(String bundleSymbolicName, String version) { Bundle result = null; for (Bundle b : bundleContext.getBundles()) { if (b.getSymbolicName().equals(bundleSymbolicName)) { if (version == null || b.getVersion().equals(Version.parseVersion(version))) { result = b; break; } } } return result; } protected static Option[] updateOptions(Option[] options) { // We need to add pax-exam-junit here when running with the ibm // jdk to avoid the following exception during the test run: // ClassNotFoundException: org.ops4j.pax.exam.junit.Configuration if ("IBM Corporation".equals(System.getProperty("java.vendor"))) { Option[] ibmOptions = options(wrappedBundle(mavenBundle( "org.ops4j.pax.exam", "pax-exam-junit"))); options = combine(ibmOptions, options); } return options; } protected <T> T getOsgiService(Class<T> type, long timeout) { return getOsgiService(type, null, timeout); } protected <T> T getOsgiService(Class<T> type) { return getOsgiService(type, null, DEFAULT_TIMEOUT); } protected <T> T getOsgiService(Class<T> type, String filter, long timeout) { return getOsgiService(null, type, filter, timeout); } protected <T> T getOsgiService(BundleContext bc, Class<T> type, String filter, long timeout) { // close out all service trackers closeServiceTrackers(); ServiceTracker tracker = null; try { String flt; if (filter != null) { if (filter.startsWith("(")) { flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")"; } else { flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))"; } } else { flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")"; } Filter osgiFilter = FrameworkUtil.createFilter(flt); tracker = new ServiceTracker(bc == null ? bundleContext : bc, osgiFilter, null); tracker.open(); // add tracker to the list of trackers we close at tear down srs.add(tracker); Object svc = type.cast(tracker.waitForService(timeout)); if (svc == null) { throw new RuntimeException("Gave up waiting for service " + flt); } return type.cast(svc); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException("Invalid filter", e); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
Java
CL
57adc2dabcb4d30d7ca79b698a4931d3a7b55f16ffa7bf23a1ed1bf1f9810ab8
package com.example.gszzz.attendclass; import android.app.PendingIntent; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public class ScannerService extends Service { //Constants private static final int FOREGROUND_NOTIFICATION_ID = 1333; /** * A global variable to let AdvertiserFragment check if the Service is running without needing * to start or bind to it. * This is the best practice method as defined here: * https://groups.google.com/forum/#!topic/android-developers/jEvXMWgbgzE */ protected static boolean running = false; private ArrayList<ScanResult> scanResults; protected static final String NEW_DEVICE_FOUND = "ble_new_device_found"; protected static final String SCANNING_FAILED = "com.example.gszzz.attendclass.scanning_failed"; protected static final String SCANNING_FAILED_EXTRA_CODE = "failureCode"; protected static final int SCANNING_TIMED_OUT = 6; protected static final String PARCELABLE_SCANRESULTS = "ParcelScanResults"; protected static final String TAG = "ScannerService"; private static int powerLevel; private BluetoothLeScanner mBluetoothLeScanner; private ScanCallback mScanCallback; private Handler mHandler; private Runnable timeoutRunnable; /** * Length of time to allow advertising before automatically shutting off. */ private long TIMEOUT = TimeUnit.MILLISECONDS.convert(Constants.CLASS_DURATION, TimeUnit.MINUTES); @Override public void onCreate() { running = true; // scanResults = new ArrayList<>(); initialize(); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { scanResults = new ArrayList<>(); powerLevel = intent.getIntExtra("power", 2); startScanning(); return super.onStartCommand(intent, flags, startId); } private void startScanning() { goForeground(); if (mScanCallback == null) { //set timeout for scanning setTimeout(); //start a new scan mScanCallback = new SampleScanCallback(); mBluetoothLeScanner.startScan(buildScanFilters(), buildScanSettings(), mScanCallback); Toast.makeText(getApplicationContext(), "Scan frequency: " + buildScanSettings().getScanMode(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), R.string.scanning_already_started, Toast.LENGTH_SHORT).show(); } } @Override public void onDestroy() { running = false; stopScanning(); mHandler.removeCallbacks(timeoutRunnable); stopForeground(true); //Toast.makeText(getApplicationContext(), "Scanning stopped...", Toast.LENGTH_SHORT).show(); super.onDestroy(); } /** * Custom ScanCallback object - adds to adapter on success, displays error on failure. */ private class SampleScanCallback extends ScanCallback { @Override public void onBatchScanResults(List<ScanResult> results) { super.onBatchScanResults(results); for (ScanResult result : results) { addScanResult(result); } // Toast.makeText(getApplicationContext(), "Multiple new devices detected... (" + scanResults.size() + ")", Toast.LENGTH_SHORT).show(); Intent newDeviceFoundIntent = new Intent(); newDeviceFoundIntent.setAction(NEW_DEVICE_FOUND); newDeviceFoundIntent.putParcelableArrayListExtra(PARCELABLE_SCANRESULTS, scanResults); sendBroadcast(newDeviceFoundIntent); } @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); //add to the scanResults list addScanResult(result); Intent newDeviceFoundIntent = new Intent(); newDeviceFoundIntent.setAction(NEW_DEVICE_FOUND); newDeviceFoundIntent.putParcelableArrayListExtra(PARCELABLE_SCANRESULTS, scanResults); sendBroadcast(newDeviceFoundIntent); } @Override public void onScanFailed(int errorCode) { super.onScanFailed(errorCode); Toast.makeText(getApplicationContext(), "Scan failed with error: " + errorCode, Toast.LENGTH_SHORT) .show(); } } private void addScanResult(ScanResult result) { int existingPosition = getPosition(result.getDevice().getAddress()); if (existingPosition >= 0) { // Device is already in list, update its record. scanResults.set(existingPosition, result); } else { // Add new Device's ScanResult to list. scanResults.add(result); } } /** * Search the adapter for an existing device address and return it, otherwise return -1. */ private int getPosition(String address) { int position = -1; for (int i = 0; i < scanResults.size(); i++) { if (scanResults.get(i).getDevice().getAddress().equals(address)) { position = i; break; } } return position; } /** * Return a List of {@link ScanFilter} objects to filter by Service UUID. */ private List<ScanFilter> buildScanFilters() { List<ScanFilter> scanFilters = new ArrayList<>(); ScanFilter.Builder builder = new ScanFilter.Builder(); // Comment out the below line to see all BLE devices around you builder.setServiceUuid(Constants.Service_UUID); scanFilters.add(builder.build()); return scanFilters; } /** * Return a {@link ScanSettings} object set to use low power (to preserve battery life). */ private ScanSettings buildScanSettings() { ScanSettings.Builder builder = new ScanSettings.Builder(); switch (powerLevel) { case 0: builder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER); Log.i(TAG, "mode is 0, low power"); break; case 1: builder.setScanMode(ScanSettings.SCAN_MODE_BALANCED); Log.i(TAG, "mode is 1, balanced"); break; case 2: builder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY); Log.i(TAG, "mode is 2, high power"); break; } return builder.build(); } /** * Move service to the foreground, to avoid execution limits on background processes. * * Callers should call stopForeground(true) when background work is complete. */ private void goForeground() { Intent notificationIntent = new Intent(this, AttendanceTaking.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setContentTitle("Scanning students' devices") .setContentText("Student name list will be updated once found...") .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pendingIntent); startForeground(FOREGROUND_NOTIFICATION_ID, builder.build()); } private void stopScanning() { //Toast.makeText(getApplicationContext(), "Stopping scanning...", Toast.LENGTH_SHORT).show(); //Stop the scan, wipe the callback. mBluetoothLeScanner.stopScan(mScanCallback); mScanCallback = null; //TODO: Update name list?? } private void setTimeout() { mHandler = new Handler(); timeoutRunnable = new Runnable() { @Override public void run() { sendFailureIntent(SCANNING_TIMED_OUT); stopSelf(); } }; mHandler.postDelayed(timeoutRunnable, TIMEOUT); } /** * Builds and sends a broadcast intent indicating Advertising has failed. Includes the error * code as an extra. This is intended to be picked up by the {@code AdvertiserFragment}. */ private void sendFailureIntent(int errorCode) { Intent failureIntent = new Intent(); failureIntent.setAction(SCANNING_FAILED); failureIntent.putExtra(SCANNING_FAILED_EXTRA_CODE, errorCode); sendBroadcast(failureIntent); } /** * Get references to system Bluetooth objects if we don't have them already. */ private void initialize() { if (mBluetoothLeScanner == null) { BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); if (mBluetoothManager !=null) { BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter(); if (mBluetoothAdapter != null) { // Log.i(TAG, "before got scanner"); mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); // Log.i(TAG, "got scanner"); } else { Toast.makeText(this, R.string.bluetooth_not_supported, Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, R.string.bluetooth_not_supported, Toast.LENGTH_LONG).show(); } } } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } }
Java
CL
0c1675248cc7e262a2c350a79e8c6918368b9ba28bf3dfcfd856fe2a1a490c6e
package com.jyss.ziwei.action; import com.jyss.ziwei.entity.ResponseResult; import com.jyss.ziwei.entity.UserDevices; import com.jyss.ziwei.service.UserDevicesService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/user") public class UserDevicesAction { @Autowired private UserDevicesService udService; /** * 添加设备 * @param token * @param ud * @return */ @RequestMapping("/addDevice") @ResponseBody public ResponseResult addDevice(@RequestParam("token") String token, UserDevices ud) { return udService.addDevice(token,ud); } /** * 修改设备 * @param token * @param ud * @return */ @RequestMapping("/upDevice") @ResponseBody public ResponseResult upDevice(@RequestParam("token") String token, UserDevices ud) { return udService.upDevice(token,ud); } /** * 删除设备 * @param token * @param udId * @return */ @RequestMapping("/delDevice") @ResponseBody public ResponseResult delDevice(@RequestParam("token") String token, @RequestParam("udId") String udId) { return udService.delDevice(token,udId); } /** * 获取我的设备 * @param token * @return */ @RequestMapping("/getMyDevice") @ResponseBody public ResponseResult getMyDevice(@RequestParam("token") String token) { return udService.getMyDevice(token); } }
Java
CL
899b15dc69207ec1cafeb06d08cc814c45f9f47749bbf0b66e9725968f10e5a9
package com.huhuo.cmcar.cartype; import java.io.OutputStream; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang.exception.ExceptionUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.huhuo.carservicecore.cust.car.ModelCarType; import com.huhuo.carservicecore.cust.car.ModelChargeStandard; import com.huhuo.integration.base.BaseCtrl; import com.huhuo.integration.db.mysql.Condition; import com.huhuo.integration.db.mysql.Dir; import com.huhuo.integration.db.mysql.Order; import com.huhuo.integration.db.mysql.Page; import com.huhuo.integration.exception.HuhuoException; import com.huhuo.integration.web.Message; import com.huhuo.integration.web.Message.Status; @Controller("cmcarCtrlCarType") @RequestMapping(value="/cmcar/cartype") public class CtrlCarType extends BaseCtrl { protected String basePath = "/car-module-car"; @Resource(name = "cmcarServCarType") private IServCarType iservCarType; @Resource(name = "cmcarServChargeStandards") private IServChargeStandard iServChargeStandard; /************************************************************* * car type management *************************************************************/ @RequestMapping(value="/index.do") public String index(Model model) { // car type management page logger.debug("---> access car type management page"); Condition<ModelCarType> condition = new Condition<ModelCarType>(); condition.setOrderList(new Order("createTime", Dir.DESC), new Order("updateTime", Dir.DESC)); condition.setPage(new Page(0, 20)); List<ModelCarType> list = iservCarType.findByCondition(condition, true); model.addAttribute("list", list); return basePath + "/cartype/index"; } @RequestMapping(value="/condition/get.do") public String get(Model model, Condition<ModelCarType> condition, ModelCarType t){ try { condition.setT(t); condition.setOrderList(new Order("createTime", Dir.DESC), new Order("updateTime", Dir.DESC)); logger.debug("---> server receive: condition={}", condition); List<ModelCarType> records = iservCarType.findByCondition(condition); // write(ExtUtils.getJsonStore(records, records.size()), out); model.addAttribute("records", records); } catch (HuhuoException e) { logger.warn(e.getMessage()); model.addAttribute("msg", new Message<String>(Status.FAILURE, e.getMessage())); } catch (Exception e) { logger.error(ExceptionUtils.getFullStackTrace(e)); model.addAttribute("msg", new Message<String>(Status.ERROR, e.getMessage())); } return basePath + "/cartype/grid-condition"; } @RequestMapping(value="/add-ui.do") public String addUI(Model model) { logger.debug("==> access add ui"); return basePath + "/cartype/edit-ui"; } @RequestMapping(value="/add.do") public void huhuoForm(ModelCarType carType, ModelChargeStandard chargeStandard, OutputStream out){ try { logger.debug("---> server receive: carType={}, chargeStandard={}", carType, chargeStandard); // add charge standard chargeStandard.setStatus(1); chargeStandard.setCreateTime(new Date()); chargeStandard.setUpdateTime(new Date()); iServChargeStandard.add(chargeStandard); carType.setChargeStandardId(chargeStandard.getId()); // add car type carType.setStatus(1); carType.setCreateTime(new Date()); carType.setUpdateTime(new Date()); iservCarType.add(carType); write(new Message<ModelCarType>(Status.SUCCESS, "add new cartype success!", carType), out); } catch (HuhuoException e) { logger.warn(e.getMessage()); write(new Message<String>(Status.FAILURE, e.getMessage()), out); } catch (Exception e) { logger.error(ExceptionUtils.getFullStackTrace(e)); write(new Message<String>(Status.ERROR, e.getMessage()), out); } } }
Java
CL
9403b8d685b9a8771e98a99765128494cc59081e84458ef7fc785e4a3d47ca8a
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.accumulo.core.iteratorsImpl.system; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.accumulo.core.client.SampleNotPresentException; import org.apache.accumulo.core.data.ByteSequence; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.iterators.IteratorEnvironment; import org.apache.accumulo.core.iterators.SortedKeyValueIterator; /** * A simple iterator over a Java SortedMap * * Note that this class is intended as an in-memory replacement for RFile$Reader, so its behavior * reflects the same assumptions; namely, that this iterator is not responsible for respecting the * columnFamilies passed into seek(). If you want a Map-backed Iterator that returns only sought * CFs, construct a new ColumnFamilySkippingIterator(new SortedMapIterator(map)). * * @see ColumnFamilySkippingIterator */ public class SortedMapIterator implements InterruptibleIterator { private Iterator<Entry<Key,Value>> iter; private Entry<Key,Value> entry; private SortedMap<Key,Value> map; private Range range; private AtomicBoolean interruptFlag; private int interruptCheckCount = 0; @Override public SortedMapIterator deepCopy(IteratorEnvironment env) { if (env != null && env.isSamplingEnabled()) { throw new SampleNotPresentException(); } return new SortedMapIterator(map, interruptFlag); } private SortedMapIterator(SortedMap<Key,Value> map, AtomicBoolean interruptFlag) { this.map = map; iter = null; this.range = new Range(); entry = null; this.interruptFlag = interruptFlag; } public SortedMapIterator(SortedMap<Key,Value> map) { this(map, null); } @Override public Key getTopKey() { return entry.getKey(); } @Override public Value getTopValue() { return entry.getValue(); } @Override public boolean hasTop() { return entry != null; } @Override public void next() throws IOException { if (entry == null) { throw new IllegalStateException(); } if (interruptFlag != null && interruptCheckCount++ % 100 == 0 && interruptFlag.get()) { throw new IterationInterruptedException(); } if (iter.hasNext()) { entry = iter.next(); if (range.afterEndKey(entry.getKey())) { entry = null; } } else { entry = null; } } @Override public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException { if (interruptFlag != null && interruptFlag.get()) { throw new IterationInterruptedException(); } this.range = range; Key key = range.getStartKey(); if (key == null) { key = new Key(); } iter = map.tailMap(key).entrySet().iterator(); if (iter.hasNext()) { entry = iter.next(); if (range.afterEndKey(entry.getKey())) { entry = null; } } else { entry = null; } while (hasTop() && range.beforeStartKey(getTopKey())) { next(); } } @Override public void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env) throws IOException { throw new UnsupportedOperationException(); } @Override public void setInterruptFlag(AtomicBoolean flag) { this.interruptFlag = flag; } }
Java
CL
f571fe7c83d8edb82d0cca3fb7800e76aedf781fb79cea490a5942a85f80a7c6
package edu.uams.clara.webapp.protocol.web.ajax; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.xpath.XPathExpressionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; 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 org.xml.sax.SAXException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import com.google.common.collect.Lists; import edu.uams.clara.webapp.common.dao.usercontext.UserDao; import edu.uams.clara.webapp.common.domain.usercontext.User; import edu.uams.clara.webapp.common.objectwrapper.PagedList; import edu.uams.clara.webapp.common.util.JsonResponseHelper; import edu.uams.clara.webapp.common.util.response.JsonResponse; import edu.uams.clara.webapp.contract.domain.Contract; import edu.uams.clara.webapp.protocol.dao.ProtocolDao; import edu.uams.clara.webapp.protocol.dao.search.ProtocolSearchBookmarkDao; import edu.uams.clara.webapp.protocol.dao.thing.GrantDao; import edu.uams.clara.webapp.protocol.domain.Protocol; import edu.uams.clara.webapp.protocol.domain.search.ProtocolSearchBookmark; import edu.uams.clara.webapp.protocol.domain.thing.Grant; import edu.uams.clara.webapp.protocol.objectwrapper.ProtocolSearchCriteria; import edu.uams.clara.webapp.xml.processor.XmlProcessor; @Controller public class ProtocolListAjaxController { private final static Logger logger = LoggerFactory .getLogger(ProtocolListAjaxController.class); private ProtocolDao protocolDao; private GrantDao grantDao; private ProtocolSearchBookmarkDao protocolSearchBookmarkDao; private UserDao userDao; private XmlProcessor xmlProcessor; private static final int PAGE_SIZE = 20; private ObjectMapper objectMapper = new ObjectMapper(); /** * reading protocol meta data from metaDataXml in protocol object * * @param start * @param limit * @param fields * @param query * @return * @throws XPathExpressionException * @throws SAXException * @throws IOException */ //@TODO @Cacheable @RequestMapping(value = "/ajax/protocols/list.xml", method = RequestMethod.POST) public @ResponseBody String listProtocols( @RequestParam(value = "start", required = false) Integer start, @RequestParam(value = "limit", required = false) Integer limit, @RequestParam(value = "keyword", required = false) String quickSearchKeyword, @RequestParam(value = "searchCriterias", required = false) String searchCriteriasJsonString ) //@RequestParam(value = "searchCriterias[]", required = false) List<ProtocolSearchCriteria> searchCriterias throws XPathExpressionException, SAXException, IOException { int s = start == null ? 0 : start; int l = limit == null ? PAGE_SIZE : limit; User u = (User) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); //for (GrantedAuthority p:u.getAuthorities()){ //logger.debug("p: " + (Permission)p); //} PagedList<Protocol> pagedProtocolMetaDatas = null; List<ProtocolSearchCriteria> searchCriterias = null; boolean quickSearch = false; if (quickSearchKeyword != null && (searchCriteriasJsonString == null || searchCriteriasJsonString.isEmpty())){ quickSearchKeyword = quickSearchKeyword.trim(); searchCriteriasJsonString = "[{\"searchField\":\"TITLE\",\"searchOperator\":\"CONTAINS\",\"keyword\":\""+quickSearchKeyword+"\"}, {\"searchField\":\"IDENTIFIER\",\"searchOperator\":\"CONTAINS\",\"keyword\":\""+quickSearchKeyword+"\"}]"; quickSearch = true; } if(searchCriteriasJsonString != null && searchCriteriasJsonString.length() > 0){ logger.debug("searchCriteriasJsonString :" + searchCriteriasJsonString); try { JavaType listOfProtocolSearchCriteria = TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, ProtocolSearchCriteria.class); searchCriterias = objectMapper.readValue(searchCriteriasJsonString, listOfProtocolSearchCriteria); } catch (Exception e) { e.printStackTrace(); } //ProtocolSearchCriteria protocolSearchCriteria = objectMapper.readValue(searchCriteriasJsonString, ProtocolSearchCriteria.class); //logger.debug("ProtocolSearchCriteria: " + protocolSearchCriteria.getSearchField()); } pagedProtocolMetaDatas = protocolDao .listPagedProtocolMetaDatasByUserAndSearchCriteriaAndProtocolStatusFilter( u, s, l, searchCriterias, quickSearch); String finalResultXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><list total=\"" + pagedProtocolMetaDatas.getTotal() + "\">"; if (pagedProtocolMetaDatas.getList() != null && !pagedProtocolMetaDatas.getList().isEmpty()) { for (Protocol p : pagedProtocolMetaDatas.getList()) { //logger.debug("" + p.getId()); finalResultXml += (p.getMetaDataXml() != null ? p .getMetaDataXml() : ""); } } finalResultXml += "</list>"; /* String convertedString = Normalizer .normalize(finalResultXml, Normalizer.Form.NFD) .replaceAll("[^\\p{ASCII}]", "");*/ //return new StringHelper().convertToAscii(finalResultXml,true); return finalResultXml; } @RequestMapping(value = "/ajax/protocols/search-bookmarks/export", method = RequestMethod.POST) public @ResponseBody String exportBookmakrSearch( @RequestParam(value = "searchCriterias", required = false) String searchCriteriasJsonString ) //@RequestParam(value = "searchCriterias[]", required = false) List<ProtocolSearchCriteria> searchCriterias throws XPathExpressionException, SAXException, IOException { User u = (User) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); PagedList<Protocol> pagedProtocolMetaDatas = null; List<ProtocolSearchCriteria> searchCriterias = null; boolean quickSearch = false; if(searchCriteriasJsonString != null && searchCriteriasJsonString.length() > 0){ logger.debug("searchCriteriasJsonString :" + searchCriteriasJsonString); try { JavaType listOfProtocolSearchCriteria = TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, ProtocolSearchCriteria.class); searchCriterias = objectMapper.readValue(searchCriteriasJsonString, listOfProtocolSearchCriteria); } catch (Exception e) { e.printStackTrace(); } //ProtocolSearchCriteria protocolSearchCriteria = objectMapper.readValue(searchCriteriasJsonString, ProtocolSearchCriteria.class); //logger.debug("ProtocolSearchCriteria: " + protocolSearchCriteria.getSearchField()); } pagedProtocolMetaDatas = protocolDao .listPagedProtocolMetaDatasByUserAndSearchCriteriaAndProtocolStatusFilter( u, 0, protocolDao.listProtocolsByUser(u).size(), searchCriterias, quickSearch); String finalResultXml = "<list>"; if (pagedProtocolMetaDatas.getList() != null && !pagedProtocolMetaDatas.getList().isEmpty()) { for (Protocol p : pagedProtocolMetaDatas.getList()) { //logger.debug("" + p.getId()); finalResultXml += (p.getMetaDataXml() != null ? p .getMetaDataXml() : ""); } } finalResultXml += "</list>"; String fileUrl = protocolDao.exportBookmarkSearchResultFile(finalResultXml,u); return fileUrl; } @RequestMapping(value = "/ajax/protocols/search-bookmarks/save", method = RequestMethod.POST) public @ResponseBody JsonResponse saveProtocolSearchBookmarks( @RequestParam(value = "userId") long userId, @RequestParam(value = "name") String name, @RequestParam(value = "searchCriterias") String searchCriterias) { // User u = // (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); try { User u = userDao.findById(userId); ProtocolSearchBookmark protocolSearchBookmark = new ProtocolSearchBookmark(); protocolSearchBookmark.setName(name); protocolSearchBookmark.setSearchCriterias(searchCriterias); protocolSearchBookmark.setUser(u); protocolSearchBookmark = protocolSearchBookmarkDao .saveOrUpdate(protocolSearchBookmark); return new JsonResponse(false); } catch (Exception ex) { ex.printStackTrace(); logger.info("bookmark", ex); return new JsonResponse(true, "Saving search bookmarks is encounting an error!", "", false, null); } } @RequestMapping(value = "/ajax/protocols/search-bookmarks/{searchBookmarkId}/update", method = RequestMethod.POST) public @ResponseBody JsonResponse updateProtocolSearchBookmarks( @PathVariable(value = "searchBookmarkId") long searchBookmarkId, @RequestParam(value = "userId") long userId, @RequestParam(value = "name") String name, @RequestParam(value = "searchCriterias") String searchCriterias) { try { ProtocolSearchBookmark protocolSearchBookmark = protocolSearchBookmarkDao.findById(searchBookmarkId); protocolSearchBookmark.setName(name); protocolSearchBookmark.setSearchCriterias(searchCriterias); protocolSearchBookmark = protocolSearchBookmarkDao .saveOrUpdate(protocolSearchBookmark); return new JsonResponse(false); } catch (Exception ex) { ex.printStackTrace(); logger.info("bookmark", ex); return new JsonResponse(true, "Failed to update bookmark!", "", false, null); } } @RequestMapping(value = "/ajax/protocols/search-bookmarks/{id}/remove", method = RequestMethod.POST) public @ResponseBody JsonResponse removeProtocolSearchBookmarks( @PathVariable("id") long id, @RequestParam(value = "userId") long userId) { // User u = // (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); try { //User u = userDao.findById(userId);//for audit... ProtocolSearchBookmark protocolSearchBookmark = protocolSearchBookmarkDao.findById(id); protocolSearchBookmark.setRetired(true); protocolSearchBookmark = protocolSearchBookmarkDao .saveOrUpdate(protocolSearchBookmark); logger.debug("id: " + id); return new JsonResponse(false); } catch (Exception ex) { ex.printStackTrace(); return new JsonResponse(true, "Removing search bookmarks is encounting an error!", "", false, null); } } private ProtocolSearchBookmark newCommonBookmark(long id, String name, String searchCriterias){ ProtocolSearchBookmark bookmark = new ProtocolSearchBookmark(); bookmark.setId(id);// common bookmark all have id <= 0 to avoid conflict with bookmarks from db. bookmark.setName(name); bookmark.setSearchCriterias(searchCriterias); return bookmark; } @RequestMapping(value = "/ajax/protocols/search-bookmarks/list", method = RequestMethod.GET) public @ResponseBody Map<String, List<ProtocolSearchBookmark>> listProtocolSearchBookmarks( @RequestParam(value = "userId") long userId) { Map<String, List<ProtocolSearchBookmark>> protocolSearchBookmarks = new HashMap<String, List<ProtocolSearchBookmark>>(0); try { List<ProtocolSearchBookmark> protocolSearchBookmarkList = Lists.newArrayList(); protocolSearchBookmarkList.add(newCommonBookmark(-2, "All protocols", null)); protocolSearchBookmarkList.add(newCommonBookmark(-1, "My protocols", "[{\"searchField\":\"MY_PROTOCOLS\",\"searchOperator\":\"IS\",\"keyword\":\"true\"}]")); protocolSearchBookmarkList.add(newCommonBookmark(0, "My protocols - PI Action Needed", "[{\"searchField\":\"PENDING_PI_ACTION\",\"searchOperator\":\"IS\",\"keyword\":\"true\"}]")); protocolSearchBookmarkList.addAll(protocolSearchBookmarkDao.listSearchBookmarksByUserId(userId)); protocolSearchBookmarks.put("bookmarks", protocolSearchBookmarkList); } catch (Exception ex) { ex.printStackTrace(); } return protocolSearchBookmarks; } @RequestMapping(value = "/ajax/protocols/related-contract/list.xml", method = RequestMethod.GET) public @ResponseBody String listRelatedContract( @RequestParam(value = "protocolId", required = true) long protocolId, @RequestParam(value = "start", required = false) Integer start, @RequestParam(value = "limit", required = false) Integer limit ) throws XPathExpressionException, SAXException, IOException { int s = start == null ? 0 : start; int l = limit == null ? PAGE_SIZE : limit; User u = (User) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); PagedList<Contract> pagedContractMetaDatas = protocolDao.listPagedContractMetaDatasByUserAndProtocolId(u, s, l, protocolId); String finalResultXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><list total=\"" + pagedContractMetaDatas.getTotal() + "\">"; if (pagedContractMetaDatas.getList() != null && !pagedContractMetaDatas.getList().isEmpty()) { for (Contract c : pagedContractMetaDatas.getList()) { logger.debug("" + c.getId()); finalResultXml += (c.getMetaDataXml() != null ? c .getMetaDataXml() : ""); } } finalResultXml += "</list>"; return finalResultXml; } @RequestMapping(value = "/ajax/protocols/related-grant/list", method = RequestMethod.GET, produces="application/json") public @ResponseBody JsonResponse listRelatedGrant( @RequestParam(value = "protocolId", required = true) long protocolId) { try { List<Grant> pagedGrant = grantDao.listRelatedGrantByProtocolId(protocolId); return JsonResponseHelper.newDataResponseStub(pagedGrant); } catch (Exception e) { e.printStackTrace(); return JsonResponseHelper.newDataResponseStub(Lists.newArrayList()); } } @Autowired(required = true) public void setProtocolDao(ProtocolDao protocolDao) { this.protocolDao = protocolDao; } public ProtocolDao getProtocolDao() { return protocolDao; } @Autowired(required = true) public void setXmlProcessor(XmlProcessor xmlProcessor) { this.xmlProcessor = xmlProcessor; } public XmlProcessor getXmlProcessor() { return xmlProcessor; } public ProtocolSearchBookmarkDao getProtocolSearchBookmarkDao() { return protocolSearchBookmarkDao; } @Autowired(required = true) public void setProtocolSearchBookmarkDao( ProtocolSearchBookmarkDao protocolSearchBookmarkDao) { this.protocolSearchBookmarkDao = protocolSearchBookmarkDao; } public UserDao getUserDao() { return userDao; } @Autowired(required = true) public void setUserDao(UserDao userDao) { this.userDao = userDao; } public GrantDao getGrantDao() { return grantDao; } @Autowired(required = true) public void setGrantDao(GrantDao grantDao) { this.grantDao = grantDao; } }
Java
CL
18bcee2e5798b12a34945fecfaac35ceec2fc5a967323b9bd615f2b427d12c80
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.itest.springboot.util; import java.io.File; import java.io.FileWriter; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.camel.itest.springboot.ITestConfig; import org.apache.camel.itest.springboot.ITestConfigBuilder; import org.apache.camel.itest.springboot.arquillian.SpringBootZipExporterImpl; import org.apache.commons.io.IOUtils; import org.jboss.arquillian.container.se.api.ClassPath; import org.jboss.arquillian.core.spi.InvocationException; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.Configuration; import org.jboss.shrinkwrap.api.ConfigurationBuilder; import org.jboss.shrinkwrap.api.Domain; import org.jboss.shrinkwrap.api.ExtensionLoader; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset; import org.jboss.shrinkwrap.api.asset.FileAsset; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.impl.base.ServiceExtensionLoader; import org.jboss.shrinkwrap.impl.base.URLPackageScanner; import org.jboss.shrinkwrap.impl.base.asset.AssetUtil; import org.jboss.shrinkwrap.impl.base.path.BasicPath; import org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.jboss.shrinkwrap.resolver.api.maven.MavenResolvedArtifact; import org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage; import org.jboss.shrinkwrap.resolver.api.maven.ScopeType; import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate; import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinates; import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencies; import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency; import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencyExclusion; /** * Packages a module in a spring-boot compatible nested-jar structure. */ public final class ArquillianPackager { /** * Spring-boot 1.4+ packaging model */ private static final String LIB_FOLDER = "/BOOT-INF/lib"; private static final String CLASSES_FOLDER = "BOOT-INF/classes"; private static final Pattern PROP_PATTERN = Pattern.compile("(\\$\\{[^}]*})"); private ArquillianPackager() { } public static Archive<?> springBootPackage(ITestConfig config) throws Exception { if (!new File(".").getCanonicalFile().getName().equals("camel-itest-spring-boot")) { throw new IllegalStateException("In order to run the integration tests, 'camel-itest-spring-boot' must be the working directory. Check your configuration."); } ExtensionLoader extensionLoader = new ServiceExtensionLoader(Collections.singleton(getExtensionClassloader())); extensionLoader.addOverride(ZipExporter.class, SpringBootZipExporterImpl.class); ConfigurationBuilder builder = new ConfigurationBuilder().extensionLoader(extensionLoader); Configuration conf = builder.build(); Domain domain = ShrinkWrap.createDomain(conf); JavaArchive ark = domain.getArchiveFactory().create(JavaArchive.class, "test.jar"); ark = ark.addAsManifestResource("BOOT-MANIFEST.MF", "MANIFEST.MF"); ark = ark.addAsDirectories(LIB_FOLDER); ark = ark.addAsDirectories(CLASSES_FOLDER); if (config.getUseCustomLog()) { // Spring loads logback-spring not spring-logback ark = ark.addAsResource("logback-spring.xml", CLASSES_FOLDER + "/logback-spring.xml"); } for (Map.Entry<String, String> res : config.getResources().entrySet()) { ark = ark.addAsResource(res.getKey(), CLASSES_FOLDER + "/" + res.getValue()); } String version = System.getProperty("version_org.apache.camel:camel-core"); if (version == null) { version = config.getMavenVersion(); } if (version == null) { // It is missing when launching from IDE PomEquippedResolveStage pom = resolver(config).loadPomFromFile("pom.xml"); MavenResolvedArtifact[] resolved = pom.importCompileAndRuntimeDependencies().resolve().withoutTransitivity().asResolvedArtifact(); for (MavenResolvedArtifact dep : resolved) { if (dep.getCoordinate().getGroupId().equals("org.apache.camel.springboot")) { version = dep.getCoordinate().getVersion(); break; } } } debug(config, "Resolved version: " + version); if (version == null) { throw new IllegalStateException("Cannot determine the current version of the camel component"); } List<MavenDependencyExclusion> commonExclusions = new LinkedList<>(); commonExclusions.add(MavenDependencies.createExclusion("commons-logging", "commons-logging")); commonExclusions.add(MavenDependencies.createExclusion("org.slf4j", "slf4j-log4j12")); commonExclusions.add(MavenDependencies.createExclusion("log4j", "log4j")); commonExclusions.add(MavenDependencies.createExclusion("log4j", "log4j-slf4j2-impl")); commonExclusions.add(MavenDependencies.createExclusion("org.apache.logging.log4j", "log4j")); commonExclusions.add(MavenDependencies.createExclusion("org.apache.logging.log4j", "log4j-core")); commonExclusions.add(MavenDependencies.createExclusion("org.apache.logging.log4j", "log4j-slf4j2-impl")); commonExclusions.add(MavenDependencies.createExclusion("log4j", "apache-log4j-extras")); commonExclusions.add(MavenDependencies.createExclusion("org.slf4j", "slf4j-simple")); commonExclusions.add(MavenDependencies.createExclusion("org.slf4j", "slf4j-jdk14")); commonExclusions.add(MavenDependencies.createExclusion("ch.qos.logback", "logback-classic")); commonExclusions.add(MavenDependencies.createExclusion("ch.qos.logback", "logback-core")); for (String ex : config.getMavenExclusions()) { commonExclusions.add(MavenDependencies.createExclusion(ex)); } // Module dependencies List<MavenDependency> additionalDependencies = new LinkedList<>(); for (String canonicalForm : config.getAdditionalDependencies()) { MavenCoordinate coord = MavenCoordinates.createCoordinate(canonicalForm); MavenDependency dep = MavenDependencies.createDependency(coord, ScopeType.RUNTIME, false); additionalDependencies.add(dep); } List<String> providedDependenciesXml = new LinkedList<>(); List<ScopeType> scopes = new LinkedList<>(); if (config.getIncludeProvidedDependencies() || config.getIncludeTestDependencies() || config.getUnitTestEnabled()) { if (config.getIncludeTestDependencies() || config.getUnitTestEnabled()) { scopes.add(ScopeType.TEST); } if (config.getIncludeProvidedDependencies()) { providedDependenciesXml.addAll(DependencyResolver.getDependencies(config.getModuleBasePath() + "/pom.xml", ScopeType.PROVIDED.toString())); scopes.add(ScopeType.PROVIDED); } } List<String> cleanProvidedDependenciesXml = new LinkedList<>(); for (String depXml : providedDependenciesXml) { if (validTestDependency(config, depXml, commonExclusions)) { depXml = useBOMVersionIfPresent(config, depXml); depXml = enforceExclusions(depXml, commonExclusions); depXml = switchToStarterIfPresent(depXml); cleanProvidedDependenciesXml.add(depXml); } } File moduleSpringBootPom = createUserPom(config, cleanProvidedDependenciesXml); List<ScopeType> resolvedScopes = new LinkedList<>(); resolvedScopes.add(ScopeType.COMPILE); resolvedScopes.add(ScopeType.RUNTIME); resolvedScopes.addAll(scopes); Set<MavenResolvedArtifact> runtimeDependencies; try { runtimeDependencies = new HashSet<>(Arrays.asList(resolver(config) .loadPomFromFile(moduleSpringBootPom) .importDependencies(resolvedScopes.toArray(new ScopeType[0])) .addDependencies(additionalDependencies) .resolve() .withTransitivity() .asResolvedArtifact())); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } // Load the test dependencies from the actual starter pom with transitivity // since most are defined in the parent pom Set<MavenResolvedArtifact> testProvidedDependenciesPom; try { testProvidedDependenciesPom = new HashSet<>(Arrays.asList(resolver(config) .loadPomFromFile(new File(config.getModuleBasePath() + "/pom.xml")) .importTestDependencies() .resolve() .withTransitivity() .asResolvedArtifact())); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } // Remove duplicates between test and runtime dependencies runtimeDependencies.addAll(testProvidedDependenciesPom); List<MavenResolvedArtifact> dependencyArtifacts = new LinkedList<>(runtimeDependencies); lookForVersionMismatch(config, dependencyArtifacts); List<File> dependencies = new LinkedList<>(); for (MavenResolvedArtifact a : dependencyArtifacts) { dependencies.add(a.asFile()); } // The spring boot-loader dependency will be added to the main jar, so it should be excluded from the embedded ones excludeDependencyRegex(dependencies, "^spring-boot-loader-[0-9].*"); // Add all dependencies as spring-boot nested jars ark = addDependencies(config, ark, dependencies); // Add common packages to main jar ark = ark.addPackages(true, "org.jboss.shrinkwrap"); // Add current classes to both location to be used by different classloaders ark = ark.addPackages(true, "org.apache.camel.itest.springboot"); ark = addSpringbootPackage(ark, "org.apache.camel.itest.springboot"); // CAMEL-10060 is resolved since 2.18 but some unit tests use custom (non spring-boot enabled) camel contexts ark = ark.addPackages(true, "org.apache.camel.converter.myconverter"); ark = ark.addPackages(true, "org.springframework.boot.loader"); ClassPath.Builder external = ClassPath.builder().add(ark); // overcome limitations of some JDKs external.addSystemProperty("javax.xml.accessExternalDTD", "all"); external.addSystemProperty("javax.xml.accessExternalSchema", "all"); // Set a java logging configuration which will not log to console external.addSystemProperty("java.util.logging.config.file", new File(".").getCanonicalPath() + "/target/test-classes/jul.properties"); if (config.getUnitTestEnabled()) { external.addSystemProperty("container.user.dir", new File(config.getModuleBasePath()).getCanonicalPath()); external.addSystemProperty("container.test.resources.dir", new File(config.getModuleBasePath()).getCanonicalPath() + "/target/test-classes"); } // Adding configuration properties for (Map.Entry<Object, Object> e : System.getProperties().entrySet()) { if (e.getKey() instanceof String key && e.getValue() instanceof String) { if (key.startsWith(ITestConfigBuilder.CONFIG_PREFIX)) { external.addSystemProperty(key, (String) e.getValue()); } } } for (Map.Entry<String, String> e : config.getSystemProperties().entrySet()) { external.addSystemProperty(e.getKey(), e.getValue()); } return external.build(); } private static void lookForVersionMismatch(ITestConfig config, List<MavenResolvedArtifact> dependencyArtifacts) { Set<String> ignore = new HashSet<>(config.getIgnoreLibraryMismatch()); // A list of known libraries that don't follow the all-artifacts-same-version convention ignore.add("com.atlassian.jira:jira-rest-java-client-api"); ignore.add("com.fasterxml.jackson.module:jackson-module-scala_2.11"); // latest version not available ignore.add("com.github.jnr"); ignore.add("com.sun.xml.bind:jaxb-xjc"); ignore.add("com.azure:azure"); ignore.add("com.datastax.oss:java"); ignore.add("com.jcabi:jcabi"); ignore.add("commons-beanutils:commons-beanutils"); ignore.add("io.dropwizard.metrics:metrics-json"); // PR to spring-boot ignore.add("io.dropwizard.metrics:metrics-jvm"); // PR to spring-boot ignore.add("io.fabric8:kubernetes-"); ignore.add("io.netty:netty:jar"); // an old version ignore.add("io.netty:netty-tcnative-boringssl-static"); ignore.add("io.swagger:swagger-parser"); ignore.add("io.opencensus:opencensus-"); ignore.add("io.opentracing.contrib:opentracing-"); ignore.add("org.apache.commons"); ignore.add("org.apache.curator"); ignore.add("org.apache.cxf:cxf-api"); ignore.add("org.apache.geronimo.specs"); ignore.add("org.apache.flink:flink-shaded-asm"); ignore.add("org.apache.flink:flink-shaded-guava"); ignore.add("org.apache.flink:flink-shaded-jackson"); ignore.add("org.apache.flink:flink-shaded-netty"); ignore.add("org.apache.logging.log4j:log4j-jcl"); ignore.add("org.apache.maven"); ignore.add("org.apache.parquet"); ignore.add("org.apache.velocity"); ignore.add("org.apache.qpid:qpid-jms-client"); ignore.add("org.opensaml"); ignore.add("org.ow2.asm"); // No problem ignore.add("org.codehaus.plexus"); ignore.add("org.eclipse.jetty.websocket:websocket-api"); // PR to spring-boot ignore.add("org.jboss.arquillian.container"); ignore.add("org.jboss:"); ignore.add("org.hibernate:hibernate-validator"); // does not match with hibernate-core ignore.add("org.mortbay.jetty:servlet-api-2.5"); ignore.add("org.scala-lang:scala-compiler"); ignore.add("org.slf4j:slf4j-ext"); // PR to spring-boot ignore.add("org.easytesting"); ignore.add("net.java.dev.jna:jna-platform"); // PR to spring-boot ignore.add("net.openhft"); ignore.add("org.scala-lang.modules:scala-java8-compat_2.11"); ignore.add("org.scala-lang.modules:scala-parser-combinators_2.12"); ignore.add("org.scala-lang.modules:scala-xml_2.12"); ignore.add("net.sourceforge.htmlunit:htmlunit-core-js"); // v 2.21 does not exist ignore.add("org.springframework.cloud"); // too many different versions ignore.add("org.springframework.data"); ignore.add("org.springframework.security:spring-security-jwt"); ignore.add("org.springframework.security:spring-security-rsa"); ignore.add("org.springframework.social"); ignore.add("org.webjars"); // No problem ignore.add("stax:stax-api"); ignore.add("xml-apis:xml-apis-ext"); ignore.add("org.jboss.logging"); ignore.add("org.jboss.marshalling"); ignore.add("org.jgroups:jgroups-raft"); ignore.add("net.sourceforge.htmlunit:htmlunit"); ignore.add("ai.djl.mxnet:mxnet-engine"); ignore.add("ai.djl.mxnet:mxnet-model-zoo"); ignore.add("ai.djl.mxnet:mxnet-native-auto"); ignore.add("org.sonatype.plexus"); ignore.add("org.codehaus.plexus"); ignore.add("org.sonatype.sisu"); ignore.add("com.healthmarketscience.jackcess"); ignore.add("com.google.cloud"); ignore.add("com.google.api"); ignore.add("com.google.http-client"); ignore.add("org.eclipse.rdf4j"); ignore.add("org.scala-lang"); ignore.add("org.datanucleus"); ignore.add("org.apache.hive"); // these are from camel-spring-boot and not camel repo so ignore them ignore.add("org.apache.camel:camel-spring-boot"); // google grpc is a mix of all sort of different versions ignore.add("com.google.api.grpc"); // microsoft azure msal4j-persistence-extension library introduced by datalake component ignore.add("com.microsoft.azure:msal4j-persistence-extension"); Map<String, Map<String, Set<String>>> status = new TreeMap<>(); Set<String> mismatches = new TreeSet<>(); Set<String> potentialMismatches = new TreeSet<>(); for (MavenResolvedArtifact a : dependencyArtifacts) { boolean ignoreCheck = false; String identifier = getIdentifier(a); for (String i : ignore) { if (identifier.startsWith(i)) { ignoreCheck = true; break; } } if (ignoreCheck) { continue; } String group = a.getCoordinate().getGroupId(); String artifact = a.getCoordinate().getArtifactId(); String version = a.getCoordinate().getVersion(); String artifactPrefix = artifact; if (artifactPrefix.contains("-")) { artifactPrefix = artifactPrefix.substring(0, artifactPrefix.indexOf("-")); } String prefixId = group + ":" + artifactPrefix; if (!status.containsKey(prefixId)) { status.put(prefixId, new TreeMap<>()); } for (Map.Entry<String, Set<String>> entry : status.get(prefixId).entrySet()) { Set<String> anotherVersions = entry.getValue(); if (anotherVersions.size() == 1 && !sameVersion(anotherVersions.iterator().next(), version)) { if (identifier.equals(entry.getKey())) { // Same coordinates but different versions mismatches.add(prefixId); } else { // Same prefix but different versions potentialMismatches.add(prefixId); } } } status.get(prefixId).computeIfAbsent(identifier, k -> new LinkedHashSet<>()).add(version); } StringBuilder message = new StringBuilder(); for (String mismatch : mismatches) { message.append("Found mismatch for dependency ").append(mismatch).append(":\n"); Map<String, Set<String>> artifacts = status.get(mismatch); for (String art : artifacts.keySet()) { Set<String> versions = artifacts.get(art); message.append(" - ").append(art).append(" --> ").append(versions).append("\n"); } } if (message.length() > 0) { String alert = "Library version mismatch found.\n" + message; if (config.getFailOnRelatedLibraryMismatch()) { throw new InvocationException(new RuntimeException(alert)); } else { warn(alert); } } for (String mismatch : potentialMismatches) { message.setLength(0); message.append("Found a potential version mismatch for dependency ").append(mismatch).append(":\n"); Map<String, Set<String>> artifacts = status.get(mismatch); for (String art : artifacts.keySet()) { Set<String> versions = artifacts.get(art); message.append(" - ").append(art).append(" --> ").append(versions).append("\n"); } warn(message.toString()); } } private static boolean sameVersion(String v1, String v2) { if (v1.indexOf(".") != v1.lastIndexOf(".") && v2.indexOf(".") != v2.lastIndexOf(".")) { // truncate up to minor version int v1MinSplit = v1.indexOf(".", v1.indexOf(".") + 1); v1 = v1.substring(0, v1MinSplit); int v2MinSplit = v2.indexOf(".", v2.indexOf(".") + 1); v2 = v2.substring(0, v2MinSplit); } return v1.equals(v2); } private static String getIdentifier(MavenResolvedArtifact a) { return a.getCoordinate().getGroupId() + ":" + a.getCoordinate().getArtifactId() + ":" + a.getCoordinate().getType() + ":" + a.getCoordinate().getClassifier(); } private static File createUserPom(ITestConfig config, List<String> cleanTestProvidedDependencies) throws Exception { String pom; String template = "/application-pom-sb" + config.getSpringBootMajorVersion() + ".xml"; try (InputStream pomTemplate = ArquillianPackager.class.getResourceAsStream(template)) { pom = IOUtils.toString(Objects.requireNonNull(pomTemplate), StandardCharsets.UTF_8); } StringBuilder dependencies = new StringBuilder(); for (String dep : cleanTestProvidedDependencies) { dependencies.append(dep); dependencies.append("\n"); } pom = pom.replace("<!-- DEPENDENCIES -->", dependencies.toString()); Map<String, String> resolvedProperties = new TreeMap<>(); Matcher m = PROP_PATTERN.matcher(pom); while (m.find()) { String property = m.group(); String resolved = DependencyResolver.resolveModuleOrParentProperty(new File(new File(config.getModuleBasePath()), "pom.xml"), property); resolvedProperties.put(property, resolved); } for (String property : resolvedProperties.keySet()) { pom = pom.replace(property, resolvedProperties.get(property)); } pom = pom.replace("#{module}", config.getModuleName()); // some modules are not in component-starter String path = config.getModuleBasePath(); File pomFile = new File(path + "/target/itest-spring-boot-pom.xml"); pomFile.getParentFile().mkdirs(); try (FileWriter fw = new FileWriter(pomFile)) { IOUtils.write(pom, fw); } return pomFile; } private static ConfigurableMavenResolverSystem resolver(ITestConfig config) { return Maven.configureResolver().workOffline(config.getMavenOfflineResolution()); } private static ClassLoader getExtensionClassloader() { ClassLoader cl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } return cl; } private static boolean validTestDependency(ITestConfig config, String dependencyXml, List<MavenDependencyExclusion> exclusions) { boolean valid = true; for (MavenDependencyExclusion excl : exclusions) { String groupId = excl.getGroupId(); String artifactId = excl.getArtifactId(); boolean notExclusion = !dependencyXml.contains("<exclusions>") || dependencyXml.indexOf(groupId) < dependencyXml.indexOf("<exclusions>"); if (dependencyXml.contains(groupId) && dependencyXml.contains(artifactId) && notExclusion) { valid = false; break; } } if (!valid) { debug(config, "Discarded test dependency: " + dependencyXml.replace("\n", "").replace("\r", "").replace("\t", "")); } return valid; } private static String enforceExclusions(String dependencyXml, List<MavenDependencyExclusion> exclusions) { if (!dependencyXml.contains("<exclusions>")) { dependencyXml = dependencyXml.replace("</dependency>", "<exclusions></exclusions></dependency>"); } for (MavenDependencyExclusion excl : exclusions) { String groupId = excl.getGroupId(); String artifactId = excl.getArtifactId(); dependencyXml = dependencyXml.replace("</exclusions>", "<exclusion><groupId>" + groupId + "</groupId><artifactId>" + artifactId + "</artifactId></exclusion></exclusions>"); } return dependencyXml; } private static String switchToStarterIfPresent(String dependencyXml) { String groupId = textBetween(dependencyXml, "<groupId>", "</groupId>"); String artifactId = textBetween(dependencyXml, "<artifactId>", "</artifactId>"); String type = textBetween(dependencyXml, "<type>", "</type>"); if ("org.apache.camel".equals(groupId) && artifactId.startsWith("camel-") && !"test-jar".equals(type)) { String starterArtifact = artifactId + "-starter"; File starterFile = new File("../../components-starter/" + starterArtifact); if (starterFile.exists()) { dependencyXml = dependencyXml.replace(artifactId, starterArtifact); } } return dependencyXml; } private static String useBOMVersionIfPresent(ITestConfig config, String dependencyXml) { String groupId = textBetween(dependencyXml, "<groupId>", "</groupId>"); String artifactId = textBetween(dependencyXml, "<artifactId>", "</artifactId>"); String version = config.getTestLibraryVersions().get(groupId + ":" + artifactId); boolean stripVersion = false; if (version == null) { boolean testsLib = dependencyXml.contains("<classifier>tests"); stripVersion = !testsLib && BOMResolver.getInstance(config).getBOMVersion(groupId, artifactId) != null; // skip if its org.infinispan as we need explict version to work-around a problem when using test-jar dependencies if ("org.infinispan".equals(groupId)) { stripVersion = false; } } if (version != null) { if (dependencyXml.contains("<version>")) { int from = dependencyXml.indexOf("<version>") + 9; int to = dependencyXml.indexOf("</version>"); dependencyXml = dependencyXml.substring(0, from) + version + dependencyXml.substring(to); } else { String kw = "</artifactId>"; int pos = dependencyXml.indexOf(kw) + kw.length(); dependencyXml = dependencyXml.substring(0, pos) + "<version>" + version + "</version>" + dependencyXml.substring(pos); } } else if (stripVersion && dependencyXml.contains("<version>")) { int from = dependencyXml.indexOf("<version>"); int to = dependencyXml.indexOf("</version>") + 10; dependencyXml = dependencyXml.substring(0, from) + dependencyXml.substring(to); } return dependencyXml; } private static String textBetween(String text, String start, String end) { int sp = text.indexOf(start); int rsp = sp + start.length(); int ep = text.indexOf(end); if (sp < 0 || ep < 0 || ep <= rsp) { return ""; } return text.substring(rsp, ep); } private static boolean excludeDependencyRegex(List<File> dependencies, String regex) { Pattern pattern = Pattern.compile(regex); int count = 0; for (Iterator<File> it = dependencies.iterator(); it.hasNext();) { File f = it.next(); if (pattern.matcher(f.getName()).matches()) { it.remove(); count++; break; } } return count > 0; } private static JavaArchive addDependencies(ITestConfig config, JavaArchive ark, Collection<File> deps) { Set<File> dependencySet = new HashSet<>(deps); for (File d : dependencySet) { debug(config, "Adding spring-boot dependency: " + d.getName()); ark = ark.add(new FileAsset(d), LIB_FOLDER + "/" + d.getName()); } return ark; } private static JavaArchive addSpringbootPackage(JavaArchive ark, String... packageNames) { Iterable<ClassLoader> classLoaders = Collections.singleton(Thread.currentThread().getContextClassLoader()); for (String packageName : packageNames) { for (final ClassLoader classLoader : classLoaders) { final URLPackageScanner.Callback callback = new URLPackageScanner.Callback() { @Override public void classFound(String className, Asset asset) { ArchivePath classNamePath = AssetUtil.getFullPathForClassResource(className); asset = new ClassLoaderAsset(classNamePath.get().substring(1), classLoader); ArchivePath location = new BasicPath(CLASSES_FOLDER + "/", classNamePath); ark.add(asset, location); } }; final URLPackageScanner scanner = URLPackageScanner.newInstance(true, classLoader, callback, packageName); scanner.scanPackage(); } } return ark; } private static void debug(ITestConfig config, String str) { if (config.getDebugEnabled()) { System.out.println("DEBUG>>> " + str); } } private static void warn(String str) { System.out.println("WARN>>> " + str); } }
Java
CL
577327c3d72f60398b7c3a8611befd4ac33f1293c2c4494b3e9fdc9ae53c6ec2
package com.cloudhopper.commons.sql.proxool; /* * #%L * ch-commons-sql * %% * Copyright (C) 2012 - 2013 Cloudhopper by Twitter * %% * 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. * #L% */ import com.cloudhopper.commons.sql.*; import com.cloudhopper.commons.sql.adapter.*; import com.cloudhopper.commons.util.ManagementUtil; import java.lang.management.ManagementFactory; import java.util.Properties; import org.logicalcobwebs.proxool.ProxoolDriver; import org.logicalcobwebs.proxool.ProxoolException; import org.logicalcobwebs.proxool.ProxoolFacade; /** * Adapter for a Proxool DataSource. * * @author joelauer */ public class ProxoolDataSourceAdapter implements DataSourceAdapter { public boolean isPooled() { return true; } public boolean isJmxCapable() { return true; } public ManagedDataSource create(DataSourceConfiguration config) throws SQLMissingDependencyException, SQLConfigurationException { // verify proxool driver exists and register it try { // create a new instance ProxoolDriver driver = new ProxoolDriver(); } catch (Exception e) { throw new SQLMissingDependencyException("Proxool driver '" + ProxoolDriver.class.getName() + "' failed to load. Perhaps missing proxool jar file?", e); } // create new set of proxool properties Properties info = new Properties(); // setup properties to use info.setProperty("proxool.minimum-connection-count", Integer.toString(config.getMinPoolSize())); info.setProperty("proxool.maximum-connection-count", Integer.toString(config.getMaxPoolSize())); // set the validation query info.setProperty("proxool.house-keeping-test-sql", config.getValidationQuery()); // amount of time (in ms) to wait for getConnection() to succeed // not supported by Proxool -- maybe driver dependant???? //config.getCheckoutTimeout()); // checkin/checkout validation info.setProperty("proxool.test-after-use", Boolean.toString(config.getValidateOnCheckin())); info.setProperty("proxool.test-before-use", Boolean.toString(config.getValidateOnCheckout())); // amount of time to wait to validate connections info.setProperty("proxool.house-keeping-sleep-time", Long.toString(config.getValidateIdleConnectionTimeout())); // set idleConnectionTimeout // not supported by prooxool -- this is implicitly done... // set activeConnectionTimeout info.setProperty("proxool.maximum-active-time", Long.toString(config.getActiveConnectionTimeout())); // should jmx be turned on/off? if (config.getJmx()) { // enable jmx for proxool (no support for renaming domain, object name) info.setProperty("proxool.jmx", "true"); // create list of all mbean servers... String serverId = ManagementUtil.getMBeanServerId(ManagementFactory.getPlatformMBeanServer()); // add agent-id property info.setProperty("proxool.jmx-agent-id", serverId); } else { info.setProperty("proxool.jmx", "false"); } info.setProperty("user", config.getUsername()); info.setProperty("password", config.getPassword()); String alias = config.getName(); String driverClass = config.getDriver(); String driverUrl = config.getUrl(); // create new url for proxool String proxoolUrl = "proxool." + alias + ":" + driverClass + ":" + driverUrl; // register this connection // normally, you'd do this ProxoolFacade.registerConnectionPool(url, info); try { ProxoolFacade.registerConnectionPool(proxoolUrl, info); } catch (ProxoolException e) { throw new SQLConfigurationException("Failed while registering proxool connection", e); //throw new SQLMissingDependencyException("Proxool '" + PROXOOL_FACADE_CLASS + "' failed to load. Perhaps missing proxool jar file?", e); } // create basic DataSource wrapper to handle calls to the DriverManager BasicDataSource ds = new BasicDataSource(proxoolUrl, config.getUsername(), config.getPassword()); // done creating datasource wrapper, return it return new ProxoolManagedDataSource(this, config, ds); } }
Java
CL
151a65716c8ba559a3cae37facf44b6c260f43241f4f505cec414369cde319ad
package ru.job4j.array; public class BubbleSort { /** * @param array массив int * метод должен сортировать массив по возрастанию * используя метод перестановок или "пузырьковой сортировки" * the method should sort the array in ascending order * using the permutation or "bubble sort method" * * tmp - временная переменная для перестановок * цикл i уменьшается справа по мере выталкивания максимальных элементов * цикл j пробегает внутри i и проверяет условие * Если первый элемент больше второго, то они меняются местами * Таким образом, в конец цикла j выталкивается самы большой элемент * который отсекается циклом i. * @return отортированный массив */ public int[] sort(int[] array) { int tmp; for (int i = array.length - 1; i >= 0; i--) { for (int j = 0; j < i; j++) { if (array[j] > array[j + 1]) { tmp = array[j]; array[j] = array[j + 1]; array[j + 1] = tmp; } } } return array; } }
Java
CL
4b3981e924faf202f7a19ea55d25ddc7ff2d00473c2dd38787f3e9d8b4e3500c
package org.sagebionetworks.bridge.services; import java.util.Map; import org.joda.time.DateTimeZone; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.sagebionetworks.bridge.cache.CacheProvider; import org.sagebionetworks.bridge.models.CriteriaContext; import org.sagebionetworks.bridge.models.accounts.ConsentStatus; import org.sagebionetworks.bridge.models.accounts.ExternalIdentifier; import org.sagebionetworks.bridge.models.accounts.SharingScope; import org.sagebionetworks.bridge.models.accounts.StudyParticipant; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.subpopulations.SubpopulationGuid; /** * Service that updates the state of a user's session, eventually its dependencies as well (the state of the * user's push notification topic subscriptions, and the session as it is cached). Changes that update a * user's session should go through this service to ensure dependencies are handled correctly. */ @Component public class SessionUpdateService { private CacheProvider cacheProvider; private ConsentService consentService; private NotificationTopicService notificationTopicService; @Autowired public final void setCacheProvider(CacheProvider cacheProvider) { this.cacheProvider = cacheProvider; } @Autowired public final void setConsentService(ConsentService consentService) { this.consentService = consentService; } /** Notification topic service, used to manage auto-managed Push and SMS notifications. */ @Autowired public final void setNotificationTopicService(NotificationTopicService notificationTopicService) { this.notificationTopicService = notificationTopicService; } public void updateTimeZone(UserSession session, DateTimeZone timeZone) { session.setParticipant(builder(session).withTimeZone(timeZone).build()); cacheProvider.setUserSession(session); } public void updateStudy(UserSession session, StudyIdentifier studyId) { session.setStudyIdentifier(studyId); cacheProvider.setUserSession(session); } public void updateLanguage(UserSession session, CriteriaContext context) { updateCriteria(session, context, builder(session).withLanguages(context.getLanguages()).build()); } public void updateExternalId(UserSession session, ExternalIdentifier externalId) { session.setParticipant(builder(session).withExternalId(externalId.getIdentifier()).build()); cacheProvider.setUserSession(session); } public void updateParticipant(UserSession session, CriteriaContext context, StudyParticipant participant) { updateCriteria(session, context, participant); } public void updateDataGroups(UserSession session, CriteriaContext context) { updateCriteria(session, context, builder(session).withDataGroups(context.getUserDataGroups()).build()); } private void updateCriteria(UserSession session, CriteriaContext context, StudyParticipant participant) { // Update session and consent statuses. session.setParticipant(participant); Map<SubpopulationGuid,ConsentStatus> statuses = consentService.getConsentStatuses(context); session.setConsentStatuses(statuses); cacheProvider.setUserSession(session); // Manage notifications, if necessary. notificationTopicService.manageCriteriaBasedSubscriptions(context.getStudyIdentifier(), context, participant.getHealthCode()); } public void updateSharingScope(UserSession session, SharingScope sharingScope) { session.setParticipant(builder(session).withSharingScope(sharingScope).build()); cacheProvider.setUserSession(session); } public void updateSession(UserSession oldSession, UserSession newSession) { newSession.setSessionToken(oldSession.getSessionToken()); newSession.setInternalSessionToken(oldSession.getInternalSessionToken()); cacheProvider.setUserSession(newSession); } private StudyParticipant.Builder builder(UserSession session) { return new StudyParticipant.Builder().copyOf(session.getParticipant()); } }
Java
CL
add39b775c2ab40fd35a04f48ba45c6bc6b7d71319e46d3c4e80b5892a33e544
package org.ng.undp.vdms.domains.consultants; import lombok.Data; import lombok.Getter; import lombok.Setter; import org.ng.undp.vdms.constants.MaritalStatus; import org.ng.undp.vdms.dao.Accessor; import org.ng.undp.vdms.dao.Filter; import org.ng.undp.vdms.domains.constants.Sex; import javax.persistence.*; import java.util.Date; import java.util.List; /** * Created by emmanuel on 6/19/17. */ @Getter @Setter @Table(name = "bio_data") @Entity public class BioData { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String surName; private String firstName; private String middleName; private String maidenName; private Date dob; private String placeOfBirth; @ElementCollection private List<String> nationalitiesAtBirth; @ElementCollection private List<String> presentNationalities; @Enumerated(EnumType.STRING) private Sex sex; private double height; private double weight; @Enumerated(EnumType.STRING) private MaritalStatus maritalStatus; @ManyToOne private Address permanentAddress; @ManyToOne private Address presentAddress; @ManyToOne private Address officeAddress; private boolean hasSpouse; /*Have you taken any permanet status in any country that is not you Nationality*/ private boolean hasForeignPermanentStatus; /*Country where you took Permanent Status that is not your Nationality*/ private String countryOfForeignPermanentStatus; /*Are any of your relatives employed by a public international organization?*/ private boolean hasAnyRelationWorkingInternationally; private String prefferedFieldOfWork; private String motherTongue; //capture Language skills @Transient private List<LanguageSkill> languageSkills; public List<LanguageSkill> getLanguageSkillsFromDb(){ return Accessor.findList(LanguageSkill.class, Filter.get().field("bioData.id", this.getId())); } //Item 19 from form is skipped (Clerical grades) private boolean everTriedChangingPresentNationality; @Lob private String reasonForAttemptingToChangeNationality; }
Java
CL
af4ec5d1d4b3507cfe07c28811c0210aff829ce0c238fde7ad57a7deef9d5c10
package net.bflows.pagafatture.controller; import static org.hamcrest.core.Is.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.json.JSONObject; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.fasterxml.jackson.databind.ObjectMapper; import net.bflows.pagafatture.entities.InvoicingConnectionEntity; import net.bflows.pagafatture.entities.InvoicingEntity; import net.bflows.pagafatture.entities.MerchantEntity; import net.bflows.pagafatture.entities.UserEntity; import net.bflows.pagafatture.model.InvoicingConnectionReq; import net.bflows.pagafatture.model.UserReq; import net.bflows.pagafatture.repositories.InvoicingRepository; import net.bflows.pagafatture.repositories.MerchantRepository; import net.bflows.pagafatture.repositories.UserRepository; @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") class InvoicingsApiControllerTest { @Autowired private MockMvc mvc; @Autowired private MerchantRepository merchantRepository; @Autowired private InvoicingRepository invoicingRepository; @Autowired private ObjectMapper mapper; @Autowired private UserRepository userRepository; @Test @Order(1) void testCreateInvocingConnection_Fail_By_Credential() throws Exception { InvoicingEntity invoicingEntity = invoicingRepository.findById(1l).get(); InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq(); invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c0862123"); invoicingConnection.setApiUid("88864"); invoicingConnection.setTypeId(invoicingEntity.getId()); MerchantEntity merchant = new MerchantEntity(); merchant.setName("Merchant2"); merchant.setVatNumber("12345678901"); merchant.setDirectUrl("Http:www.www.it"); merchant.setAddressCity("Cagliari"); merchant.setAddressState("Sardinia"); merchant.setAddressCAP("09100"); merchant.setAddressStreet("Via PPP"); merchant = merchantRepository.save(merchant); String URI = "/v1/invoicings/" + merchant.getId() + "/connections"; mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()).andExpect(jsonPath("$.message", is("Invalid credentials."))); } @Test @Order(2) void testCreateInvocingConnection_Fail_By_invoicingId() throws Exception { InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq(); invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086"); invoicingConnection.setApiUid("88864"); invoicingConnection.setTypeId(0l); MerchantEntity merchantEntity = merchantRepository.findById(2l).get(); String URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections"; mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test @Order(3) void testCreateInvocingConnection_Success() throws Exception { InvoicingEntity invoicingEntity = invoicingRepository.findById(1l).get(); InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq(); invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086"); invoicingConnection.setApiUid("88864"); invoicingConnection.setTypeId(invoicingEntity.getId()); MerchantEntity merchantEntity = merchantRepository.findById(2l).get(); String URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections"; mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(jsonPath("$.data.apiKey", is(invoicingConnection.getApiKey()))); URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections"; mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test @Order(4) void testGetInvoicing() throws Exception { String URI = "/v1/invoicings"; mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isOk()); } @Test @Order(5) void testGetInvoicingConnectionByMerchantId_Sucess() throws Exception { InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq(); invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086"); invoicingConnection.setApiUid("88864"); invoicingConnection.setTypeId(1l); UserReq user = new UserReq(); user.setId(1l); user.setCompanyName("Test InvoicingConnection"); user.setConfPassword("test12345678"); user.setEmail("testInvoicingConnection@test.com"); user.setFirstName("test"); user.setLastName("test lastname"); user.setPassword("test12345678"); user.setPhone("2424856"); String URI = "/v1/users"; mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(user)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()); UserEntity userEntity = userRepository.findByEmailIgnoreCase(user.getEmail()).get(); URI = "/v1/invoicings/" + userEntity.getMerchant().getId() + "/connections"; ResultActions resultActions = mvc.perform(post(URI).content(new ObjectMapper().writeValueAsString(invoicingConnection)) .contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isCreated()); MvcResult result = resultActions.andReturn(); String contentAsString = result.getResponse().getContentAsString(); JSONObject json = new JSONObject(contentAsString); InvoicingConnectionEntity response = mapper.readValue(json.get("data").toString(), InvoicingConnectionEntity.class); URI = "/v1/invoicings/" + response.getMerchantEntity().getId() + "/connections"; mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isOk()); } @Test @Order(6) void testGetInvoicingConnectionByMerchantId_Fail() throws Exception { String URI = "/v1/invoicings/" + 0 + "/connections"; mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isNotFound()); MerchantEntity merchant = new MerchantEntity(); merchant.setName("InvoicingConnection Merchant"); merchant.setVatNumber("12345678901"); merchant.setDirectUrl("Http:www.www.it"); merchant.setAddressCity("Cagliari"); merchant.setAddressState("Sardinia"); merchant.setAddressCAP("09100"); merchant.setAddressStreet("Via PPP"); merchant = merchantRepository.save(merchant); URI = "/v1/invoicings/" + merchant.getId() + "/connections"; mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isNotFound()); } @Test @Order(7) void testCreateInvocingConnection_Fail_By_MerchantId() throws Exception { InvoicingEntity invoicingEntity = invoicingRepository.findById(1l).get(); InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq(); invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086"); invoicingConnection.setApiUid("88864"); invoicingConnection.setTypeId(invoicingEntity.getId()); String URI = "/v1/invoicings/" + 0 + "/connections"; mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test @Order(8) void testCreateInvocingConnection_FailByTypeId() throws Exception { InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq(); invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086"); invoicingConnection.setApiUid("88864"); MerchantEntity merchantEntity = merchantRepository.findById(2l).get(); String URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections"; mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test @Order(9) void testGetInvoicingConnection() throws Exception { String URI = "/v1/invoicings/connections"; mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isOk()); URI = "/v1/invoicings/connections?type=1"; mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isOk()); } /* @Test @Order(10) void testCreateInvocingConnection_WithPasspartout() throws Exception { InvoicingEntity invoicingEntity = invoicingRepository.findById(2l).get(); InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq(); invoicingConnection.setApiKey("137918001"); invoicingConnection.setApiUid("STU"); invoicingConnection.setTypeId(invoicingEntity.getId()); MerchantEntity merchantEntity = new MerchantEntity(); merchantEntity.setName("Test merchant"); merchantEntity.setEmail("testpasspartout@test.test"); merchantEntity = merchantRepository.save(merchantEntity); String URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections"; mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); invoicingConnection = new InvoicingConnectionReq(); invoicingConnection.setApiKey("1379185000"); invoicingConnection.setApiUid("STU"); invoicingConnection.setTypeId(invoicingEntity.getId()); URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections"; mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(jsonPath("$.data.apiKey", is(invoicingConnection.getApiKey()))); }*/ }
Java
CL
1cf1925c2d05fdc5fd78a797d4a24f8c158ce7b164a9a01e44dd63f4f810ffe2
package com.musiclibrary.shal.pojos; import javax.annotation.Generated; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; @Generated("org.jsonschema2pojo") public class ArtistImage { @SerializedName("image_id") @Expose private String imageId; @SerializedName("image_file") @Expose private String imageFile; @SerializedName("image_title") @Expose private String imageTitle; @SerializedName("image_caption") @Expose private String imageCaption; @SerializedName("image_copyright") @Expose private String imageCopyright; @SerializedName("image_source") @Expose private String imageSource; /** * * @return The imageId */ public String getImageId() { return imageId; } /** * * @param imageId * The image_id */ public void setImageId(String imageId) { this.imageId = imageId; } /** * * @return The imageFile */ public String getImageFile() { return imageFile; } /** * * @param imageFile * The image_file */ public void setImageFile(String imageFile) { this.imageFile = imageFile; } /** * * @return The imageTitle */ public String getImageTitle() { return imageTitle; } /** * * @param imageTitle * The image_title */ public void setImageTitle(String imageTitle) { this.imageTitle = imageTitle; } /** * * @return The imageCaption */ public String getImageCaption() { return imageCaption; } /** * * @param imageCaption * The image_caption */ public void setImageCaption(String imageCaption) { this.imageCaption = imageCaption; } /** * * @return The imageCopyright */ public String getImageCopyright() { return imageCopyright; } /** * * @param imageCopyright * The image_copyright */ public void setImageCopyright(String imageCopyright) { this.imageCopyright = imageCopyright; } /** * * @return The imageSource */ public String getImageSource() { return imageSource; } /** * * @param imageSource * The image_source */ public void setImageSource(String imageSource) { this.imageSource = imageSource; } }
Java
CL
fa48a6dcc4f878d9b4e8bd7ab57eac57f51169e4a47e65d09b1272b882d2f7ff
package enterprise.entity_bean_entity; import static javax.persistence.CascadeType.ALL; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; /** * The entity. */ @Entity @Table(name = "Auction") public class Auction implements Serializable { private static final long serialVersionUID = 2L; private int auction_id; private int user_id; private int objet_id; private String state; private int duration; private int max_duration; private double starting_price; private double current_price; private double inc_bidding; private int id_bidder; /** * gets the auction_id. * * @return the auction_id. */ @Id //Auction_ID est généré par un generator, mettre la valeur initiale à 1 @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "auctionGenerator") @SequenceGenerator(name = "auctionGenerator", sequenceName = "Auction_sequence", initialValue = 1, allocationSize = 1) @Column(name = "Auction_ID") public int getauction_id() { return auction_id; } /** * sets the auction_id. * * @param id * the new auction_id. */ public void setauction_id(final int id) { this.auction_id = id; } /** * gets the user_id. * * @return the user_id. */ @Column(name = "user_id") public int getuser_id() { return user_id; } /** * sets the user_id. * * @param id * the new user_id. */ public void setuser_id(final int id) { this.user_id = id; } /** * gets the objet_id. * * @return the objet_id. */ @Column(name = "objet_id") public int getobjet_id() { return objet_id; } /** * sets the objet_id. * * @param id * the new objet_id. */ public void setobjet_id(final int id) { this.objet_id = id; } /** * gets the state. * * @return the state. */ @Column(name = "state") public String getstate() { return state; } /** * sets the state. * * @param state * the new state. */ public void setstate(final String state) { this.state = state; } /** * gets the duration. * * @return the duration. */ @Column(name = "duration") public int getduration() { return duration; } /** * sets the duration. * * @param duration * the new duration. */ public void setduration(final int duration) { this.duration = duration; } /** * gets the max_duration. * * @return the max_duration. */ @Column(name = "max_duration") public int getmax_duration() { return max_duration; } /** * sets the max_duration. * * @param max_duration * the new max_duration. */ public void setmax_duration(final int max_duration) { this.max_duration = max_duration; } /** * gets the starting_price. * * @return the starting_price. */ @Column(name = "starting_price") public double getstarting_price() { return starting_price; } /** * sets the starting_price. * * @param starting_price * the new max_dustarting_priceration. */ public void setstarting_price(final double starting_price) { this.starting_price = starting_price; } /** * gets the current_price. * * @return the current_price. */ @Column(name = "current_price") public double getcurrent_price() { return current_price; } /** * sets the current_price. * * @param current_price * the new current_price. */ public void setcurrent_price(final double current_price) { this.current_price = current_price; } /** * gets the inc_bidding. * * @return the inc_bidding. */ @Column(name = "inc_bidding") public double getinc_bidding() { return inc_bidding; } /** * sets the inc_bidding. * * @param inc_bidding * the new inc_bidding. */ public void setinc_bidding(final double inc_bidding) { this.inc_bidding = inc_bidding; } /** * gets the id_bidder. * * @return the id_bidder. */ @Column(name = "id_bidder") public int getid_bidder() { return id_bidder; } /** * sets the id_bidder. * * @param id_bidder * the new id_bidder. */ public void setid_bidder(final int id_bidder) { this.id_bidder = id_bidder; } //Retourner les informations sur l'auction @Override public String toString() { return " objet_id is: " + objet_id + "\n state is: " + state + "\n duration is: " + duration + "\n max_duration is: " + max_duration + "\n starting_price is: " + starting_price + "\n current_price is: " + current_price + "\n increment for bidding is: " + inc_bidding + "\n the id of last bidder is: " + id_bidder; } }
Java
CL
c22f1f2349e3fa17aac9f3583b3dc9d84435eae27065a00568bc272e538f1b7a
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.gmu.csiss.earthcube.cyberconnector.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.namespace.QName; import javax.xml.soap.MessageFactory; import javax.xml.soap.MimeHeaders; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import org.apache.log4j.Logger; /** * Class SOAPClient * @author ziheng * @createtime 5:34:14 PM Jul 18, 2014 * aim to support igfds */ public class SOAPClient { static Logger logger = Logger.getLogger(SOAPClient.class); private String soapmessage; private String endpoint; private String respmessage; public String getSoapmessage() { return soapmessage; } public void setSoapmessage(String soapmessage) { this.soapmessage = soapmessage; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public String getRespmessage() { return respmessage; } public void setRespmessage(String respmessage) { this.respmessage = respmessage; } /*private void send1() throws SOAPException { SOAPMessage message = MessageFactory.newInstance().createMessage(); SOAPHeader header = message.getSOAPHeader(); header.detachNode(); SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); envelope.setAttribute("namespace","namespaceUrl"); SOAPBody body = message.getSOAPBody(); QName bodyName = new QName("getResponse"); SOAPBodyElement bodyElement = body.addBodyElement(bodyName); SOAPElement symbol = bodyElement.addChildElement("name"); symbol.addTextNode("Harry Joy"); SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection(); SOAPMessage response = connection.call(message, endpoint); connection.close(); SOAPBody responseBody = response.getSOAPBody(); SOAPBodyElement responseElement = (SOAPBodyElement)responseBody.getChildElements().next(); SOAPElement returnElement = (SOAPElement)responseElement.getChildElements().next(); if(responseBody.getFault()!=null){ logger.debug(returnElement.getValue()+" "+responseBody.getFault().getFaultString()); } else { logger.debug(returnElement.getValue()); } try { logger.debug(getXmlFromSOAPMessage(message)); logger.debug(getXmlFromSOAPMessage(response)); } catch (IOException e) { e.printStackTrace(); } }*/ /** * send message to SOAP service * @throws SOAPException */ public void send() throws SOAPException { InputStream in = null; try { String soap = getSoapmessage(); BaseTool util = new BaseTool(); in = util.convertString2InputStream(soap); MessageFactory mf = MessageFactory.newInstance(); MimeHeaders headers = new MimeHeaders(); headers.addHeader("Content-Type", "text/xml"); headers.addHeader("SOAPAction", ""); SOAPMessage message = mf.createMessage(headers, in); SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection(); SOAPMessage response = connection.call(message, getEndpoint()); connection.close(); String resp = getXmlFromSOAPMessage(response); logger.debug(resp); setRespmessage(resp); } catch (IOException ex) { String errmsg = ex.getClass().getName()+ ex.getLocalizedMessage(); logger.error(errmsg); throw new RuntimeException(errmsg); } catch (Exception ex){ String errmsg = ex.getClass().getName()+ ex.getLocalizedMessage(); logger.error(errmsg); throw new RuntimeException(errmsg); }finally { try { in.close(); } catch (IOException ex) { logger.error(ex.getLocalizedMessage()); } } } public static void main(String[] args){ try { SOAPClient client = new SOAPClient(); //client.send1(); client.setEndpoint("http://129.174.131.8:9006/GeoprocessingWS/services/Raster_ImageSegment"); client.setSoapmessage("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ras=\"http://Raster_ImageSegment.grass.ws.laits.gmu.edu\">\n" + " <soapenv:Header/>\n" + " <soapenv:Body>\n" + " <ras:segmentElement>\n" + " <ras:imgURL>http://www3.csiss.gmu.edu/data/cfpp_clipped.tif</ras:imgURL>\n" + " <ras:sigmaS>6.5</ras:sigmaS>\n" + " <ras:sigmaR>7</ras:sigmaR>\n" + " <ras:minRegion>20</ras:minRegion>\n" + " <ras:speedUpLevel>medium</ras:speedUpLevel>\n" + " <ras:returnFormat>BMP</ras:returnFormat>\n" + " </ras:segmentElement>\n" + " </soapenv:Body>\n" + "</soapenv:Envelope>"); client.send(); logger.debug("The response SOAP message is:\n"+client.getRespmessage()); } catch (SOAPException ex) { ex.printStackTrace(); } } private String getXmlFromSOAPMessage(SOAPMessage msg) throws SOAPException, IOException { ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); msg.writeTo(byteArrayOS); return new String(byteArrayOS.toByteArray()); } }
Java
CL
ed4e3e7de9b548b228a5844477006b622f86ea684f87eb1d417fa8bfe9621d18
package org.example.controller; import org.example.data.User; import org.example.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * @author Anton Lenok * @since 28.10.16. * Контроллер в архитектуре MVC * Необходим для создания REST методов (GET, POST и т.д.) в сервере */ @Controller public class SimpleController { // Подключаем репозиторий для работы с БД @Autowired private UserRepository userRepository; // Просейший GET метод // Доступ по адресу: // http://localhost:8080/ @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } // Метод, который конвертирует Java класс в JSON данные // http://localhost:8080/user @RequestMapping("/user") @ResponseBody User user() { return new User("Anton", "12345678"); } // Метод, который получает JSON данные и сохраняет их в БД // http://localhost:8080/custom-user @RequestMapping("/custom-user") @ResponseBody User userFrom(@RequestBody User user) { return userRepository.save(user); } // Метод, который обращается к БД и выводит все записи о пользователей // в JSON массиве @RequestMapping("/users-all") @ResponseBody List<User> userAll() { return userRepository.findAll(); } }
Java
CL
b757633a0719e33c40e4596bb3013bc61920b098c7e57e7ef2d1fb1b72a517db
package com.example.uclone; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.location.Location; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.core.content.ContextCompat; import androidx.core.graphics.drawable.DrawableCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Handler; import android.os.Parcel; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.directions.route.AbstractRouting; import com.directions.route.Route; import com.directions.route.RouteException; import com.directions.route.Routing; import com.directions.route.RoutingListener; import com.firebase.geofire.GeoFire; import com.firebase.geofire.GeoLocation; import com.firebase.geofire.GeoQuery; import com.firebase.geofire.GeoQueryEventListener; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.ResolvableApiException; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResponse; import com.google.android.gms.location.SettingsClient; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.libraries.places.api.Places; import com.google.android.libraries.places.api.model.AutocompletePrediction; import com.google.android.libraries.places.api.model.AutocompleteSessionToken; import com.google.android.libraries.places.api.model.Place; import com.google.android.libraries.places.api.model.TypeFilter; import com.google.android.libraries.places.api.net.FetchPlaceRequest; import com.google.android.libraries.places.api.net.FetchPlaceResponse; import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest; import com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse; import com.google.android.libraries.places.api.net.PlacesClient; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.karumi.dexter.Dexter; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionDeniedResponse; import com.karumi.dexter.listener.PermissionGrantedResponse; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.single.PermissionListener; import com.mancj.materialsearchbar.MaterialSearchBar; import com.mancj.materialsearchbar.adapter.SuggestionsAdapter; import com.skyfishjy.library.RippleBackground; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; import static android.app.Activity.RESULT_OK; import static android.content.Context.INPUT_METHOD_SERVICE; /** * A simple {@link Fragment} subclass. */ public class MapFragment extends Fragment implements OnMapReadyCallback, RoutingListener { private final int LOCATION_REQUEST_CODE = 100; private final float DEFAULT_ZOOM = 15; private RecyclerView recyclerView; private final String TAG = "MAP FRAGMENT"; public static List<getdoctorordriver> getdoctorordriverList; private double latitude,longitude; private View mView, mapView; RelativeLayout relat; private ImageView mLocationPin; private TextView mDriverName, mDriverVehicle, mDriverTime, getmDriverRating; private CircleImageView mDriverProfileImage; private GoogleMap mMap; private Marker mCustomerMarker; private Marker mHelpMarker; private FusedLocationProviderClient mFusedLocationProviderClient; private PlacesClient mPlacesClient; private List<AutocompletePrediction> autocompletePredictionList; private Location mLastKnownLocation; private LocationCallback locationCallback; private MaterialSearchBar mMaterialSearchBar; final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance(); private RippleBackground mRippleBg; private Button mGo, mCancelRequest,chat; private BottomSheetDialog selectRideSheetDialog; private boolean mCarSelect = true, mBikeSelect, mRequestBol = false; private Routing routing; private List<Polyline> polylines; private LatLng currentMarkerLocation; private BottomSheetBehavior sheetBehavior; private LinearLayout layoutBottomSheet; public MapFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment mView = inflater.inflate(R.layout.fragment_map, container, false); getdoctorordriverList = new ArrayList<>(); PreferencesClass preferencesClass = new PreferencesClass(getActivity()); Log.i(TAG, preferencesClass.getUSER_NAME()); Log.i(TAG, preferencesClass.getUSER_EMAIL()); Log.i(TAG, preferencesClass.getUserContact()); recyclerView = mView.findViewById(R.id.recyclerview); recyclerView.setHasFixedSize(true); relat = mView.findViewById(R.id.relat); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); llm.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(llm); init(); FirebaseDatabase.getInstance().getReference().child("Users").child("Patient").child(FirebaseAuth.getInstance().getUid()).child("status").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.getValue().toString().equals("0")){ mGo.setEnabled(false); mGo.setText("A request is in progress"); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); return mView; } @SuppressLint("MissingPermission") @Override public void onMapReady(final GoogleMap googleMap) { Dexter.withActivity(getActivity()) .withPermission(Manifest.permission.ACCESS_FINE_LOCATION) .withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { mMap = googleMap; mMap.setMyLocationEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(true); // moveCamera(new LatLng(-34, 151),"Me"); if (mapView != null && mapView.findViewById(Integer.parseInt("1")) != null) { View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2")); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams(); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); layoutParams.setMargins(0, 0, 40, 180); } //check if gps is enabled or not and then request user to enable it LocationRequest locationRequest = LocationRequest.create(); locationRequest.setInterval(10000); locationRequest.setFastestInterval(5000); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest); SettingsClient settingsClient = LocationServices.getSettingsClient(getActivity()); Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build()); task.addOnSuccessListener(getActivity(), new OnSuccessListener<LocationSettingsResponse>() { @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { getDeviceLocation(); } }); task.addOnFailureListener(getActivity(), new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e instanceof ResolvableApiException) { ResolvableApiException resolvable = (ResolvableApiException) e; try { // resolvable.startResolutionForResult(getActivity(), LOCATION_REQUEST_CODE); startIntentSenderForResult(resolvable.getResolution().getIntentSender(), LOCATION_REQUEST_CODE, null, 0, 0, 0, null); } catch (IntentSender.SendIntentException e1) { e1.printStackTrace(); } } } }); mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() { @Override public void onCameraMove() { } }); mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() { @Override public boolean onMyLocationButtonClick() { if (mMaterialSearchBar.isSuggestionsVisible()) mMaterialSearchBar.clearSuggestions(); if (mMaterialSearchBar.isSearchEnabled()) mMaterialSearchBar.disableSearch(); return false; } }); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { if (response.isPermanentlyDenied()) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Permission Denied") .setMessage("Permission to access device location is permanently denied. you need to go to setting to allow the permission.") .setNegativeButton("Cancel", null) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); // intent.setData(Uri.fromParts("package", getActivity(), null)); } }) .show(); } else { Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_SHORT).show(); } } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { token.continuePermissionRequest(); } }) .check(); } private void init() { SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); mapView = mapFragment.getView(); layoutBottomSheet = mView.findViewById(R.id.bottom_sheet_layout); sheetBehavior = BottomSheetBehavior.from(layoutBottomSheet); sheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); polylines = new ArrayList<>(); mMaterialSearchBar = mView.findViewById(R.id.searchBar); mGo = mView.findViewById(R.id.btn_go); chat = mView.findViewById(R.id.chatbutton); mCancelRequest = mView.findViewById(R.id.btn_cancel_request); mRippleBg = mView.findViewById(R.id.ripple_bg); mLocationPin = mView.findViewById(R.id.location_pin); mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity()); Places.initialize(getActivity(), getString(R.string.GOOGLE_API)); mPlacesClient = Places.createClient(getActivity()); final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance(); mDriverName = mView.findViewById(R.id.sheet_name); mDriverVehicle = mView.findViewById(R.id.sheet_vehicle); mDriverProfileImage = mView.findViewById(R.id.sheet_profile_image); mMaterialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() { @Override public void onSearchStateChanged(boolean enabled) { } @Override public void onSearchConfirmed(CharSequence text) { getActivity().startSearch(text.toString(), true, null, true); } @Override public void onButtonClicked(int buttonCode) { if (buttonCode == MaterialSearchBar.BUTTON_NAVIGATION) { //opening or closing a navigation drawer } else if (buttonCode == MaterialSearchBar.BUTTON_BACK) { mMaterialSearchBar.disableSearch(); } } }); chat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FirebaseDatabase.getInstance().getReference("Users").child("Patient").child(FirebaseAuth.getInstance().getUid()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Intent intent = new Intent(getActivity(),MessagingActivity.class); intent.putExtra("driverId",dataSnapshot.child("dora").getValue().toString()); intent.putExtra("driverName","Medical assitant"); startActivity(intent); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }); mMaterialSearchBar.addTextChangeListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { final FindAutocompletePredictionsRequest predictionsRequest = FindAutocompletePredictionsRequest.builder() .setCountry("pk") .setSessionToken(token) .setQuery(charSequence.toString()) .build(); mPlacesClient.findAutocompletePredictions(predictionsRequest).addOnCompleteListener(new OnCompleteListener<FindAutocompletePredictionsResponse>() { @Override public void onComplete(@NonNull Task<FindAutocompletePredictionsResponse> task) { if (task.isSuccessful()) { FindAutocompletePredictionsResponse predictionsResponse = task.getResult(); if (predictionsResponse != null) { autocompletePredictionList = predictionsResponse.getAutocompletePredictions(); List<String> suggestionsList = new ArrayList<>(); for (AutocompletePrediction autocompletePrediction : autocompletePredictionList) { suggestionsList.add(autocompletePrediction.getFullText(null).toString()); } mMaterialSearchBar.updateLastSuggestions(suggestionsList); if (!mMaterialSearchBar.isSuggestionsVisible()) { mMaterialSearchBar.showSuggestionsList(); } } } else { Log.i(TAG, task.getException().toString()); } } }); } @Override public void afterTextChanged(Editable editable) { } }); mMaterialSearchBar.setSuggestionsClickListener(new SuggestionsAdapter.OnItemViewClickListener() { @Override public void OnItemClickListener(int position, View v) { if (position >= autocompletePredictionList.size()) { return; } AutocompletePrediction selectedPrediction = autocompletePredictionList.get(position); String suggestion = mMaterialSearchBar.getLastSuggestions().get(position).toString(); mMaterialSearchBar.setText(suggestion); new Handler().postDelayed(new Runnable() { @Override public void run() { mMaterialSearchBar.clearSuggestions(); } }, 1000); InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE); if (imm != null) imm.hideSoftInputFromWindow(mMaterialSearchBar.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY); final String placeId = selectedPrediction.getPlaceId(); List<Place.Field> placeFields = Arrays.asList(Place.Field.LAT_LNG); FetchPlaceRequest fetchPlaceRequest = FetchPlaceRequest.builder(placeId, placeFields).build(); mPlacesClient.fetchPlace(fetchPlaceRequest).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() { @Override public void onSuccess(FetchPlaceResponse fetchPlaceResponse) { Place place = fetchPlaceResponse.getPlace(); Log.i(TAG, "Place found: " + place.getName()); LatLng latLngOfPlace = place.getLatLng(); if (latLngOfPlace != null) { currentMarkerLocation = mMap.getCameraPosition().target; if (mCustomerMarker != null) mCustomerMarker = null; LatLngBounds.Builder builder = new LatLngBounds.Builder(); builder.include(currentMarkerLocation); builder.include(latLngOfPlace); LatLngBounds bounds = builder.build(); int width = getResources().getDisplayMetrics().widthPixels; int padding = (int) (width * 0.2); mLocationPin.setVisibility(View.GONE); CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding); mMap.animateCamera(cameraUpdate); mMap.addMarker(new MarkerOptions().position(latLngOfPlace).title("Destination")); mMap.addMarker(new MarkerOptions().position(currentMarkerLocation).title("Pick Up")).setIcon(getMarkerIconFromDrawable( getResources().getDrawable(R.drawable.ic_location_pin))); getRouteToMarker(currentMarkerLocation, latLngOfPlace); showSelectBottomSheetDialog(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e instanceof ApiException) { ApiException apiException = (ApiException) e; apiException.printStackTrace(); int statusCode = apiException.getStatusCode(); Log.i(TAG, "place not found: " + e.getMessage()); Log.i(TAG, "status code: " + statusCode); } } }); } @Override public void OnItemDeleteListener(int position, View v) { } }); mGo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showSelectBottomSheetDialog(); } }); mCancelRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { endRide(); } }); setupLocationStream(); } private void moveCamera(LatLng latLng, String title) { mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM)); } @Override public void onStart() { super.onStart(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == LOCATION_REQUEST_CODE) { if (resultCode == RESULT_OK) { getDeviceLocation(); } } } @SuppressLint("MissingPermission") private void getDeviceLocation() { mFusedLocationProviderClient.getLastLocation() .addOnCompleteListener(new OnCompleteListener<Location>() { @Override public void onComplete(@NonNull Task<Location> task) { if (task.isSuccessful()) { mLastKnownLocation = task.getResult(); if (mLastKnownLocation != null) { moveCamera(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), "Pick Up"); } else { final LocationRequest locationRequest = LocationRequest.create(); locationRequest.setInterval(10000); locationRequest.setFastestInterval(5000); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { super.onLocationResult(locationResult); if (locationResult == null) { return; } mLastKnownLocation = locationResult.getLastLocation(); moveCamera(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), "Pick Up"); mFusedLocationProviderClient.removeLocationUpdates(locationCallback); } }; mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null); } } else { Toast.makeText(getActivity(), "unable to get last location", Toast.LENGTH_SHORT).show(); } } }); } private void showSelectBottomSheetDialog() { if (selectRideSheetDialog == null) { View view = LayoutInflater.from(getActivity()).inflate(R.layout.select_ride_bottom_sheet_layout, null); final TextView carSelect = view.findViewById(R.id.car_select); final TextView bikeSelect = view.findViewById(R.id.bike_select); Button request = view.findViewById(R.id.btn_request); Button cancel = view.findViewById(R.id.btn_cancel); carSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bikeSelect.setBackground(null); carSelect.setBackgroundResource(R.drawable.selected_ride_background); mBikeSelect = false; mCarSelect = true; } }); bikeSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { carSelect.setBackground(null); bikeSelect.setBackgroundResource(R.drawable.selected_ride_background); mBikeSelect = true; mCarSelect = false; } }); request.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "CAR: " + mCarSelect + " BIKE: " + mBikeSelect); selectRideSheetDialog.dismiss(); if (mLocationPin.getVisibility() == View.GONE) { mMap.clear(); mLocationPin.setVisibility(View.VISIBLE); moveCamera(currentMarkerLocation, "Pick Up"); } else currentMarkerLocation = mMap.getCameraPosition().target; String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("customerRequest"); GeoFire geoFire = new GeoFire(ref); geoFire.setLocation(userId, new GeoLocation(currentMarkerLocation.latitude, currentMarkerLocation.longitude), new GeoFire.CompletionListener() { @Override public void onComplete(String key, DatabaseError error) { //Do some stuff if you want to } }); if (mCustomerMarker != null) mCustomerMarker = null; mCancelRequest.setVisibility(View.VISIBLE); mGo.setText("Getting your Driver...."); mRippleBg.startRippleAnimation(); if (mCarSelect){ getCloserDriver("Doctor"); } else{ getCloserDriver("ambulance"); } } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectRideSheetDialog.dismiss(); getDeviceLocation(); mMap.clear(); mLocationPin.setVisibility(View.VISIBLE); } }); selectRideSheetDialog = new BottomSheetDialog(getActivity()); selectRideSheetDialog.setContentView(view); selectRideSheetDialog.setCanceledOnTouchOutside(false); selectRideSheetDialog.setCancelable(false); } selectRideSheetDialog.show(); } private String driverFoundId; GeoQuery geoQuery; private void getCloserDriver(final String userfor) { FirebaseDatabase.getInstance().getReference("Users").child(userfor).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { float[] results = new float[1]; getdoctorordriverList.clear(); for (DataSnapshot snapshot:dataSnapshot.getChildren()){ if (snapshot.child("status").getValue().equals("1")){ String[] getvv = snapshot.child("latlng").getValue().toString().split(","); latitude = Double.parseDouble(getvv[0]); longitude = Double.parseDouble(getvv[1]); android.location.Location. distanceBetween(currentMarkerLocation.latitude, currentMarkerLocation.longitude, latitude, longitude, results); float distanceInMeters = results[0]; boolean isWithin10km = distanceInMeters < 5000; if (isWithin10km) { if(userfor.equals("ambulance")){ getdoctorordriverList.add(new getdoctorordriver(snapshot.child("name").getValue().toString(), snapshot.child("profileImageUrl").getValue().toString(),snapshot.child("address").getValue().toString(), snapshot.child("contact").getValue().toString(), snapshot.getKey(),userfor)); } else{ getdoctorordriverList.add(new getdoctorordriver(snapshot.child("name").getValue().toString(), snapshot.child("profileImageUrl").getValue().toString(),snapshot.child("address").getValue().toString(), snapshot.child("contact").getValue().toString(),"",snapshot.child("specialization").getValue().toString(), snapshot.getKey(),userfor)); } } } } if (getdoctorordriverList.size() >0){ relat.setVisibility(View.GONE); NearbydriverorDoctoradapter nearbydriverorDoctoradapter = new NearbydriverorDoctoradapter(getdoctorordriverList,getActivity()); recyclerView.setAdapter(nearbydriverorDoctoradapter); recyclerView.setVisibility(View.VISIBLE); } else{ driverNotFound(); Toast.makeText(getActivity(), "No Driver Found!", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } DatabaseReference driverLocRef; private ValueEventListener driverLocRefListener; private Marker marker; public static BitmapDescriptor getBitmapDesFromVectorDrawable(Context context, int drawableId) { Drawable drawable = ContextCompat.getDrawable(context, drawableId); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { drawable = (DrawableCompat.wrap(drawable)).mutate(); } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Bitmap bitmapICon = Bitmap.createScaledBitmap(bitmap, 60, 60, false); Canvas canvas = new Canvas(bitmapICon); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return BitmapDescriptorFactory.fromBitmap(bitmapICon); } private BitmapDescriptor getMarkerIconFromDrawable(Drawable drawable) { Canvas canvas = new Canvas(); Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return BitmapDescriptorFactory.fromBitmap(bitmap); } private void getRouteToMarker(LatLng place1, LatLng place2) { routing = new Routing.Builder() .key(getResources().getString(R.string.GOOGLE_API)) .travelMode(AbstractRouting.TravelMode.DRIVING) .withListener(this) .alternativeRoutes(false) .waypoints(place1, place2) .build(); routing.execute(); } @Override public void onRoutingFailure(RouteException e) { try{ if (e != null) { Log.i(TAG, e.getMessage()); } else { Toast.makeText(getActivity(), "Something went wrong, Try again", Toast.LENGTH_SHORT).show(); } } catch (Exception ee){} } @Override public void onRoutingStart() { } @Override public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) { if (polylines.size() > 0) { for (Polyline poly : polylines) { poly.remove(); } } chat.setVisibility(View.VISIBLE); Log.d("LOCATION TRACKING",route.size()+""); polylines = new ArrayList<>(); //add route(s) to the map. for (int i = 0; i < route.size(); i++) { PolylineOptions polyOptions = new PolylineOptions(); polyOptions.color(getResources().getColor(R.color.colorPrimary)); polyOptions.width(10 + i * 3); polyOptions.addAll(route.get(i).getPoints()); Polyline polyline = mMap.addPolyline(polyOptions); polylines.add(polyline); } } private void driverDocFound(){ mRippleBg.stopRippleAnimation(); mCancelRequest.setVisibility(View.GONE); mMaterialSearchBar.setVisibility(View.GONE); mGo.setVisibility(View.GONE); mLocationPin.setVisibility(View.GONE); relat.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.GONE); } private void driverNotFound() { mCancelRequest.setVisibility(View.GONE); mMaterialSearchBar.setVisibility(View.VISIBLE); mGo.setVisibility(View.VISIBLE); mGo.setText(getResources().getString(R.string.lets_go)); mMap.clear(); mLocationPin.setVisibility(View.VISIBLE); mRippleBg.stopRippleAnimation(); } private void endRide() { driverNotFound(); chat.setVisibility(View.GONE); mGo.setVisibility(View.VISIBLE); //dothis mCustomerMarker = null; mHelpMarker = null; FirebaseDatabase.getInstance() .getReference("Users") .child("Patient") .child(FirebaseAuth.getInstance().getUid()) .child("status") .setValue("1"); } @Override public void onRoutingCancelled() { } private void setupLocationStream(){ DatabaseReference trackingRequest = FirebaseDatabase.getInstance() .getReference("Users") .child("Patient") .child(FirebaseAuth.getInstance().getUid()) .child("dora"); trackingRequest.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()) { listenForLocationStream(dataSnapshot.getValue().toString()); } else{ endRide(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void listenForLocationStream(final String uid){ DatabaseReference customerRequest = FirebaseDatabase.getInstance() .getReference("customerRequest") .child(FirebaseAuth.getInstance().getUid()) .child("l"); customerRequest.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()) { LatLng latLng = new LatLng(Double.parseDouble(dataSnapshot.child("0").getValue().toString()) , Double.parseDouble(dataSnapshot.child("1").getValue().toString())); mCustomerMarker = mMap.addMarker(new MarkerOptions().position(latLng).title("Me")); driverDocFound(); makeRoute(uid, latLng); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void makeRoute(String uid, final LatLng latLng){ DatabaseReference tracking = FirebaseDatabase.getInstance() .getReference("Tracking") .child(uid); tracking.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()) { String lat = dataSnapshot.child("lat").getValue().toString(); String lng = dataSnapshot.child("lng").getValue().toString(); LatLng latLng1 = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)); if (mHelpMarker == null) { mCustomerMarker.setIcon(getMarkerIconFromDrawable(getResources().getDrawable(R.drawable.ic_location_pin))); mHelpMarker = mMap.addMarker(new MarkerOptions().position(latLng1).title("Medical Assistance")); mHelpMarker.setIcon(getMarkerIconFromDrawable(getResources().getDrawable(R.drawable.hospital_opt))); latLngBoundCamera(latLng1,latLng); } else { mHelpMarker.setPosition(latLng1); } getRouteToMarker(latLng1, latLng); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void latLngBoundCamera(LatLng l, LatLng ln){ LatLngBounds.Builder builder = new LatLngBounds.Builder(); builder.include(l); builder.include(ln); LatLngBounds bounds = builder.build(); int width = getResources().getDisplayMetrics().widthPixels; int padding = (int) (width * 0.2); CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding); mMap.animateCamera(cameraUpdate); } }
Java
CL
d8b5ad84f864212b8d6420293dcb16d4cb7c54db0ec6f7e7dda87040d4e2691a
package server; import Client.ClientGUI; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import database.Directory; import database.DirectoryRepository; import database.User; import database.UserRepository; import library.Messages; import network.ServerSocketThread; import network.ServerSocketThreadListener; import network.SocketThread; import network.SocketThreadListener; import org.apache.log4j.Logger; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.List; import java.util.Vector; import static com.google.common.base.Preconditions.checkState; /** Dropbox server. */ public class DropboxServer implements ServerSocketThreadListener, SocketThreadListener { private static Logger logger = Logger.getLogger(DropboxServer.class); private final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss: "); private final DropboxServerListener eventListener; private final AuthService authService; private ServerSocketThread serverSocketThread; private final Vector<SocketThread> clients = new Vector<>(); private final DirectoryRepository directoryRepository; private final UserRepository userRepository; public DropboxServer(DropboxServerListener eventListener, AuthService authService, DirectoryRepository directoryRepository, UserRepository userRepository) { this.eventListener = eventListener; this.authService = authService; this.directoryRepository = directoryRepository; this.userRepository = userRepository; } public void startListening(int port) { if(serverSocketThread != null && serverSocketThread.isAlive()) { putLog("Server thread already started."); return; } serverSocketThread = new ServerSocketThread(this, "ServerSocketThread", port, 2000); authService.start(); } public synchronized void dropAllClients() { for (int i = 0; i < clients.size(); i++) clients.get(i).close(); } public void stopListening() { if(serverSocketThread == null || !serverSocketThread.isAlive()) { putLog("Server thread is not started."); return; } serverSocketThread.interrupt(); authService.stop(); } private synchronized void putLog(String msg) { String msgLog = dateFormat.format(System.currentTimeMillis()); msgLog += Thread.currentThread().getName() + ": " + msg; eventListener.onLogChatServer(this, msgLog); } @Override public void onStartServerSocketThread(ServerSocketThread thread) { putLog("started..."); } @Override public void onStopServerSocketThread(ServerSocketThread thread) { putLog("stopped."); } @Override public void onReadyServerSocketThread(ServerSocketThread thread, ServerSocket serverSocket) { putLog("ServerSocket is ready..."); } @Override public void onTimeOutAccept(ServerSocketThread thread, ServerSocket serverSocket) { // putLog("accept() timeout"); } @Override public void onAcceptedSocket(ServerSocketThread thread, ServerSocket serverSocket, Socket socket) { putLog("Client connected: " + socket); String threadName = "Socket thread: " + socket.getInetAddress() + ":" + socket.getPort(); new DropboxSocketThread(this, threadName, socket); } @Override public void onExceptionServerSocketThread(ServerSocketThread thread, Exception e) { putLog("Exception: " + e.getClass().getName() + ": " + e.getMessage()); } @Override public synchronized void onStartSocketThread(SocketThread socketThread) { putLog("started..."); } @Override public synchronized void onStopSocketThread(SocketThread socketThread) { putLog("stopped."); clients.remove(socketThread); DropboxSocketThread client = (DropboxSocketThread) socketThread; if(client.isAuthorized() && !client.isReconnected()) { sendToAllAuthorizedClients(Messages.getBroadcast("server", client.getNickname() + " disconnected.")); sendToAllAuthorizedClients(Messages.getFilesList(getAllNicknamesString())); } } @Override public synchronized void onReadySocketThread(SocketThread socketThread, Socket socket) { putLog("Socket is ready."); clients.add(socketThread); } @Override public synchronized void onReceiveString(SocketThread socketThread, Socket socket, String value) { DropboxSocketThread client = (DropboxSocketThread) socketThread; if(client.isAuthorized()) { handleAuthorizeClient(client, value); } else { handleNonAuthorizeClient(client, value); } } private void handleAuthorizeClient(DropboxSocketThread client, String msg) { List<String> tokens = Splitter.on(Messages.DELIMITER).splitToList(msg); String type = tokens.get(0); String login = client.getNickname(); Directory directory = getDirectory(login); switch (type) { case Messages.FILES_LIST: client.sendMsg(getFilesList(directory)); break; case Messages.FILE_UPLOAD: logger.debug("File uploading started."); Path path = Paths.get(directory.path, tokens.get(1)); File file = path.toFile(); try { file.createNewFile(); ReceiveFileThread receiveFileThread = new ReceiveFileThread(file); logger.debug("Created ReceiveFileThread object: " + receiveFileThread); client.sendMsg(Messages.getSocketOpened(receiveFileThread.getPort(), tokens.get(2))); logger.debug(String.format("port: %d", receiveFileThread.getPort())); receiveFileThread.start(); logger.debug("File is uploaded."); client.sendMsg(getFilesList(directory)); } catch (IOException e) { } } } private Directory getDirectory(String login) { User user = userRepository.findByLogin(login); checkState(user != null, String.format("Did not find user for login: %s", login)); Directory directory = directoryRepository.findByUserId(user.id); checkState(directory != null, String.format( "Did not find dicrectory for userId: %s (login: %s)", user.id, login)); return directory; } private String getFilesList(Directory directory) { File[] listOfFiles = FileSystemUtil.getFilesFromDirectory(directory.path); String[] filesNames = new String[listOfFiles.length]; for (int i = 0; i < listOfFiles.length; i++) { filesNames[i] = listOfFiles[i].getName(); } String files = Joiner.on(Messages.DELIMITER).join(filesNames); String response = Messages.getFilesList(files); return response; } private void sendToAllAuthorizedClients(String msg) { for (int i = 0; i < clients.size(); i++) { DropboxSocketThread client = (DropboxSocketThread) clients.get(i); if(client.isAuthorized()) client.sendMsg(msg); } } private void handleNonAuthorizeClient(DropboxSocketThread newClient, String msg) { String tokens[] = msg.split(Messages.DELIMITER); if(tokens.length != 3 || !tokens[0].equals(Messages.AUTH_REQUEST)) { newClient.messageFormatError(msg); return; } String login = tokens[1]; String password = tokens[2]; String nickname = authService.getNickname(login, password); if(nickname == null) { newClient.authError(); return; } DropboxSocketThread oldClient = getClientByNickname(nickname); newClient.authAccept(nickname); if (oldClient == null) { sendToAllAuthorizedClients(Messages.getBroadcast("server", newClient.getNickname() + " connected.")); } else { oldClient.reconnected(); } } private DropboxSocketThread getClientByNickname(String nickname) { final int cnt = clients.size(); for (int i = 0; i < cnt; i++) { DropboxSocketThread client = (DropboxSocketThread) clients.get(i); if(!client.isAuthorized()) continue; if(client.getNickname().equals(nickname)) return client; } return null; } private String getAllNicknamesString() { StringBuilder sb = new StringBuilder(); final int cnt = clients.size(); final int last = cnt - 1; for (int i = 0; i < cnt; i++) { DropboxSocketThread client = (DropboxSocketThread) clients.get(i); if(!client.isAuthorized() || client.isReconnected()) continue; sb.append(client.getNickname()); if(i != last) sb.append(Messages.DELIMITER); } return sb.toString(); } private String[] getFilesList() { String[] files = {"1", "2", "3"}; return files; } @Override public synchronized void onExceptionSocketThread(SocketThread socketThread, Socket socket, Exception e) { putLog("Exception: " + e); } }
Java
CL
cd7bb3005f03fb57d91950670570ceab410814acd95e62b5e12cb9021d78bf02
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.synapse.generated; import com.azure.core.util.BinaryData; import com.azure.resourcemanager.synapse.models.GetSsisObjectMetadataRequest; import org.junit.jupiter.api.Assertions; public final class GetSsisObjectMetadataRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GetSsisObjectMetadataRequest model = BinaryData.fromString("{\"metadataPath\":\"prltzkatbhjmz\"}").toObject(GetSsisObjectMetadataRequest.class); Assertions.assertEquals("prltzkatbhjmz", model.metadataPath()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { GetSsisObjectMetadataRequest model = new GetSsisObjectMetadataRequest().withMetadataPath("prltzkatbhjmz"); model = BinaryData.fromObject(model).toObject(GetSsisObjectMetadataRequest.class); Assertions.assertEquals("prltzkatbhjmz", model.metadataPath()); } }
Java
CL
e668b71c8207d7f1cc4e4f6f0def54e37072447c04c074d854a6c8698d62139d
package com.bis.common; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.lang.StringUtils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.apache.log4j.Logger; import com.bis.common.conf.Params; public class Util { private static final Logger LOG = Logger.getLogger(Util.class); private Util() { } /** * 判断是否是MAC地址格式 * * @param mac * @return */ public static boolean isMac(String mac) { boolean result = false; // 正则校验MAC合法性 String patternMac = "^[A-F0-9]{2}([:-]{1}[A-F0-9]{2}){5}$"; if (Pattern.compile(patternMac).matcher(mac).find()) { result = true; } return result; } /** * 根据格式判断是ip或者mac进行转换 * * @param macOrIp * @return */ public static String convertMacOrIp(String macOrIp) { String result = ""; if (!StringUtils.isEmpty(macOrIp)) { String macOrIpt = macOrIp.toUpperCase().trim(); if (isMac(macOrIpt)) { result = convertMac(macOrIpt); } else { result = convertIp(macOrIpt); } } return result.trim(); } /** * mac转换16进制 * * @param mac * @return */ public static String convertMac(String mac) { String result = mac.replaceAll("-", ""); result = result.replaceAll(":", ""); result = result.toLowerCase(); return result; } /** * 16进制转换成ip地址 * * @param ip * @return */ public static String convert(String ip) { Integer te = Integer.valueOf(ip, 16); int i = te.intValue(); return (i >> 24 & 0xFF) + '.' + ((i >> 16) & 0xFF) + String.valueOf('.') + ((i >> 8) & 0xFF) + '.' + (i & 0xFF); } /** * ip地址转换16进制 * * @param ip * @return */ public static String convertIp(String ip) { String[] iplist = ip.split("\\."); Logger.getLogger(Util.class).error("123456789ip:" + iplist); int ip0 = Integer.parseInt(iplist[0]); int ip1 = Integer.parseInt(iplist[1]); int ip2 = Integer.parseInt(iplist[2]); int ip3 = Integer.parseInt(iplist[3]); String result = Integer.toHexString((ip0 << 24) + (ip1 << 16) + (ip2 << 8) + ip3); for (int i = result.length(); i < 8; i++) { result = '0' + result; } return result; } /** * 日期型转指定格式字符型 * * @param date * 日期 * @param format * 格式,如:yyyy-MM-dd HH:mm:ss * @return */ public static String dateFormat(Date date, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.format(date); } /** * 时间戳转指定格式字符型 * * @param timestamp * 时间戳 * @param format * 格式,如:yyyy-MM-dd HH:mm:ss * @return */ public static String dateFormat(long timestamp, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.format(timestamp); } /** * 时间字符型转个时间戳 * * @param timestamp * 时间戳 * @param format * 格式,如:yyyy-MM-dd HH:mm:ss * @return */ public static long dateFormatStringtoLong(String data, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); Date da = null; try { da = formatter.parse(data); } catch (ParseException e) { Logger.getLogger(Util.class).info(e); } return da.getTime(); } /** * 字符型日期转指定格式字符型 * * @param date * 日期字符串 * @param format * 格式,如:yyyy-MM-dd HH:mm:ss * @return */ public static Date dateStringFormat(String date, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); Date result = null; try { result = formatter.parse(date); } catch (Exception e) { Logger.getLogger(Util.class).info(e); } return result; } /** * @Title: getRangeDay @Description: 获取两个时间之间的日期数组,格式由参数format决定 @param * start 开始时间 @param end 结束时间 @param format 日期格式 @return List * <String> @throws */ public static List<String> getRangeDay(Date start, Date end, String format) { // 返回值 List<String> result = new ArrayList<String>(); // 日历型 用于日期加法,设置起始为start Calendar c = Calendar.getInstance(); c.setTime(start); Date tempDate = new Date(start.getTime()); // 当起始日期小于等于结束日期,运行循环体内逻辑 while (tempDate.getTime() <= end.getTime()) { // 将该起始日期转换格式后添加进返回数组中 result.add(dateFormat(start, format)); // 日期加1后 作为新的起始日期 c.add(Calendar.DATE, 1); tempDate = c.getTime(); } return result; } /** * @Title: getMinute * @Description:秒转为分,保留两位小数 * @param time * @param size * @return */ public static String getMinute(long time, int size) { if (size == 0) { return "0"; } else { float b = (time / 1000) / 60; float averageTime = b / size; DecimalFormat df = new DecimalFormat("0.00"); return df.format(averageTime); } } /** * * @Title: getTwoPointNumber * @Description: float保留两位小数 * @param f * @return */ public static float getTwoPointNumber(float f) { if (f == 0) { return 0; } else { DecimalFormat df = new DecimalFormat("0.00"); return Float.parseFloat(df.format(f)); } } /** * * @Title: sToM * @Description: 秒转化为带两位小数点的分 * @param f * @return */ public static float sToM(float f) { if (f == 0) { return 0; } else { int a = (int) (f / 60); float b = (f % 60) / 60; DecimalFormat df = new DecimalFormat("0.00"); return a + Float.parseFloat(df.format(b)); } } /** * * @Title: getAge * @Description: 生日转化为岁数 * @param birthDate * @return */ public static int getAge(Date birthDate) { if (birthDate == null) throw new RuntimeException("出生日期不能为null"); int age = 0; Date now = new Date(); SimpleDateFormat format_y = new SimpleDateFormat("yyyy"); SimpleDateFormat format_M = new SimpleDateFormat("MM"); String birth_year = format_y.format(birthDate); String this_year = format_y.format(now); String birth_month = format_M.format(birthDate); String this_month = format_M.format(now); // 初步,估算 age = Integer.parseInt(this_year) - Integer.parseInt(birth_year); // 如果未到出生月份,则age - 1 if (this_month.compareTo(birth_month) < 0) age -= 1; if (age < 0) age = 0; return age; } /** * * @param startTime * 开始时间 * @param endTime * 结束时间 * @param flag * 时间段标识,1:day,2:mouth * @return */ public static Map<String, Object> getPeriodList(String startTime, String endTime, int flag) { Map<String, Object> result = new HashMap<String, Object>(2); Date start = Util.dateStringFormat(startTime, Params.YYYYMMDDHHMMSS); Date end = Util.dateStringFormat(endTime, Params.YYYYMMDDHHMMSS); Calendar cal = Calendar.getInstance(); cal.setTime(start); Date tmpDate = cal.getTime(); long endTimeInSec = end.getTime(); if (flag == 1) { long time = tmpDate.getTime(); String keyTime; Boolean b = tmpDate.before(end); while (b || time == endTimeInSec) { b = tmpDate.before(end); keyTime = Util.dateFormat(cal.getTime(), Params.YYYYMMDD2); result.put(keyTime, 0); cal.add(Calendar.DATE, 1); tmpDate = cal.getTime(); } } else if (flag == 2) { long time = tmpDate.getTime(); String keyTime; Boolean b = tmpDate.before(end); while (b || time == endTimeInSec) { b = tmpDate.before(end); keyTime = Util.dateFormat(cal.getTime(), Params.YYYYMMM); result.put(keyTime, 0); cal.add(Calendar.MONTH, 1); tmpDate = cal.getTime(); } } return result; } /** * * @Title: getPeriodMonthList * @Description: 得到一定时间段的月度驻留统计表名 * @param startTime * @param endTime * @return */ public static List<String> getPeriodMonthList(String startTime, String endTime) { Map<String, Object> result = new HashMap<String, Object>(); Date start = Util.dateStringFormat(startTime, Params.YYYYMMDD2); Date end = Util.dateStringFormat(endTime, Params.YYYYMMDD2); List<String> dateList = new ArrayList<>(); Calendar cal = Calendar.getInstance(); cal.setTime(start); String keyTime; while (!cal.getTime().after(end)) { keyTime = Util.dateFormat(cal.getTime(), Params.YYYYMM); dateList.add(Params.SHOPLOCATION + keyTime); cal.add(Calendar.MONTH, 1); } return dateList; } /** * * @Title: getLastNumMonths * @Description: 取得过去num个月的指定格式数组 * @param num * @param format * @return */ public static String[] getLastNumMonths(int num, String format) { Calendar cal = Calendar.getInstance(); String[] result = new String[num]; for (int i = num - 1; i >= 0; i--) { cal.add(Calendar.MONTH, -1); String str = Util.dateFormat(cal.getTime(), format); result[i] = str; } return result; } public static String getDouble(int count, int allcount) { DecimalFormat df = new DecimalFormat("######0.00"); String result = df.format((((float) (allcount / count)) * 2 / 60)); return result; } /** * * @Title: getLastNumDays * @Description: 取得过去num天的指定格式数组 * @param num * @param format * @return */ public static String[] getLastNumDays(int num, String format) { Calendar cal = Calendar.getInstance(); String[] result = new String[num]; for (int i = num - 1; i >= 0; i--) { cal.add(Calendar.DATE, -1); String str = Util.dateFormat(cal.getTime(), format); result[i] = str; } return result; } /** * @Title: getSHA256 * @Description: SHA256加密 * @param msg * 要加密的信息 * @return */ public static String getSHA256(String msg) { MessageDigest messageDigest; String encodeStr = ""; try { messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(msg.getBytes("UTF-8")); encodeStr = byte2Hex(messageDigest.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encodeStr; } private static String byte2Hex(byte[] bytes) { StringBuffer stringBuffer = new StringBuffer(); String temp = null; for (int i = 0; i < bytes.length; i++) { temp = Integer.toHexString(bytes[i] & 0xFF); if (temp.length() == 1) { // 1得到一位的进行补0操作 stringBuffer.append("0"); } stringBuffer.append(temp); } return stringBuffer.toString(); } /** * @Title: downFile * @Description: 从FTP服务器下载文件 * @param ip FTP服务器ip * @param port FTP端口 * @param username 账号 * @param password 密码 * @param remotePath FTP路径(例:\\:默认FTP根目录,\\SVA\\:FTP根目录下SVA文件夹) * @param fileName 下载文件名称 * @param localPath 保存本地下载路径 * @param type 0:下载对应路径在的文件 1:下载对应路径下的所有文件 * @return */ public static boolean downFtpFile(String ip, int port, String username, String password, String remotePath, String fileName, String localPath, int type) { boolean success = false; LOG.debug("FTP param ip:"+ip+",port:"+port+",userName:"+username+",password:"+password+",remotePath:"+remotePath+",fileName:"+fileName+",localPath:"+localPath+",type:"+type); FTPClient ftp = new FTPClient(); try { int reply; ftp.setConnectTimeout(50000); ftp.connect(ip, port); // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 ftp.login(username, password);// 登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { LOG.debug("FTP is reply:"+reply); ftp.disconnect(); return success; } ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录 // ftp.enterLocalPassiveMode(); FTPFile[] fs = ftp.listFiles(); LOG.debug("FTP FTPFile size"+fs.length); for (FTPFile ff : fs) { if (type == 0) { if (ff.getName().equals(fileName)) { File localFile = new File(localPath + "/" + ff.getName()); OutputStream is = new FileOutputStream(localFile); ftp.retrieveFile(ff.getName(), is); is.close(); } } else { File localFile = new File(localPath + "/" + ff.getName()); OutputStream is = new FileOutputStream(localFile); ftp.retrieveFile(ff.getName(), is); is.close(); } } ftp.logout(); success = true; } catch (IOException e) { success = false; LOG.error("FTP ERROR:"+e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { LOG.error("FTP close ftp error:"+ioe); } } } LOG.debug("FTP result:"+success); return success; } public static void deleteAll(File file){ if(file.isFile() || file.list().length ==0) { file.delete(); }else{ File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { deleteAll(files[i]); files[i].delete(); } } } // public static void ftp4jConnecttion(String ip, int port,String username, String password) // { // it.sauronsoftware.ftp4j.FTPClient client = null; // try { // TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() { // public X509Certificate[] getAcceptedIssuers() { // return null; // } // public void checkClientTrusted(X509Certificate[] certs, // String authType) { // } // public void checkServerTrusted(X509Certificate[] certs, // String authType) { // } // } }; // SSLContext sslContext = null; // sslContext = SSLContext.getInstance("SSL"); //// System.setProperty("https.protocols", "TLS"); //// sslContext = SSLContext.getInstance("TLS"); // sslContext.init(null, trustManager, new SecureRandom()); // SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); // client = new it.sauronsoftware.ftp4j.FTPClient();; // client.setSSLSocketFactory(sslSocketFactory); // client.setSecurity(it.sauronsoftware.ftp4j.FTPClient.SECURITY_FTPS); // client.connect(ip, 33); // client.login(username, password); // System.out.println(client.toString()); // System.out.println(client.currentDirectory()); // client.changeDirectory("\\SVA\\wangjun\\ftp\\"); // String[] fs = client.listNames(); // for (int i = 0; i < fs.length; i++) { // if (fs[i].equals("H2F1.xml")) { // client.download("\\SVA\\wangjun\\ftp\\H2F1.xml",new File("d:\\H2F2.xml")); // } // } // } catch (Exception e) { // e.printStackTrace(); // }finally { // if (null != client) { // try { // client.disconnect(true);// 安全退出 // } catch (Exception e) { // e.printStackTrace(); // System.out.println("安全退出FTP服务时异常!" + e.getMessage()); // } // } // } // } // public static void main(String[] args) { // ftp4jConnecttion("139.159.219.166", 990, "Administrator", "Huawei@sva_demo_app"); // } }
Java
CL
bdbeea639a2318ef99898f7899978c2de99e8c2d849d264caf09f6143b2fcaf8
package com.duongll.succotask.service; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.os.Build; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.duongll.succotask.R; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFcmService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID") .setSmallIcon(R.drawable.ic_action_unread) .setContentTitle(remoteMessage.getNotification().getTitle()) .setContentText(remoteMessage.getNotification().getBody()) .setPriority(NotificationCompat.PRIORITY_DEFAULT); createNotificationChannel(); NotificationManagerCompat.from(this).notify(1, builder.build()); super.onMessageReceived(remoteMessage); } private void createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String name = "channel"; String descriptionText = "description"; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel("CHANNEL_ID", name, importance); channel.setDescription(descriptionText); // Register the channel with the system NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(channel); } } }
Java
CL
0b3036592529286b94854e875b212fce8fba23f0da4760da0eb312d8307b5728
package ru.job4j.thread; import net.jcip.annotations.GuardedBy; import net.jcip.annotations.ThreadSafe; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; import java.util.concurrent.*; /** * Class ParallelSearch реализует поиск текста в файле. * * @author Konstantin Inozemcev (9715791@gmail.com) * @version $Id$ * @since 0.1 */ @ThreadSafe public class ParallelSearch { /** * Путь до папки откуда надо осуществлять поиск */ private final String root; /** * Текст поиска в файле */ private final String text; /** * Список расширений файлов в которых осуществляется делать поиск. */ private final List<String> exts; /** * Шаблон расширений файлов */ private final String TEMPLATE = "glob:*"; /** * Флаг проверки завершения работы нити seach */ volatile boolean finish = false; /** * Очередь для хранения адресов с файлами */ @GuardedBy("this") private final Queue<String> files = new LinkedBlockingQueue<>(); /** * Список для хранения адресов с файлами с найденным текстом */ @GuardedBy("this") private final List<String> paths = new ArrayList<>(); /** * Конструктор - создание нового объекта с параметрами * @param root - путь до папки откуда надо осуществляется поиск. * @param text - текст поиска * @param exts - список расширений файлов в которых осуществляется поиск. * */ public ParallelSearch(String root, String text, List<String> exts) { this.root = root; this.text = text; this.exts = exts; } /** * Метод запускает нити поиска */ public void init() { Thread search = new Thread() { @Override public void run() { call(); } }; Thread read = new Thread(new Runnable() { @Override public void run() { search(); } }); search.start(); read.start(); try { read.join(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Метод выполняет поиск файлов по * заданным расширениям */ public void call() { Path fileDir = Paths.get(this.root); try { for (String e : exts) { Files.walkFileTree(fileDir, new FileVisitor(TEMPLATE.concat(e))); } } catch (IOException e1) { e1.printStackTrace(); } finally { this.finish = true; } } /** * Метод выполняет ипоиск текст в файлах * и сохраняет адрес файла. */ public void search() { File file; while (!finish) { while (!files.isEmpty()) { try { file = new File(this.files.poll()); BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(file))); String line; while ((line = br.readLine()) != null) { if (line.contains(this.text)) { this.paths.add(file.toString()); break; } } } catch (FileNotFoundException e) { e.printStackTrace(); break; } catch (IOException e) { e.printStackTrace(); } } } } /** * Метод возвращает список адресов файлов * @return paths */ public List<String> result() { return this.paths; } /** * Class FileVisitor */ private class FileVisitor extends SimpleFileVisitor<Path> { /** * Поле интерфейса PathMatcher */ private PathMatcher matcher; /** * Конструктор - создание нового объекта с параметрами * @param pattern - строка шаблона расширения файла * */ public FileVisitor(String pattern) { this.matcher = FileSystems.getDefault().getPathMatcher(pattern); } /** * Метод добавляет адрес файла по найденному расширению * @param path адрес файла */ private void find(Path path) { Path name = path.getFileName(); if (matcher.matches(name)) { files.offer(path.toString()); } } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { find(dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { find(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { System.err.println(exc.getMessage()); return FileVisitResult.CONTINUE; } } }
Java
CL
5b5a1b49ff188dc75428ace76fe01c4be0c3fd6fcd3484d1ca1cd9e14420671f
package pers.astlvk.acgn.dao.websitenav; import java.util.Map; import pers.astlvk.acgn.entity.websitenav.Website; public interface WebsiteDao { /** * 分页获取website数据, param可以是map, 也可以是封装的对象。 * * @param currPage * @param pageSize * @param param 可以为null,为null时需要在mybatis的映射文件中判断后再拼接sql * @return Map<String, Object> keys: int rows, int allPage, int currPage, List list */ Map<String, Object> getWebsitePagination(int currPage, int pageSize, Object param); /** * 添加website, 求简单, 只添加name字段内容, 为了偷懒sql中typeId都给写1了。 * 也就是说该插入添加了name和typeId两个字段内容。 * * @param webiste * @return int primaryKey */ int addWebsiteOnlyName(Website website); /** * del website by id * * @param id * @return int */ int delWebsiteById(int id); /** * del website by typeId * * @param id * @return int */ int delWebsiteByTypeId(int typeId); /** * update website by id * * @param website * @return int */ int updateWebsiteById(Website website); }
Java
CL
2308f21c2b89212f6ba1719e536298893578f97ddacd08946180bbdb4bf05537
/* * Yeti 2, NesC development in Eclipse. * Copyright (C) 2009 ETH Zurich * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Web: http://tos-ide.ethz.ch * Mail: tos-ide@tik.ee.ethz.ch */ package tinyos.yeti.views; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.progress.UIJob; import tinyos.yeti.Debug; import tinyos.yeti.ep.parser.IASTModelElement; import tinyos.yeti.ep.parser.IASTModelNode; import tinyos.yeti.ep.parser.IASTModelNodeConnection; import tinyos.yeti.views.NodeContentProvider.Element; import tinyos.yeti.views.NodeContentProvider.ModelInfo; /** * A helper class to update the tree by reusing as many {@link Element}s * as possible. * @author Benjamin Sigg */ public class NodeTreeRefiller { /** the old roots of the tree */ private Element[] oldRoots; /** the viewer which shows the tree */ private NodeContentProvider provider; public NodeTreeRefiller( NodeContentProvider provider, Element[] oldRoots ){ this.provider = provider; this.oldRoots = oldRoots; } /** * Refills the whole tree with the nodes from <code>models</code>. This * method starts its own thread and will return immediately. * @param model the new models, not <code>null</code> */ public void refill( final ModelInfo[] models ){ Job job = new Job( "Update Node Tree" ){ @Override protected IStatus run(IProgressMonitor monitor) { if( provider.isDisposed() ){ return Status.OK_STATUS; } final List<Element> newRoots = new ArrayList<Element>(); Debug.enter(); for( ModelInfo info : models ){ IASTModelNode[] roots = info.model.getNodes( provider.getRootFilter() ); int[] occurrence = buildOccurrenceMap( roots ); for( int i = 0; i < roots.length; i++ ){ IASTModelNode root = roots[i]; Element element = search( oldRoots, root.getIdentifier(), occurrence[i] ); if( element == null ){ element = provider.new Element( null, root, null, info ); } else{ refill( element, null, root ); } newRoots.add( element ); } } UIJob finish = new UIJob( "Update Node Tree"){ @Override public IStatus runInUIThread(IProgressMonitor monitor) { if( !provider.isDisposed() ){ provider.setRoots( newRoots.toArray( new Element[ newRoots.size() ]) ); } return Status.OK_STATUS; } }; finish.setSystem( true ); finish.schedule(); Debug.leave(); return Status.OK_STATUS; } }; job.schedule(); } /** * Creates an array where the index'th position tells how many times * the identifier of the index'th element was already found. To be used * together with {@link #search(Element[], String, int)}. * @param elements the element to analyze * @return the occurrences */ private int[] buildOccurrenceMap( IASTModelElement[] elements ){ if( elements == null ) return null; int[] result = new int[ elements.length ]; loop:for( int i = 0; i < elements.length; i++ ){ String id = elements[i].getIdentifier(); for( int j = i-1; j >= 0; j-- ){ if( elements[j].getIdentifier().equals( id )){ result[i] = result[j]+1; continue loop; } } result[i] = 0; } return result; } /** * Searches for the one {@link Element} whose identifier matches <code>identifier</code>. * @param choices the possible answers * @param identifier the identifier to search * @param occurrence how many times to ignore a result and continue the search * @return either an element of <code>choices</code> or <code>null</code> */ private Element search( Element[] choices, String identifier, int occurrence ){ if( choices != null ){ for( Element choice : choices ){ if( choice.getIdentifier().equals( identifier )){ if( occurrence == 0 ) return choice; occurrence--; } } } return null; } /** * Updates <code>element</code> such that it shows <code>connection</code>. * @param element the element to update * @param connection the new value of <code>element</code> */ private void refill( Element element, IASTModelNodeConnection connection ){ if( provider.isExpanded( element )){ IASTModelNode node = provider.resolveNode( element, connection, null ); if( node != null ){ refill( element, connection, node ); } else{ provider.setContent( element, true, null, connection, null, null ); } } else{ provider.setContent( element, false, null, connection, null, null ); } } /** * Updates <code>element</code> such that it shows <code>node</code>. * @param element the element to update * @param connection the connection that points to <code>node</code> * @param node the new value of <code>element</code> */ private void refill( Element element, IASTModelNodeConnection connection, IASTModelNode node ){ if( provider.isExpanded( element )){ Element[] childElements = element.getChildren(); IASTModelNodeConnection[] childNodes = node.getChildren(); List<Element> children = new ArrayList<Element>(); if( childNodes != null ){ int[] occurrences = buildOccurrenceMap( childNodes ); for( int i = 0; i < childNodes.length; i++ ){ IASTModelNodeConnection childConnection = childNodes[i]; Element child = search( childElements, childConnection.getIdentifier(), occurrences[i] ); if( child == null ){ child = provider.new Element( element, childConnection, null, element.getModelInfo() ); } else{ refill( child, childConnection ); } children.add( child ); } } provider.setContent( element, true, node, connection, children.toArray( new Element[ children.size() ]), null ); } else{ provider.setContent( element, false, node, null, null, null ); } } }
Java
CL
b14143ed4f2a28eea05f31630d740fd68ccdb38626dd07b7d31cc0cdf1916546
/* * A Sinhala, Tamil and English Transliterator * * Copyright (c) 2010 Asankha Chamath Perera. (http://www.asankha.com). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asankha.translit; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.InputStreamReader; import java.util.*; /** * Implemented my own Transliterator re-using rules from the ICTA transliterator which had severe code/architectural * issues making it unsuitable for any real work * * This implementation attempts to be not-dependent on any external libraries - and hence debug and error logging are * limited and not based on SLF4J or Log4J etc. This is 'by choice'! * * This implementation also does NOT use a database. The original ICTA implementation executed hundreds of SQLs for * each word. This implementation caches all words in memory, loaded from files found in the classpath. Hence an * update of rules is possible by placing updated rules files on the classpath com/asankha/translit/resources * followed by a restart. * * The implementation is optimized for performance, and hence uses RAM to keep rules and the dictionary cached. Thus * the implementation will roughly take about 1.25MB of Heap Memory for English/Sinhala/Tamil transliteration. * * Note: The accuracy of the transliterator can be improved with updated dictionary files, or by tuning the phonetic * rules used. The former is strongly encouraged. For example, the name of the town "Galle" cannot be correctly * transliterated by only using phonetic rules, as its name in Sinhalese is different from the sound made by the * word "Galle" in English. The accuracy is generally better for person names etc. However, the Male/Female or Unknown * specifier must be specified to obtain a correct translation where application. (e.g. Avanka - as a male "අවන්ක" or * as a female "අවන්කා" * * e.g. Sample execution of the command line application * $java -jar translit-core-1.0.0.jar [-s si|ta|en*] [-t si*|ta|en] [-g m|f|u*] : (* - denotes default) * asankha perera * අසන්ඛ පෙරේරා * * Transliterating an input file /tmp/input into /tmp/output using default options * $java -jar translit-core-1.0.0.jar < /tmp/input > /tmp/output * * @author asankha perera (asankha AT gmail DOT com) * 6th November 2010 */ public class Transliterate { private static final ClassLoader CLS_LDR = Transliterate.class.getClassLoader(); private static boolean DEBUG = Boolean.getBoolean("debug"); public static final int ENGLISH = 0; public static final int SINHALA = 1; public static final int TAMIL = 2; public static final int UNKNOWN = 0; public static final int MALE = 1; public static final int FEMALE = 2; private static final String END_VOVELS = ".aeiou#"; private static final String START_VOVELS = ".aeiou"; private static final String PREFIX = "com/asankha/translit/resources/"; private static final Map<String, String> engToSinNames = new HashMap<String, String>(); private static final Map<String, String> engToSinOther = new HashMap<String, String>(); private static final Map<String, String> sinToEngNames = new HashMap<String, String>(); private static final Map<String, String> sinToEngOther = new HashMap<String, String>(); private static final Map<String, String> engToTamNames = new HashMap<String, String>(); private static final Map<String, String> engToTamOther = new HashMap<String, String>(); private static final Map<String, String> tamToEngNames = new HashMap<String, String>(); private static final Map<String, String> tamToEngOther = new HashMap<String, String>(); private static final Map<String, String> sinToTamNames = new HashMap<String, String>(); private static final Map<String, String> sinToTamOther = new HashMap<String, String>(); private static final Map<String, String> tamToSinNames = new HashMap<String, String>(); private static final Map<String, String> tamToSinOther = new HashMap<String, String>(); private static LangToPhonetic[] enToPhRules; private static LangToPhonetic[] siToPhRules; private static LangToPhonetic[] taToPhRules; private static PhoneticToLang[] phToSiRules; private static PhoneticToLang[] phToTaRules; private static PhoneticToLang[] phToEnRules; static { try { enToPhRules = loadLangToPhoneticFile(PREFIX + "rules-en.txt"); siToPhRules = loadLangToPhoneticFile(PREFIX + "rules-si.txt"); taToPhRules = loadLangToPhoneticFile(PREFIX + "rules-ta.txt"); phToSiRules = loadPhoneticToLangFile(PREFIX + "phonetic-si.txt"); phToTaRules = loadPhoneticToLangFile(PREFIX + "phonetic-ta.txt"); phToEnRules = loadPhoneticToLangFile(PREFIX + "phonetic-en.txt"); loadMappingFile(PREFIX + "en-to-si.txt", engToSinNames, engToSinOther, sinToEngNames, sinToEngOther); loadMappingFile(PREFIX + "en-to-ta.txt", engToTamNames, engToTamOther, tamToEngNames, tamToEngOther); loadMappingFile(PREFIX + "si-to-ta.txt", sinToTamNames, sinToTamOther, tamToSinNames, tamToSinOther); if (DEBUG) { System.out.println("En to Ph rules : " + enToPhRules.length); System.out.println("Si to Ph rules : " + siToPhRules.length); System.out.println("Ta to Ph rules : " + taToPhRules.length); System.out.println("Ph to Si rules : " + phToSiRules.length); System.out.println("Ph to Ta rules : " + phToTaRules.length); System.out.println("Ph to En rules : " + phToEnRules.length); System.out.println("En to Si mappings : " + engToSinNames.size() + " : " + engToSinOther.size()); System.out.println("En to Ta mappings : " + engToTamNames.size() + " : " + engToTamOther.size()); System.out.println("Si to Ta mappings : " + sinToTamNames.size() + " : " + sinToTamOther.size()); } } catch (Exception e) { System.out.println("Error during the initialization of the Transliterator : " + e.getMessage()); e.printStackTrace(); } } public static void main(String[] args) { //System.out.println(translateLine("\"Kumarasiri\" asankha-chamath, #Perera#", ENGLISH, SINHALA, MALE)); int src = ENGLISH; int dst = SINHALA; int gender = UNKNOWN; System.out.println("java -jar translit.jar [-s si|ta|en*] [-t si*|ta|en] [-g m|f|u*] : (* - denotes default)"); for (int i=0; i<args.length; i++) { if (args[i].equals("-s")) { if (i+1 < args.length) { src = "si".equals(args[i+1]) ? SINHALA : "ta".equals(args[i+1]) ? TAMIL : ENGLISH; } } if (args[i].equals("-t")) { if (i+1 < args.length) { dst = "si".equals(args[i+1]) ? SINHALA : "ta".equals(args[i+1]) ? TAMIL : ENGLISH; } } if (args[i].equals("-g")) { if (i+1 < args.length) { gender = "m".equals(args[i+1]) ? MALE : "f".equals(args[i+1]) ? FEMALE : UNKNOWN; } } } Scanner sc = new Scanner(System.in); String s = null; try { while ((s = sc.nextLine()) != null) { System.out.println(translateLine(s, src, dst, gender)); } } catch (NoSuchElementException ignore) {} } private static LangToPhonetic[] loadLangToPhoneticFile(String filename) throws Exception { DataInputStream in = new DataInputStream(CLS_LDR.getResourceAsStream(filename)); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; List<LangToPhonetic> list = new ArrayList<LangToPhonetic>(); while ((s = br.readLine()) != null) { String[] p = s.split(","); list.add(new LangToPhonetic(p[2].replaceAll("%", ".*"), p[0], p[3], p[4].replaceAll("%", ""))); } in.close(); return list.toArray(new LangToPhonetic[list.size()]); } private static PhoneticToLang[] loadPhoneticToLangFile(String filename) throws Exception { DataInputStream in = new DataInputStream(CLS_LDR.getResourceAsStream(filename)); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; List<PhoneticToLang> list = new ArrayList<PhoneticToLang>(); while ((s = br.readLine()) != null) { String[] p = s.split(","); list.add(new PhoneticToLang(p[0].replaceAll("\\.", "\\\\.").replaceAll("%", ".*"), p[1].replaceAll("%", ""), p[2])); } in.close(); return list.toArray(new PhoneticToLang[list.size()]); } private static void loadMappingFile(String filename, Map<String, String> namesOne, Map<String, String> otherOne, Map<String, String> namesTwo, Map<String, String> otherTwo) throws Exception { DataInputStream in = new DataInputStream(CLS_LDR.getResourceAsStream(filename)); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; while ((s = br.readLine()) != null) { String[] p = s.toLowerCase().split(","); if ("1".equals(p[2]) || "1".equals(p[3])) { // this is a person name if (!namesOne.containsKey(p[0])) { namesOne.put(p[0], p[1]); } if (!namesTwo.containsKey(p[1])) { namesTwo.put(p[1], p[0]); } } else { if (!otherOne.containsKey(p[0])) { otherOne.put(p[0], p[1]); } if (!otherTwo.containsKey(p[1])) { otherTwo.put(p[1], p[0]); } } } in.close(); } //----------------------------- translate a phrase from one language to another ------------------------------------ public static String translateLine(String s, int src, int dst, int gender) { if (DEBUG) { System.out.println("Src : " + src + " Target : " + dst + " Gender : " + gender); } StringTokenizer st = new StringTokenizer(s.toLowerCase(), " ,\\[]#'\"()", true); if (st.countTokens() == 1) { return translateWord(st.nextToken(), src, dst, gender); } else { StringBuilder sb = new StringBuilder(); while (st.hasMoreTokens()) { String t = st.nextToken(); if (t.length() > 1) { sb.append(translateWord(t, src, dst, gender)); } else { sb.append(t); } } return sb.toString(); } } // ---------------------------- translate one word from one language to another ------------------------------------ public static String translateWord(String s, int src, int dst, int gender) { Map<String, String> otherMap = null; Map<String, String> namesMap = null; LangToPhonetic[] langToPhonetic = null; PhoneticToLang[] phoneticToLang = null; s = s.toLowerCase(); switch (src) { case SINHALA: switch (dst) { case TAMIL: otherMap = sinToTamOther; namesMap = sinToTamNames; langToPhonetic = siToPhRules; phoneticToLang = phToTaRules; break; case ENGLISH: otherMap = sinToEngOther; namesMap = sinToEngNames; langToPhonetic = siToPhRules; phoneticToLang = phToEnRules; break; } break; case TAMIL: switch (dst) { case SINHALA: otherMap = tamToSinOther; namesMap = tamToSinNames; langToPhonetic = taToPhRules; phoneticToLang = phToSiRules; break; case ENGLISH: otherMap = tamToEngOther; namesMap = tamToEngNames; langToPhonetic = taToPhRules; phoneticToLang = phToEnRules; break; } break; case ENGLISH: switch (dst) { case TAMIL: otherMap = engToTamOther; namesMap = engToTamNames; langToPhonetic = enToPhRules; phoneticToLang = phToTaRules; break; case SINHALA: otherMap = engToSinOther; namesMap = engToSinNames; langToPhonetic = enToPhRules; phoneticToLang = phToSiRules; break; } break; } if (namesMap == null || otherMap == null) { System.out.println("Invalid language pair"); return null; } String result = null; if (gender == UNKNOWN) { result = otherMap.get(s); } else { result = namesMap.get(s); } if (result != null) { return result; } else { if (DEBUG) { System.out.println("Dictionary lookup failed for : " + s); } return phoneticToLang(convertToPhonetic(s, gender, langToPhonetic), phoneticToLang); } } // --------------------- rules based translation to / from a language to phonetic ---------------------------------- private static String convertToPhonetic(String word, int gender, LangToPhonetic[] rules) { StringBuilder in = new StringBuilder().append("#").append(word).append("#"); StringBuilder out = new StringBuilder(); while (in.length() > 0) { boolean found = false; String s = in.toString(); for (LangToPhonetic l2p : rules) { boolean c = s.matches(l2p.getRule()); if (c && (gender == l2p.getGender() || l2p.getGender() == UNKNOWN)) { if (DEBUG) { System.out.println("In : " + s + " matches : " + l2p.getRule() + " with : " + l2p.getPhonetic()); } appendPhoneticWithCorrection(out, l2p.getPhonetic()); in.delete(0, l2p.getLength()); found = true; break; } } if (!found) { out.append(in.charAt(0)); in.delete(0, 1); } } if (DEBUG) { System.out.println("convertToPhonetic(" + word + ") = " + out.toString()); } return out.toString(); } private static String phoneticToLang(String word, PhoneticToLang[] rules) { StringBuilder in = new StringBuilder().append(word); StringBuilder out = new StringBuilder(); while (in.length() > 0) { boolean found = false; String s = in.toString(); for (PhoneticToLang p2l : rules) { boolean c = s.matches(p2l.getRule()); if (c) { if (DEBUG) { System.out.println("In : " + s + " matches : " + p2l.getRule() + " with : " + p2l.getLang()); } if (p2l.getLang() != null) { out.append(p2l.getLang()); } in.delete(0, p2l.getLength()); found = true; break; } } if (!found) { out.append(in.charAt(0)); in.delete(0, 1); } } if (DEBUG) { System.out.println("phoneticToLang(" + word + ") = " + out.toString().replaceAll("#", "")); } return out.toString().replaceAll("#", ""); } private static void appendPhoneticWithCorrection(StringBuilder out, String ph) { final int len = out.length(); if (len > 0) { String lastChar = out.substring(len-1); if (END_VOVELS.indexOf(lastChar) == -1) { // not a vowel if (ph.length() > 0) { if (START_VOVELS.indexOf(ph.substring(0,1)) == -1) { // not a vowel out.append(".a"); } } else { out.append(".a"); } } } out.append(ph); } }
Java
CL
089ceb94ff16d87127466358629df02e50c0b0d073b4021eb31cb797d536adfb
import java.math.BigInteger; import java.util.Scanner; public class start { static boolean flag = true; static String filename = "", dirname = "", key = ""; static int chk = 0, ch = 0; // static byte [] bkey; public static void main(String[] args) { EncDec obj = new EncDec(); Scanner chscanner = new Scanner(System.in); while (flag) { System.out.println( "\n===============================================================\n 1.ENCRYPT a file \t 2.DECRYPT a file \t 3.Open a File\n 4.Delete a File \t 5.Exit Program\n==============================================================="); System.out.println("Enter Your Choice:\t"); if (chscanner.hasNextInt()) ch = chscanner.nextInt(); switch (ch) { case 1: do { System.out.println("Enter Name of the File to be Encrypted(include path if outside):"); filename = chscanner.next(); filename = filename.replaceAll("\\\\", "/"); // for windows dir scheme chk = FunctionSet.check(filename); } while (chk != 1); do { System.out.println("Enter Name of Directory to store Encrypted file:"); dirname = chscanner.next(); dirname = dirname.replaceAll("\\\\", "/"); chk = FunctionSet.check(dirname); } while (chk != 2); do { System.out.println("Enter Your Private Key (length>10),And Forget it :)"); key = chscanner.nextLine(); if (key.length() < 10) System.out.println("\t\t--Private Key Size should be > 10!--"); } while (key.length() < 10); key = FunctionSet.KeyGen(key); // bkey=key.getBytes(Charset.defaultCharset()); //array of bytes of key // key=RsaFunctionClass.StrToBytes(key); //get the string of bytes BigInteger m = new BigInteger(key); // convert to BI BigInteger Enkey = RsaFunctionClass.EncDec(m, RsaFunctionClass.e, RsaFunctionClass.n); // RSA-Encrypt // the key String keyloc = RsaFunctionClass.WriteEncKey(Enkey, dirname, filename); // write encrypted key to // file for further use obj.encrypt(filename, dirname, key); System.out.println("\nFile ENCRYPTED Successfully as 'enc.hades', Stored at" + "'" + dirname + "'"); System.out.println("ATTENTION! NOW Your Encrypted Private Key is:" + Enkey + "\n\tIt is Saved for You at '" + keyloc + "'"); break; case 2: do { System.out.println( "Enter Name of the Encrypted File that is to be Decrypted(include path if outside):"); filename = chscanner.next(); filename = filename.replaceAll("\\\\", "/"); chk = FunctionSet.check(filename); } while (chk != 1); // Get Original Extension for Decryption System.out .println("Enter EXTENSION to which file is to be Decrypted(e.g txt,pdf,jpg,mp3,mp4,etc):"); String extname = chscanner.next(); extname = extname.substring(extname.lastIndexOf(".") + 1); // if user provided a '.' with extension do { System.out.println("Enter Name of Directory where Decrypted file will be Stored:"); dirname = chscanner.next(); dirname = dirname.replaceAll("\\\\", "/"); chk = FunctionSet.check(dirname); } while (chk != 2); String regex = "[0-9]+"; // Regular Expression for string to make sure key contains only numbers do { System.out.println("Enter Your Encrypted Private Key of the file:"); key = chscanner.next(); if (key.length() < 500 || !(key.matches(regex))) System.out.println( "\t\t--Encrypted-Key Size must be > 500 and Must only contain Numeric Values!"); } while ((key.length() < 500) || !(key.matches(regex))); BigInteger c = new BigInteger(key); // convert to BI BigInteger Deckey = RsaFunctionClass.EncDec(c, RsaFunctionClass.d, RsaFunctionClass.n); // UNHANDLED>> // make // regex seq // for key // in EncDec // fxn // key=RsaFunctionClass.BytesToStr(bkey); //DEV..F // System.out.println("Decrypted Private key is:"+key); key = Deckey.toString(); obj.decrypt(filename, extname, dirname, key); System.out.println( "\nFile DECRYPTED Successfully as 'dec." + extname + ",' Stored at " + "'" + dirname + "'"); break; case 3: do { System.out.println("Enter Name of the File to be opened:"); filename = chscanner.next(); filename = filename.replaceAll("\\\\", "/"); chk = FunctionSet.check(filename); } while (chk != 1); FunctionSet.openfile(filename); // Static Call break; case 4: System.out.println("Enter the name of the file you want to delete:"); String fname = chscanner.next(); fname = fname.replaceAll("\\\\", "/"); System.out.println( "Do you want to delete the " + fname + " file! \nEnter 1 to Confirm and 2 to Abort:"); int opt = 0; if (chscanner.hasNextInt()) opt = chscanner.nextInt(); FunctionSet.delencf(fname, opt); break; case 5: flag = false; System.out.println("Good Bye!"); chscanner.close(); break; default: flag = false; System.out.println("No Such Option... Good Bye!"); chscanner.close(); } } } }
Java
CL
6fe817b8caafbaa5225e37c8f342a3b66ceb52c65ee27ef7f181c298293974bc
package make; import java.util.ArrayList; import java.util.HashSet; /** An object containing a rule for makefile. * @author Jason Qiu */ public class Rule { /** My target. */ private String target; /** My commands. */ private ArrayList<String> commandSet; /** My prerequisites. */ private HashSet<String> prereqs; /** Construct a new Rule using S, COMMANDS, and PREREQ. */ public Rule(String s, ArrayList<String> commands, HashSet<String> prereq) { target = s; commandSet = commands; prereqs = prereq; } /** Returns target. */ public String getTarget() { return target; } /** Returns commandSet. */ public ArrayList<String> getCommandSet() { return commandSet; } /** Returns prereqs. */ public HashSet<String> getPrereqs() { return prereqs; } /** Add a command CMD. */ public void addCommand(String cmd) { commandSet.add(cmd); } /** Add a prereq PREREQ. */ public void addPrereq(String prereq) { prereqs.add(prereq); } }
Java
CL
8906a294a328c503f042fb529aaa0842e12fa4a6a64a6ebf1e3aebe102aebae9
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.jxc.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.service.CrudService; import com.thinkgem.jeesite.modules.jxc.entity.JxcPurchasekind; import com.thinkgem.jeesite.modules.jxc.dao.JxcPurchasekindDao; /** * 客户类别Service * @author 马万进 * @version 2016-07-19 */ @Service @Transactional(readOnly = true) public class JxcPurchasekindService extends CrudService<JxcPurchasekindDao, JxcPurchasekind> { public JxcPurchasekind get(String id) { return super.get(id); } public List<JxcPurchasekind> findList(JxcPurchasekind jxcPurchasekind) { return super.findList(jxcPurchasekind); } public Page<JxcPurchasekind> findPage(Page<JxcPurchasekind> page, JxcPurchasekind jxcPurchasekind) { return super.findPage(page, jxcPurchasekind); } @Transactional(readOnly = false) public void save(JxcPurchasekind jxcPurchasekind) { super.save(jxcPurchasekind); } @Transactional(readOnly = false) public void delete(JxcPurchasekind jxcPurchasekind) { super.delete(jxcPurchasekind); } }
Java
CL
03f5b0648744422eac281e3a3673918397371d72efa7c4afd9d34669a8f2f250
/* * Lamblin * Copyright 2018 Borislav Shekerov * Licensed under Apache 2.0: https://github.com/BorislavShekerov/lamblin/blob/master/LICENSE */ package com.lamblin.it.client; import com.lamblin.it.model.ResponseEntity; import okhttp3.OkHttpClient; import retrofit2.Call; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import java.util.concurrent.TimeUnit; import static com.lamblin.it.client.ClientUtils.createObjectMapper; import static com.lamblin.it.client.ClientUtils.executeRequest; import static com.lamblin.it.model.EndpointsKt.*; import static com.lamblin.it.model.TestUtilsKt.*; public class GetControllerClient { public static final GetControllerClient INSTANCE = new GetControllerClient(); private final GetControllerApi client; private GetControllerClient() { Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(JacksonConverterFactory.create(createObjectMapper())) .client( new OkHttpClient.Builder() .readTimeout(1, TimeUnit.HOURS) .build()) .baseUrl(getServerBaseUrl()) .build(); this.client = retrofit.create(GetControllerApi.class); } public Response<ResponseEntity> callSimpleGetNoParamsEndpoint() { return executeRequest(client::callSimpleGetNoParamsEndpoint); } public Response<ResponseEntity> callQueryParamDefaultValueEndpoint() { return executeRequest(client::callQueryParamDefaultValueEndpoint); } public Response<ResponseEntity> callSingleQueryParamEndpoint(String queryParam) { return executeRequest(() -> client.callQueryParamEndpoint(queryParam, null)); } public Response<ResponseEntity> callMultiQueryParamEndpoint(String queryParam1, String queryParam2) { return executeRequest(() -> client.callQueryParamEndpoint(queryParam1, queryParam2)); } public Response<ResponseEntity> callSinglePathParamEndpoint(String pathParam) { return executeRequest(() -> client.callSinglePathParamEndpoint(pathParam)); } public Response<ResponseEntity> callMultiPathParamEndpoint(String pathParam1, String pathParam2) { return executeRequest(() -> client.callMultiPathParamEndpoint(pathParam1, pathParam2)); } public Response<ResponseEntity> callMultiPathParamWithQueryParamEndpoint( String queryParam, String pathParam1, String pathParam2) { return executeRequest(() -> client.callMultiPathParamEndpoint(pathParam1, pathParam2, queryParam)); } private interface GetControllerApi { @GET(SIMPLE_GET_ENDPOINT) Call<ResponseEntity> callSimpleGetNoParamsEndpoint(); @GET(QUERY_PARAM_GET_ENDPOINT) Call<ResponseEntity> callQueryParamEndpoint(@Query(QUERY_PARAM_1) String queryParam1, @Query(QUERY_PARAM_2) String queryParam2); @GET(QUERY_PARAM_DEFAULT_VALUE_GET_ENDPOINT) Call<ResponseEntity> callQueryParamDefaultValueEndpoint(); @GET(SINGLE_PATH_PARAM_GET_ENDPOINT) Call<ResponseEntity> callSinglePathParamEndpoint(@Path(PATH_PARAM_1) String pathParam1); @GET(MULTI_PATH_PARAM_GET_ENDPOINT) Call<ResponseEntity> callMultiPathParamEndpoint(@Path(PATH_PARAM_1) String pathParam1, @Path(PATH_PARAM_2) String pathParam2); @GET(MULTI_PATH_PARAM_GET_ENDPOINT) Call<ResponseEntity> callMultiPathParamEndpoint(@Path(PATH_PARAM_1) String pathParam1, @Path(PATH_PARAM_2) String pathParam2, @Query(QUERY_PARAM_1) String queryParam1); } }
Java
CL
b9cfb818836040e2a8c898c0ddb5af95f1fcf90a34faf5269f33278afec9a64d
/* * Copyright 2015-2018 The OpenZipkin 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 zipkin.internal; import java.util.List; import zipkin.Span; import zipkin.SpanDecoder; /** * Detecting decoder used in transports which don't include means to identify the type of the data. * * <p>For example, we can identify the encoding and also the format in http via the request path and * content-type. However, in Kafka it could be that folks send mixed Zipkin data without identifying * its format. For example, Kafka historically has no content-type and users don't always segregate * different queues by instrumentation format. */ // In TBinaryProtocol encoding, the first byte is the TType, in a range 0-16 // .. If the first byte isn't in that range, it isn't a thrift. // // When byte(0) == '[' (91), assume it is a list of json-encoded spans // // When byte(0) == 10, assume it is a proto3-encoded span or trace ID field // // When byte(0) <= 16, assume it is a TBinaryProtocol-encoded thrift // .. When serializing a Span (Struct), the first byte will be the type of a field // .. When serializing a List[ThriftSpan], the first byte is the member type, TType.STRUCT(12) // .. As ThriftSpan has no STRUCT fields: so, if the first byte is TType.STRUCT(12), it is a list. public final class DetectingSpanDecoder implements SpanDecoder { /** * Zipkin v2 json will have "localEndpoint" or "remoteEndpoint" fields, and others won't. * * <p>Note: Technically, it is also possible that one can thwart this by creating an binary * annotation of type string with a name or value literally ending in Endpoint. This would be * strange, especially as the convention to identify a local endpoint is the key "lc". To prevent * a secondary check, this scenario is also ignored. */ static final byte[] ENDPOINT_FIELD_SUFFIX = "Endpoint\"".getBytes(Util.UTF_8); /** * Technically, it is possible to have a v2 span with no endpoints. This should catch the case * where someone reported a tag without reporting the "localEndpoint". * * <p>Note: we don't check for annotations as that exists in both v1 and v2 formats. */ static final byte[] TAGS_FIELD = {'"', 't', 'a', 'g', 's', '"'}; static final SpanDecoder JSON2_DECODER = new V2JsonSpanDecoder(); static final SpanDecoder PROTO3_DECODER = new V2Proto3SpanDecoder(); @Override public Span readSpan(byte[] span) { SpanDecoder decoder = detectFormat(span); if (span[0] == 12 /* List[ThriftSpan] */ || span[0] == '[') { throw new IllegalArgumentException("Expected json or thrift object, not list encoding"); } return decoder.readSpan(span); } @Override public List<Span> readSpans(byte[] span) { SpanDecoder decoder = detectFormat(span); if (span[0] != 12 /* List[ThriftSpan] */ && !protobuf3(span) && span[0] != '[') { throw new IllegalArgumentException("Expected json, proto3 or thrift list encoding"); } return decoder.readSpans(span); } /** @throws IllegalArgumentException if the input isn't a json or thrift list or object. */ public static SpanDecoder detectFormat(byte[] bytes) { if (bytes[0] <= 16) { // binary format if (protobuf3(bytes)) return PROTO3_DECODER; return THRIFT_DECODER; /* the first byte is the TType, in a range 0-16 */ } else if (bytes[0] != '[' && bytes[0] != '{') { throw new IllegalArgumentException("Could not detect the span format"); } if (contains(bytes, ENDPOINT_FIELD_SUFFIX)) return JSON2_DECODER; if (contains(bytes, TAGS_FIELD)) return JSON2_DECODER; return SpanDecoder.JSON_DECODER; } static boolean contains(byte[] bytes, byte[] subsequence) { bytes: for (int i = 0; i < bytes.length - subsequence.length + 1; i++) { for (int j = 0; j < subsequence.length; j++) { if (bytes[i + j] != subsequence[j]) { continue bytes; } } return true; } return false; } /* span key or trace ID key */ static boolean protobuf3(byte[] bytes) { return bytes[0] == 10 && bytes[1] != 0; // varint follows and won't be zero } }
Java
CL
61b8455fdb1a6b6a35f484dc3ced4812c5e373c61797bda7a4929cd9ebc918e7
/* * Copyright (c) 2015-2020, www.dibo.ltd (service@dibo.ltd). * <p> * 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 * <p> * https://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 com.rednuo.core.binding.query.dynamic; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.IService; import com.rednuo.core.binding.helper.ServiceAdaptor; import com.rednuo.core.binding.parser.ParserCache; import com.rednuo.core.exception.CoreCode; import com.rednuo.core.exception.ExceptionCast; import com.rednuo.core.utils.ContextHelper; import com.rednuo.core.vo.Pagination; import lombok.Getter; import lombok.Setter; import java.util.List; /** * 动态查询wrapper * @author Mazc@dibo.ltd * @version v2.0 2020/04/16 */ public class ExtQueryWrapper<DTO,E> extends QueryWrapper<DTO> { /** * 主实体class */ @Getter @Setter private Class<E> mainEntityClass; /** * 获取entity表名 */ public String getEntityTable(){ return ParserCache.getEntityTableName(getMainEntityClass()); } /** * 查询一条数据 * @param entityClazz clazz * @return 结果 结果 E */ public E queryOne(Class<E> entityClazz){ this.mainEntityClass = entityClazz; IService<E> iService = ContextHelper.getIServiceByEntity(this.mainEntityClass); if(iService != null){ return ServiceAdaptor.getSingleEntity(iService, this); } else{ ExceptionCast.cast(CoreCode.FAIL, "查询对象无BaseService/IService实现: "+this.mainEntityClass.getSimpleName()); } return null; } /** * 查询一条数据 * @param entityClazz clazz * @return 结果 结果 list */ public List<E> queryList(Class<E> entityClazz){ this.mainEntityClass = entityClazz; IService iService = ContextHelper.getIServiceByEntity(entityClazz); if(iService != null){ return ServiceAdaptor.queryList(iService, this); } else{ ExceptionCast.cast(CoreCode.FAIL, "查询对象无BaseService/IService实现: "+entityClazz.getSimpleName()); } return null; } /** * 查询一条数据 * @param entityClazz class * @return 结果 结果 list */ public List queryList(Class<E> entityClazz, Pagination pagination){ this.mainEntityClass = entityClazz; IService iService = ContextHelper.getIServiceByEntity(entityClazz); if(iService != null){ return ServiceAdaptor.queryList(iService, (QueryWrapper)this, pagination, entityClazz); } else{ ExceptionCast.cast(CoreCode.FAIL, "查询对象无BaseService/IService实现: "+entityClazz.getSimpleName()); } return null; } }
Java
CL
bc89e31914db357258021abfa81f48c213b4422fad2632e44a3583e9d0f93923
// Copyright 2019 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.monitoring.blackbox.handler; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_8; import google.registry.monitoring.blackbox.message.InboundMessageType; import google.registry.monitoring.blackbox.message.OutboundMessageType; import google.registry.monitoring.blackbox.message.TestMessage; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; /** * {@link ChannelHandler} used in tests to convert {@link OutboundMessageType} to to {@link * ByteBuf}s and convert {@link ByteBuf}s to {@link InboundMessageType} * * <p>Specific type of {@link OutboundMessageType} and {@link InboundMessageType} used for * conversion is the {@link TestMessage} type. */ public class ConversionHandler extends ChannelDuplexHandler { /** Handles inbound conversion */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; ctx.fireChannelRead(new TestMessage(buf.toString(UTF_8))); buf.release(); } /** Handles outbound conversion */ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { String message = msg.toString(); ByteBuf buf = Unpooled.wrappedBuffer(message.getBytes(US_ASCII)); super.write(ctx, buf, promise); } }
Java
CL
f400bbe318ddc47010b4d02786eb60050c81185124c6450242870fa3ba59f521
package com.mbad.ninerhunt; import java.lang.reflect.UndeclaredThrowableException; import android.app.Activity; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.os.Bundle; import android.os.Parcelable; import android.widget.Toast; public class GoalScanActivity extends Activity implements ILocationReceiver { NfcAdapter adapter; PendingIntent pendingIntent; IntentFilter writeTagFilters[]; boolean writeMode; Tag mytag; Context ctx; Intent currentIntent; String tagText; int huntId; int goalId; Double currentLat; Double currentLon; int userId; public void setLocation(Double lat, Double lon) { currentLat = lat; currentLon = lon; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_goal_scan); ctx = this; adapter = NfcAdapter.getDefaultAdapter(ctx); currentIntent = getIntent(); // TODO: Get Username User currentUser = new User("Phil"); userId = currentUser.getUserId(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(currentIntent.getAction())) { mytag = currentIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); processTag(); completeGoal(); } } private void completeGoal() { Hunt currentHunt = new Hunt(huntId); // Todo: Make sure user has started hunt or that this is the first goal // in a hunt. // Todo: Set hunt to active HuntLogItem completedItem = new HuntLogItem(goalId, userId, huntId); completedItem.setCompleted(true); completedItem.Save(); } private void processTag() { Parcelable[] messages = currentIntent .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (messages != null) { NdefMessage[] ndefMessages = new NdefMessage[messages.length]; for (int i = 0; i < messages.length; i++) { ndefMessages[i] = (NdefMessage) messages[i]; } NdefRecord record = ndefMessages[0].getRecords()[0]; byte[] payload = record.getPayload(); tagText = new String(payload).replace("en", ""); String huntText = tagText.substring(0, tagText.indexOf(";")); huntId = Integer.parseInt(huntText .substring(huntText.indexOf(":") + 1).replace(";", "") .trim()); String goalText = tagText.substring(tagText.indexOf(";")); goalId = Integer.parseInt(goalText .substring(goalText.indexOf(":") + 1).replace(";", "") .trim()); } } }
Java
CL
9f5b826ab5f318d79172c467fa902d026c9f05f82e94b3b57461b313fe57322a
package com.tablecross.api.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import com.tablecross.api.common.ConstantParams; import com.tablecross.api.dao.RestaurantsDAO; import com.tablecross.api.model.RestaurantsDTO; import com.tablecross.api.model.UsersDTO; import com.tablecross.api.object.SearchRestaurantResponse; import com.tablecross.api.util.ConvertUtil; public class SearchRestaurant extends HttpServlet { private static Logger log = Logger.getLogger(SearchRestaurant.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String outStr = doSearchRestaurant(req); log.info("Response: " + outStr); resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); out.println(outStr); out.flush(); out.close(); } private String doSearchRestaurant(HttpServletRequest req) { SearchRestaurantResponse response = new SearchRestaurantResponse(); try { HttpSession session = req.getSession(true); UsersDTO userDTO = (UsersDTO) session .getAttribute(ConstantParams.LOGIN_USER_INFO); int searchType = Integer.parseInt(req.getParameter("searchType")); int total = -1; if (req.getParameter("total") != null) { total = Integer.parseInt(req.getParameter("total")); } String searchKey = req.getParameter("searchKey"); Double longitude = null; Double latitude = null; Float distance = null; if (searchType == ConstantParams.SEARCH_TYPE_HISTORY) { if (userDTO == null) { response.setSuccess(false); response.setErrorCode(ConstantParams.ERROR_CODE_USER_IS_NOT_LOGIN); response.setErrorMess(ConstantParams.ERROR_MESS_USER_IS_NOT_LOGIN); return ConvertUtil.convertObjectToJson(response); } } if (searchType == ConstantParams.SEARCH_TYPE_DISTANCE) { longitude = Double.parseDouble(req.getParameter("longitude")); latitude = Double.parseDouble(req.getParameter("latitude")); distance = Float.parseFloat(req.getParameter("distance")); } List<RestaurantsDTO> lst = RestaurantsDAO.searchRestaurant( searchType, (userDTO != null ? userDTO.getId() : null), searchKey, longitude, latitude, distance, total); response.setQuantity(lst.size()); response.setItems(lst.toArray(new RestaurantsDTO[lst.size()])); response.setSuccess(true); response.setErrorCode(ConstantParams.ERROR_CODE_SUCCESS); response.setErrorMess(ConstantParams.ERROR_MESS_SUCCESS); return ConvertUtil.convertObjectToJson(response); } catch (Exception e) { log.error("doSearchRestaurant ERROR: ", e); response.setSuccess(false); if (e instanceof NumberFormatException || e instanceof NullPointerException) { response.setErrorCode(ConstantParams.ERROR_CODE_PARAMS_INVALID); response.setErrorMess(ConstantParams.ERROR_MESS_PARAMS_INVALID); return ConvertUtil.convertObjectToJson(response); } response.setErrorCode(ConstantParams.ERROR_CODE_SYSTEM_ERROR); response.setErrorMess(ConstantParams.ERROR_MESS_SYSTEM_ERROR + ": " + e.getMessage()); return ConvertUtil.convertObjectToJson(response); } } }
Java
CL
b77fd750bc86b7e5666f75a2780dccbb5108d855822a209ef9125c6b84f9f474
package org.futuresight.clevelandrtanextbustrain; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import java.util.List; import java.util.Map; public class MainMenu extends AppCompatActivity { //CREDITS: base GPS pin and bus icon by Freepik from flaticon.com, train icon by Scott de Jonge on flaticon.com, star icon by Madebyoliver on flaticon.com private void alertDialog(String title, String msg, final boolean die) { AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle(title); alertDialog.setMessage(msg); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (die) { System.exit(0); } } }); alertDialog.show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setTitle(getResources().getString(R.string.main_menu_label)); setContentView(R.layout.activity_main_menu); if (!NetworkController.connected(this)) { alertDialog(getResources().getString(R.string.network), getResources().getString(R.string.nonetworkmsg), false); } if (getIntent().hasExtra("nextactivity")) { switch (getIntent().getExtras().getString("nextactivity")) { case "nextbustrain": Intent intent = new Intent(this, NextBusTrainActivity.class); intent.putExtra("lineId", getIntent().getExtras().getInt("lineId")); intent.putExtra("dirId", getIntent().getExtras().getInt("dirId")); intent.putExtra("stopId", getIntent().getExtras().getInt("stopId")); startActivityForResult(intent, 1); break; default: break; } } //new GetServiceAlertsTask(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } //task to get the times of the bus/train private class GetServiceAlertsTask extends AsyncTask<Void, Void, int[]> { private Context myContext; private String[] routes; private int[] routeIds; GetServiceAlertsTask(Context context) { myContext = context; } protected int[] doInBackground(Void... params) { if (NetworkController.connected(MainMenu.this)) { //don't try this if not connected to the internet try { PersistentDataController.getLineIdMap(myContext); //pre-load the line ID map just in case String[][] faves = PersistentDataController.getFavoriteLines(myContext); if (faves.length == 0) { return new int[]{0, 0}; } routes = new String[faves.length]; routeIds = new int[faves.length]; int i = 0; for (String[] s : faves) { routes[i] = s[0]; //save the route for later in case we want to color the results routeIds[i] = Integer.parseInt(s[1]); i++; } List<Map<String, String>> alerts = ServiceAlertsController.getAlertsByLine(myContext, routes, routeIds); int unread = 0; for (Map<String, String> alert : alerts) { if (alert.containsKey("new") && alert.get("new").equals("true")) { unread = 1; break; } } return new int[]{alerts.size(), unread}; } catch (Exception e) { e.printStackTrace(); } } return new int[]{0, 0}; } protected void onPostExecute(int[] params) { Button serviceAlertsBtn = (Button) findViewById(R.id.serviceAlertsBtn); if (serviceAlertsBtn != null) { if (params[1] == 1) { serviceAlertsBtn.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY); } else { serviceAlertsBtn.getBackground().clearColorFilter(); } } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //new GetServiceAlertsTask(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main_menu, menu); return true; } public void openNextBusTrainPage(View v) { Intent intent = new Intent(this, NextBusTrainActivity.class); startActivityForResult(intent, 1); } public void openManageLocationsPage(View v) { Intent intent = new Intent(this, ManageLocationsActivity.class); startActivityForResult(intent, 1); } public void openServiceAlertsPage(View v) { Intent intent = new Intent(this, ServiceAlertsActivity.class); v.getBackground().clearColorFilter(); startActivity(intent); } public void openMap(View v) { Intent intent = new Intent(this, MapTypeListActivity.class); startActivityForResult(intent, 1); } public void openLiveMap(View v) { Intent intent = new Intent(this, LiveMapActivity.class); startActivityForResult(intent, 1); } public void openNearMe(View v) { Intent intent = new Intent(this, NearMeActivity.class); startActivityForResult(intent, 1); } public void openSettings(View v) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } public void openCredits(View v) { Intent intent = new Intent(this, CreditsActivity.class); startActivity(intent); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return super.onOptionsItemSelected(item); } }
Java
CL
2a664133209719ff3adec5fa5b52200f5492bc7ffbf7eac13e12816bd76f1e1c
package ca.uqac.inf135.group3.tp2.crypto; import ca.uqac.inf135.group3.tp2.model.Message; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import java.security.GeneralSecurityException; public class AESMessage extends Message { public static final String ALGORITHM = "AES"; public static final String MODE = "CTR"; public static final String PADDING = "NoPadding"; //"PKCS5Padding"; public static final int BLOCK_SIZE = 16; //bytes private static String getFullAlgorithm() { return String.format("%s/%s/%s", ALGORITHM, MODE, PADDING); } private static byte[] getEncryptedBytes(Message clearMessage, AESKey key) throws GeneralSecurityException { //Prepare cipher (NOTE: since we are using OFB, we don't need an IV) Cipher cipher = Cipher.getInstance(getFullAlgorithm()); IvParameterSpec ivSpec = new IvParameterSpec(new byte[BLOCK_SIZE]); cipher.init(Cipher.ENCRYPT_MODE, key.getKey(), ivSpec); return cipher.doFinal(clearMessage.get()); } public AESMessage(byte[] encryptedBytes) { super(encryptedBytes); } public AESMessage(byte[] encryptedBytes, int offset, int length) { super(encryptedBytes, offset, length); } public AESMessage(byte[] encryptedBytes, int offset) { super(encryptedBytes, offset); } public AESMessage(Message clearMessage, AESKey key) throws GeneralSecurityException { super(getEncryptedBytes(clearMessage, key)); } public Message getClearMessage(AESKey key) throws GeneralSecurityException { //Prepare cipher (NOTE: since we are using OFB, we don't need an IV) Cipher cipher = Cipher.getInstance(getFullAlgorithm()); IvParameterSpec ivSpec = new IvParameterSpec(new byte[BLOCK_SIZE]); cipher.init(Cipher.DECRYPT_MODE, key.getKey(), ivSpec); return new Message(cipher.doFinal(get())); } }
Java
CL
18c1f279b14fb0d7bcf87a8d036d17af0638a597614985bbaa28ad0400cd714b
package io.gridgo.connector.redis; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import io.gridgo.connector.impl.AbstractConnector; import io.gridgo.connector.support.annotations.ConnectorEndpoint; import io.gridgo.connector.support.exceptions.InvalidParamException; import io.gridgo.connector.support.exceptions.InvalidPlaceholderException; import io.gridgo.redis.RedisClient; import io.gridgo.redis.RedisClientFactory; import io.gridgo.redis.RedisConfig; import io.gridgo.redis.RedisType; import io.gridgo.utils.support.HostAndPortSet; @ConnectorEndpoint(scheme = "redis", syntax = "{type}://{address}") public class RedisConnector extends AbstractConnector { private RedisClient redisClient; private Collection<String> topics; @Override protected void onInit() { var type = RedisType.forName(this.getPlaceholder("type")); if (type == null) { throw new InvalidPlaceholderException( "Redis type should be one of: SINGLE, SENTINEL, MASTER_SLAVE (or masterSlave also) and CLUSTER (case insensitive), got " + this.getPlaceholder("type")); } var addrString = this.getPlaceholder("address"); if (addrString == null || addrString.isBlank()) { throw new InvalidPlaceholderException("Address should be specified and cannot be blank"); } var address = new HostAndPortSet(addrString); var configBuilder = RedisConfig.builder().address(address); if (type == RedisType.SENTINEL) { var sentinelMasterId = this.getParam("sentinelMasterId"); if (sentinelMasterId != null && !sentinelMasterId.isBlank()) { configBuilder.sentinelMasterId(sentinelMasterId); } else { throw new InvalidParamException("Redis Sentinel require param sentinelMasterId"); } } var topicsParam = this.getParam("topics", null); var topics = topicsParam == null ? null : topicsParam.split(","); if (topics != null) { this.topics = new ArrayList<>(); for (String topic : topics) { this.topics.add(topic.trim()); } } this.redisClient = RedisClientFactory.newDefault().newClient(type, configBuilder.build()); if (this.topics != null) this.consumer = Optional.of(RedisConsumer.of(getContext(), redisClient, this.topics)); this.producer = Optional.of(RedisProducer.of(getContext(), redisClient)); } @Override protected void onStart() { this.redisClient.start(); super.onStart(); } @Override protected void onStop() { this.redisClient.stop(); super.onStop(); } }
Java
CL
96681d6c05257df02628d77ffacc9608edeccb66dd89c47ddf6888aa75edfb0f
package cn.shengyuan.yun.core.admin.dao; import java.util.List; import cn.shengyuan.basic.dao.base.BaseDao; import cn.shengyuan.yun.core.admin.entity.MenuValue; /** * 菜单值持久层接口 * @Date 2014-12-30 * @author 欧志辉 * @version 1.0 */ public interface MenuValueDao extends BaseDao<MenuValue, Long> { /** * 根据菜单值的名称查找菜单值 * @param id 菜单权限主键 * @param vName 菜单权限值(忽略大小写) * @return 名称是否存在 */ public List<MenuValue> nameExists(Long id, String vName); /** * 批量删除 * @param menuValues */ public void batchDelete(List<MenuValue> menuValues); }
Java
CL
c2d0a792ea8fd44b54e67272816e7ecd642a313db6f287c9f546289cd02db4ac
package gov.nist.microanalysis.NISTMonte.Gen3; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.TreeMap; import gov.nist.microanalysis.EPQLibrary.PhysicalConstants; import gov.nist.microanalysis.EPQLibrary.XRayTransition; import gov.nist.microanalysis.EPQLibrary.XRayTransitionSet; import gov.nist.microanalysis.NISTMonte.MonteCarloSS; import gov.nist.microanalysis.NISTMonte.Gen3.BaseXRayGeneration3.CharacteristicXRay; import gov.nist.microanalysis.NISTMonte.Gen3.BaseXRayGeneration3.XRay; import gov.nist.microanalysis.Utility.HalfUpFormat; /** * <p> * A simple acccumulator for recording the generated and emitted intensities on * a list of lines. * </p> * <p> * Copyright: Pursuant to title 17 Section 105 of the United States Code this * software is not subject to copyright protection and is in the public domain * </p> * <p> * Company: National Institute of Standards and Technology * </p> * * @author Nicholas W M Ritchie * @version 1.0 */ final public class XRayAccumulator3 implements ActionListener { private class Accumulator { final XRayTransitionSet mTransitions; double mGenerated; double mTransmitted; private Accumulator(XRayTransitionSet xrt) { mTransitions = xrt; mGenerated = 0.0; mTransmitted = 0.0; } } private final TreeMap<XRayTransition, Accumulator> mData = new TreeMap<XRayTransition, Accumulator>(); private final ArrayList<Accumulator> mAccumulators = new ArrayList<Accumulator>(); private int mElectronCount; private int mEventCount; private final double mScale; private final String mType; private final static double I_NORM = 1.0e-6 / (4.0 * Math.PI); /** * XRayAccumulator - Create an accumulator to record the sum of the generated * and transmitted x-ray intensity on the Set of XRayTransition or * AtomicShell objects in lines. * * @param lines Collection&lt;XRayTransition&gt; * @param type * @param dose in amps */ public XRayAccumulator3(Collection<XRayTransition> lines, String type, double dose) { for(XRayTransition xrt : lines) { final Accumulator acc = new Accumulator(new XRayTransitionSet(xrt)); mData.put(xrt, acc); mAccumulators.add(acc); } mScale = computeScale(dose); mType = type; clear(); } /** * XRayAccumulator - Create an accumulator to record the sum of the generated * and transmitted x-ray intensity on the Set of XRayTransition or * AtomicShell objects in lines. AtomicShells are translated into the * strongest available XRayTransition. * * @param xrtss Set&lt;XRayTransitionSet&gt; * @param type * @param dose in amps */ public XRayAccumulator3(Set<XRayTransitionSet> xrtss, String type, double dose) { for(final XRayTransitionSet xrts : xrtss) { final Accumulator acc = new Accumulator(xrts); for(XRayTransition xrt : xrts) mData.put(xrt, acc); mAccumulators.add(acc); } mScale = computeScale(dose); mType = type; clear(); } /** * getTransitions - Get an immutable list of the transitions that are being * accumulated. * * @return List&lt;XRayTransition&gt; */ public List<XRayTransition> getTransitions() { ArrayList<XRayTransition> res = new ArrayList<XRayTransition>(); for(XRayTransition xrt : mData.keySet()) res.add(xrt); return Collections.unmodifiableList(res); } /** * clear - Reset the accumulator to zero. */ public void clear() { for(final Accumulator acc : mAccumulators) { acc.mGenerated = 0.0; acc.mTransmitted = 0.0; } mElectronCount = 0; mEventCount = 0; } /** * Invoked when an action occurs. Responds to XRayEventListener events. * * @param ae ActionEvent from an XRayTransport objec */ @Override public void actionPerformed(ActionEvent ae) { final Object src = ae.getSource(); switch(ae.getID()) { case BaseXRayGeneration3.XRayGeneration: { assert src instanceof XRayTransport3; final XRayTransport3 tran = (XRayTransport3) src; for(int i = tran.getEventCount() - 1; i >= 0; --i) { final XRay tr = tran.getXRay(i); if(tr instanceof CharacteristicXRay) { final XRayTransition xrt = ((CharacteristicXRay) tr).getTransition(); final Accumulator acc = mData.get(xrt); if(acc != null) { acc.mGenerated += tr.getGenerated(); acc.mTransmitted += tr.getIntensity(); } } } ++mEventCount; } break; case MonteCarloSS.TrajectoryStartEvent: ++mElectronCount; break; } } /** * getEmitted - Get the transmitted intensity for the specified transition in * x-rays per millistetradian of detector solid angle. * * @param xrt * @return double */ public double getEmitted(XRayTransition xrt) { final Accumulator acc = mData.get(xrt); return acc != null ? I_NORM * mScale * acc.mTransmitted / mElectronCount : 0.0; } /** * Compute probe dose correct scaling * * @param probeDose in amp*s * @return A scaling factor for the data */ private static double computeScale(double probeDose) { return probeDose / PhysicalConstants.ElectronCharge; } /** * getSumEmitted - Returns the sum of the emitted intensity for all * transitions. * * @return double */ public double getSumEmitted() { double res = 0.0; for(final Accumulator acc : mAccumulators) res += acc.mTransmitted; return I_NORM * mScale * res / mElectronCount; } /** * getSumGenerated - Returns the sum of the generated intensity for all * transitons. * * @return double */ public double getSumGenerated() { double res = 0.0; for(final Accumulator acc : mAccumulators) res += acc.mGenerated; return I_NORM * mScale * res / mElectronCount; } /** * getGenerated - Get the generated intensity for the specified transition in * x-rays per millistetradian of detector solid angle. * * @param xrt * @return double */ public double getGenerated(XRayTransition xrt) { final Accumulator acc = mData.get(xrt); return acc != null ? I_NORM * mScale * acc.mGenerated / mElectronCount : 0.0; } public boolean contains(XRayTransition xrt) { return mData.get(xrt) != null; } /** * dump - Output the resulting accumulation to a PrintWriter in tab seperated * values suitable to import into a spreadsheet. * * @param pw PrintWriter */ public void dump(PrintWriter pw) { pw.println("Type:\t" + mType); pw.print("# of electrons\t"); pw.println(mElectronCount); pw.print("# of scattering events\t"); pw.println(mEventCount); pw.println("Transition\tGenerated (1/mSr)\tTransmitted (1/mSr)"); for(final XRayTransition xrt : mData.keySet()) { pw.print(xrt.toString()); pw.print('\t'); pw.print(getGenerated(xrt)); pw.print('\t'); pw.print(getEmitted(xrt)); pw.println(); } pw.flush(); } public String toHTML() { final StringBuffer sb = new StringBuffer(); final NumberFormat nf1 = new HalfUpFormat("#,##0.0"); sb.append("<table class=\"leftalign\">"); sb.append("<tr><th>Transition</th><th>Generated<br>1/msR</th><th>Emitted<br>1/msR</th><th>&nbsp;&nbsp;Ratio&nbsp;&nbsp;<br>(&#37;)</th></tr>"); for(final XRayTransition xrt : mData.keySet()) { sb.append("<tr><th>"); sb.append(xrt.toString()); sb.append("</th><td>"); sb.append(nf1.format(getGenerated(xrt))); sb.append("</td><td>"); sb.append(nf1.format(getEmitted(xrt))); sb.append("</td><td>"); if(getGenerated(xrt) > 0.0) { sb.append(nf1.format((100.0 * getEmitted(xrt)) / getGenerated(xrt))); sb.append("&#37;</td></tr>"); } else sb.append("--</td></tr>"); } sb.append("</table>"); return sb.toString(); } private Accumulator find(XRayTransitionSet xrts) { for(final Accumulator acc : mAccumulators) if(acc.mTransitions.equals(xrts)) return acc; return null; } public String compareAsHTML(XRayAccumulator3 xra2) { final StringBuffer sb = new StringBuffer(); final NumberFormat nf1 = new HalfUpFormat("0.0000"); sb.append("<table class=\"leftalign\">"); sb.append("<tr><th>Transition</th><th>&nbsp;&nbsp;Generated&nbsp;&nbsp;<br>(ratio)</th><th>&nbsp;&nbsp;Emitted&nbsp;&nbsp;<br>(ratio)</th></tr>"); for(final Accumulator acc : mAccumulators) { final Accumulator acc2 = xra2.find(acc.mTransitions); if((acc2 != null) && (acc.mGenerated > 0.0)) { sb.append("<tr><th>"); sb.append(acc.mTransitions.toString()); sb.append("</th><td>"); sb.append(nf1.format((xra2.mScale * acc2.mGenerated / xra2.mElectronCount) / (mScale * acc.mGenerated / mElectronCount))); sb.append("</td><td>"); sb.append(nf1.format((xra2.mScale * acc2.mTransmitted / xra2.mElectronCount) / (mScale * acc.mTransmitted / mElectronCount))); sb.append("</td></tr>"); } } sb.append("</table>"); return sb.toString(); } @Override public String toString() { return mType; } }
Java
CL
67cf8481d6bcfc4d6b31236d3eb1c5173a1c131909b1ddfd27855b48f07b6b4e
package py.com.sodep.mobileforms.web.controllers.scripting; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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 org.springframework.web.servlet.ModelAndView; import py.com.sodep.mobileforms.api.entities.core.User; import py.com.sodep.mobileforms.api.entities.scripting.SodepScript; import py.com.sodep.mobileforms.api.services.scripting.IScriptingService; import py.com.sodep.mobileforms.utils.StringUtils; import py.com.sodep.mobileforms.web.controllers.SodepController; import py.com.sodep.mobileforms.web.json.JsonResponse; @Controller public class ScriptingController extends SodepController { private static Logger logger = LoggerFactory.getLogger(ScriptingController.class); @Autowired private IScriptingService scriptingService; @RequestMapping(value = "/scripting/scripting.mob", method = RequestMethod.GET) public ModelAndView get(HttpSession session, HttpServletRequest request) { User user = getUser(request); ModelAndView mav = new ModelAndView("/scripting/scripting.ftl"); mav.addObject("script", ""); mav.addObject("out", ""); mav.addObject("tabIndex", 0); List<SodepScript> scripts = scriptingService.listScripts(user); mav.addObject("scripts", scripts); return mav; } @RequestMapping(value = "/scripting/execute_script.ajax", method = RequestMethod.POST) @ResponseBody public JsonResponse<Object> executeScript(HttpSession session, HttpServletRequest request) { // User user = getUser(request); String script = request.getParameter("script"); logger.debug("Execute Script:"); logger.debug(script); String out = null; JsonResponse<Object> response = new JsonResponse<Object>(); response.setSuccess(true); try { out = scriptingService.executeScript(null, script); } catch (Exception e) { out = e.getMessage(); if (out != null) { out = out + "\n" + StringUtils.getStackTraceAsString(e); } } response.addContent("script", script); response.addContent("out", out); response.addContent("tabIndex", 1); //List<SodepScript> scripts = scriptingService.listScripts(user); //result.addContent("scripts", scripts); return response; } @RequestMapping(value = "/scripting/save_script.ajax", method = RequestMethod.POST) @ResponseBody public JsonResponse<List<SodepScript>> saveScript(HttpSession session, HttpServletRequest request) { User user = getUser(request); String script = request.getParameter("script"); String scriptName = request.getParameter("scriptName"); JsonResponse<List<SodepScript>> response = new JsonResponse<List<SodepScript>>(); SodepScript saved = scriptingService.saveScript(user, script, scriptName); List<SodepScript> scripts = scriptingService.listScripts(user); if (scriptName == null || scriptName.trim().length() < 3 || script == null || script.trim().length() == 0) { response.setSuccess(false); response.setMessage("Nombre de Script o Script inválido/vacío"); return response; } for (SodepScript s : scripts) { s.setUser(null); } response.setSuccess(true); response.addContent("scripts", scripts); response.setMessage("Se guardó el Script " + saved.getId()); return response; } @RequestMapping(value = "/scripting/list_scripts.ajax", method = RequestMethod.POST) @ResponseBody public JsonResponse<List<SodepScript>> listScripts(HttpSession session, HttpServletRequest request) { User user = getUser(request); JsonResponse<List<SodepScript>> response = new JsonResponse<List<SodepScript>>(); List<SodepScript> scripts = scriptingService.listScripts(user); for (SodepScript s : scripts) { s.setUser(null); } response.setSuccess(true); Map<String, Object> content = new HashMap<String, Object>(); content.put("scripts", new ArrayList<Object>()); return response; } @RequestMapping(value = "/scripting/get_script.ajax", method = RequestMethod.POST) @ResponseBody public JsonResponse<SodepScript> getScript(HttpSession session, HttpServletRequest request, @RequestParam(value = "id") Long id) { JsonResponse<SodepScript> response = new JsonResponse<SodepScript>(); User user = getUser(request); SodepScript script = scriptingService.getScript(user, id); response.setSuccess(true); response.addContent("script", script); return response; } }
Java
CL
056a672efa15a3947d49218e5b7d2b090dce63a47ec5d66bd161a4b311d533e8
package com.android.miki.quickly.login_signup; import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import com.android.miki.quickly.R; import com.android.miki.quickly.ui.CustomTextInputLayout; import com.android.miki.quickly.utils.FieldValidator; import com.android.miki.quickly.utils.FirebaseError; import com.android.miki.quickly.utils.TextValidator; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseNetworkException; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException; import com.google.firebase.auth.FirebaseAuthUserCollisionException; import com.google.firebase.auth.FirebaseAuthWeakPasswordException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.UserProfileChangeRequest; /** * Created by mpokr on 8/13/2017. */ public class SignUpFragment extends Fragment implements FieldValidator { private CustomTextInputLayout emailInputLayout; private CustomTextInputLayout nameInputLayout; private CustomTextInputLayout passwordInputLayout; private Button signUpButton; private FirebaseAuth auth; private static final String TAG = SignUpFragment.class.getName(); private SignUpListener callbackToActivity; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_sign_up, container, false); emailInputLayout = view.findViewById(R.id.email_text_input); nameInputLayout = view.findViewById(R.id.name_text_input); passwordInputLayout = view.findViewById(R.id.password_text_input); //passwordInputLayout.setPasswordVisibilityToggleEnabled(true); FOR NOW Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.text_field_error); emailInputLayout.setErrorDrawable(drawable); nameInputLayout.setErrorDrawable(drawable); passwordInputLayout.setErrorDrawable(drawable); signUpButton = view.findViewById(R.id.sign_up_button); auth = FirebaseAuth.getInstance(); signUpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = nameInputLayout.getTrimmedText(); String password = passwordInputLayout.getTrimmedText(); String email = emailInputLayout.getTrimmedText(); if (validateFields()) { createAccount(name, email, password); } } }); return view; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof Activity) { try { callbackToActivity = (SignUpListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement SignUpListener"); } } else { Log.d(TAG, "Context in onAttach() is not an activity."); } } /** * Validates the email and password fields, and displays appropriate error messages if they are invalid. * * @return True if the fields are valid, false otherwise. */ public boolean validateFields() { String name = nameInputLayout.getTrimmedText(); TextValidator textValidator = new TextValidator(); String nameValidationMessage = textValidator.isValidName(name); boolean areFieldsValid = true; if (nameValidationMessage != null) { areFieldsValid = false; nameInputLayout.setError(nameValidationMessage); } String password = passwordInputLayout.getTrimmedText(); if (TextUtils.isEmpty(password)) { passwordInputLayout.setError("Please enter a password."); areFieldsValid = false; } String email = emailInputLayout.getTrimmedText(); if (TextUtils.isEmpty(email)) { emailInputLayout.setError("Please enter an email address."); areFieldsValid = false; } return areFieldsValid; } private void createAccount(final String name, final String email, String password) { auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign up with email and password successful. Log.d(TAG, "createUserWithEmail:success"); final FirebaseUser user = auth.getCurrentUser(); final UserProfileChangeRequest updateName = new UserProfileChangeRequest.Builder(). setDisplayName(name).build(); if (user == null) { Log.d(TAG, "Created user in SignUpMethodSelectionFragment is null"); callbackToActivity.onFailedSignUp(); // TODO: Delete user. } else { user.updateProfile(updateName).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { callbackToActivity.onSuccessfulSignUp(user); } else { // TODO: Delete user. // TODO: Throw and catch exceptions. callbackToActivity.onFailedSignUp(); } } }); } } else { try { // If sign in fails, display a message to the user. Log.e(TAG, "createUserWithEmail:failure", task.getException()); throw task.getException(); } catch (FirebaseAuthWeakPasswordException e) { // Thrown if the password is not strong enough. passwordInputLayout.setError(e.getReason()); } catch (FirebaseAuthInvalidCredentialsException e) { // Thrown if the email address is malformed. emailInputLayout.setError(e.getLocalizedMessage()); } catch (FirebaseAuthUserCollisionException e) { Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } catch (FirebaseNetworkException e) { FirebaseError networkError = FirebaseError.networkError(); Toast.makeText(getContext(), networkError.getMessage(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { FirebaseError unknownError = FirebaseError.unknownError(); Toast.makeText(getContext(), unknownError.getMessage(), Toast.LENGTH_SHORT).show(); } } } }); } }
Java
CL
4fdc7f3b7c1167f5320d0364a028e89cccac8c563f93307eaa3157eb11ad42da
package mage.cards.a; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.ReturnFromGraveyardToBattlefieldTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.SubType; import mage.filter.FilterCard; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.common.TargetCardInYourGraveyard; /** * * @author Loki */ public final class AuriokSurvivors extends CardImpl { private static final FilterCard filter = new FilterCard("Equipment card from your graveyard"); static { filter.add(SubType.EQUIPMENT.getPredicate()); } public AuriokSurvivors(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{5}{W}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SOLDIER); this.power = new MageInt(4); this.toughness = new MageInt(6); // When Auriok Survivors enters the battlefield, you may return target Equipment card from your graveyard to the battlefield. If you do, you may attach it to Auriok Survivors. Ability ability = new EntersBattlefieldTriggeredAbility(new ReturnFromGraveyardToBattlefieldTargetEffect(), true); ability.addEffect(new AuriokSurvivorsEffect()); ability.addTarget(new TargetCardInYourGraveyard(filter)); this.addAbility(ability); } private AuriokSurvivors(final AuriokSurvivors card) { super(card); } @Override public AuriokSurvivors copy() { return new AuriokSurvivors(this); } } class AuriokSurvivorsEffect extends OneShotEffect { AuriokSurvivorsEffect() { super(Outcome.Neutral); staticText = "If you do, you may attach it to {this}"; } AuriokSurvivorsEffect(final AuriokSurvivorsEffect effect) { super(effect); } @Override public boolean apply(Game game, Ability source) { Permanent p = game.getPermanent(targetPointer.getFirst(game, source)); Permanent sourcePermanent = game.getPermanent(source.getSourceId()); Player player = game.getPlayer(source.getControllerId()); if (p != null && player != null && sourcePermanent != null) { if (player.chooseUse(Outcome.Benefit, "Attach " + p.getName() + " to " + sourcePermanent.getName() + '?', source, game)) { sourcePermanent.addAttachment(p.getId(), source, game); } return true; } return false; } @Override public AuriokSurvivorsEffect copy() { return new AuriokSurvivorsEffect(this); } }
Java
CL
f6b1db19b1c1d0f2750ead12eb99decb0e75556ae1259fd1c39ecc2ec53e776c
package rt.intersectables; import java.util.Iterator; import rt.Intersectable; import rt.Material; import rt.Spectrum; import rt.materials.Diffuse; /** * A triangle mesh. The mesh internally stores the triangles using vertex * and index arrays. The mesh also instantiates a {@link MeshTriangle} for each triangle, * and the mesh provides an iterator to iterate through the triangles. */ public class Mesh extends Aggregate { /** * Array of triangle vertices. Stores x,y,z coordinates for each vertex consecutively. */ public float[] vertices; /** * Array of triangle normals (one per vertex). Stores x,y,z coordinates for each normal consecutively. */ public float[] normals; /** * Array of texture coordinates (one per vertex). Stores x,y coordinates for each texture coordinate consecutively. */ public float[] texCoords; /** * Index array. Each triangle is defined by three consecutive * indices in this array. The indices refer to the {@link Mesh#vertices} * and {@link Mesh#normals} arrays that store vertex and normal coordinates. */ public int[] indices; /** * Array of triangles stored in the mesh. */ private MeshTriangle[] triangles; /** * A material. */ public Material material; /** * Make a mesh from arrays with vertices, normals, and indices. */ public Mesh(float[] vertices, float[] normals, float[] texCoordsFinal, int[] indices) { material = new Diffuse(new Spectrum(1.f, 1.f, 1.f)); this.vertices = vertices; this.normals = normals; this.indices = indices; triangles = new MeshTriangle[indices.length/3]; // A triangle simply stores a triangle index and refers back to the mesh // to look up the vertex data for (int i = 0; i < indices.length / 3; i++) { triangles[i] = new MeshTriangle(this, i); } } public Iterator<Intersectable> iterator() { return new MeshIterator(triangles); } private class MeshIterator implements Iterator<Intersectable> { private int i; private MeshTriangle[] triangles; public MeshIterator(MeshTriangle[] triangles) { this.triangles = triangles; i = 0; } public boolean hasNext() { return i<triangles.length; } public MeshTriangle next() { int j = i; i++; return triangles[j]; } public void remove() { } } }
Java
CL
2168565d63a8441a5a0b5b3033e50dc877a4debd661f8adee3d25aeb4ce006ff
package com.commercetools.api.models.common; import java.util.Arrays; import java.util.function.Function; import javax.annotation.Nullable; import javax.money.*; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.*; import io.vrap.rmf.base.client.utils.Generated; /** * <p>Draft type that stores amounts in cent precision for the specified currency.</p> * <p>For storing money values in fractions of the minor unit in a currency, use HighPrecisionMoneyDraft instead.</p> * * <hr> * Example to create an instance using the builder pattern * <div class=code-example> * <pre><code class='java'> * Money money = Money.builder() * .centAmount(0.3) * .currencyCode("{currencyCode}") * .build() * </code></pre> * </div> */ @Generated(value = "io.vrap.rmf.codegen.rendering.CoreCodeGenerator", comments = "https://github.com/commercetools/rmf-codegen") @JsonDeserialize(as = MoneyImpl.class) @JsonIgnoreProperties(value = { "factory", "context", "number", "currency", "negative", "negativeOrZero", "positiveOrZero", "zero", "positive" }) public interface Money extends com.commercetools.api.models.common.MonetaryAmountConvertable, MonetaryAmount { /** * <p>Amount in the smallest indivisible unit of a currency, such as:</p> * <ul> * <li>Cents for EUR and USD, pence for GBP, or centime for CHF (5 CHF is specified as <code>500</code>).</li> * <li>The value in the major unit for currencies without minor units, like JPY (5 JPY is specified as <code>5</code>).</li> * </ul> * @return centAmount */ @NotNull @JsonProperty("centAmount") public Long getCentAmount(); /** * <p>Currency code compliant to ISO 4217.</p> * @return currencyCode */ @NotNull @JsonProperty("currencyCode") public String getCurrencyCode(); public void setCentAmount(final Long centAmount); public void setCurrencyCode(final String currencyCode); public static Money of() { return new MoneyImpl(); } public static Money of(final Money template) { MoneyImpl instance = new MoneyImpl(); instance.setCentAmount(template.getCentAmount()); instance.setCurrencyCode(template.getCurrencyCode()); return instance; } @Nullable public static Money deepCopy(@Nullable final Money template) { if (template == null) { return null; } MoneyImpl instance = new MoneyImpl(); instance.setCentAmount(template.getCentAmount()); instance.setCurrencyCode(template.getCurrencyCode()); return instance; } public static MoneyBuilder builder() { return MoneyBuilder.of(); } public static MoneyBuilder builder(final Money template) { return MoneyBuilder.of(template); } default <T> T withMoney(Function<Money, T> helper) { return helper.apply(this); } public default TypedMoneyDraft toDraft() { if (this instanceof TypedMoneyDraft) { return (TypedMoneyDraft) this; } return TypedMoneyDraft.centPrecisionBuilder() .centAmount(this.getCentAmount()) .currencyCode(this.getCurrencyCode()) .build(); } public static com.fasterxml.jackson.core.type.TypeReference<Money> typeReference() { return new com.fasterxml.jackson.core.type.TypeReference<Money>() { @Override public String toString() { return "TypeReference<Money>"; } }; } default MonetaryOperator createMoneyOperator() { return MoneyUtil::of; } @Override default MonetaryContext getContext() { return toMonetaryAmount().getContext(); } @Override default MonetaryAmountFactory<? extends MonetaryAmount> getFactory() { return toMonetaryAmount().getFactory(); } @Override default boolean isGreaterThan(MonetaryAmount amount) { return toMonetaryAmount().isGreaterThan(amount); } @Override default boolean isGreaterThanOrEqualTo(MonetaryAmount amount) { return toMonetaryAmount().isGreaterThanOrEqualTo(amount); } @Override default boolean isLessThan(MonetaryAmount amount) { return toMonetaryAmount().isLessThan(amount); } @Override default boolean isLessThanOrEqualTo(MonetaryAmount amount) { return toMonetaryAmount().isLessThanOrEqualTo(amount); } @Override default boolean isEqualTo(MonetaryAmount amount) { return toMonetaryAmount().isEqualTo(amount); } @Override default int signum() { return toMonetaryAmount().signum(); } @Override default MonetaryAmount add(MonetaryAmount augend) { return createMoneyOperator().apply(toMonetaryAmount().add(augend)); } @Override default MonetaryAmount subtract(MonetaryAmount subtrahend) { return createMoneyOperator().apply(toMonetaryAmount().subtract(subtrahend)); } @Override default MonetaryAmount multiply(long multiplicand) { return createMoneyOperator().apply(toMonetaryAmount().multiply(multiplicand)); } @Override default MonetaryAmount multiply(double multiplicand) { return createMoneyOperator().apply(toMonetaryAmount().multiply(multiplicand)); } @Override default MonetaryAmount multiply(Number multiplicand) { return createMoneyOperator().apply(toMonetaryAmount().multiply(multiplicand)); } @Override default MonetaryAmount divide(long divisor) { return createMoneyOperator().apply(toMonetaryAmount().divide(divisor)); } @Override default MonetaryAmount divide(double divisor) { return createMoneyOperator().apply(toMonetaryAmount().divide(divisor)); } @Override default MonetaryAmount divide(Number divisor) { return createMoneyOperator().apply(toMonetaryAmount().divide(divisor)); } @Override default MonetaryAmount remainder(long divisor) { return createMoneyOperator().apply(toMonetaryAmount().remainder(divisor)); } @Override default MonetaryAmount remainder(double divisor) { return createMoneyOperator().apply(toMonetaryAmount().remainder(divisor)); } @Override default MonetaryAmount remainder(Number divisor) { return createMoneyOperator().apply(toMonetaryAmount().remainder(divisor)); } @Override default MonetaryAmount[] divideAndRemainder(long divisor) { MonetaryOperator op = createMoneyOperator(); return Arrays.stream(toMonetaryAmount().divideAndRemainder(divisor)) .map(op::apply) .toArray(MonetaryAmount[]::new); } @Override default MonetaryAmount[] divideAndRemainder(double divisor) { MonetaryOperator op = createMoneyOperator(); return Arrays.stream(toMonetaryAmount().divideAndRemainder(divisor)) .map(op::apply) .toArray(MonetaryAmount[]::new); } @Override default MonetaryAmount[] divideAndRemainder(Number divisor) { MonetaryOperator op = createMoneyOperator(); return Arrays.stream(toMonetaryAmount().divideAndRemainder(divisor)) .map(op::apply) .toArray(MonetaryAmount[]::new); } @Override default MonetaryAmount divideToIntegralValue(long divisor) { return createMoneyOperator().apply(toMonetaryAmount().divideToIntegralValue(divisor)); } @Override default MonetaryAmount divideToIntegralValue(double divisor) { return createMoneyOperator().apply(toMonetaryAmount().divideToIntegralValue(divisor)); } @Override default MonetaryAmount divideToIntegralValue(Number divisor) { return createMoneyOperator().apply(toMonetaryAmount().divideToIntegralValue(divisor)); } @Override default MonetaryAmount scaleByPowerOfTen(int power) { return createMoneyOperator().apply(toMonetaryAmount().scaleByPowerOfTen(power)); } @Override default MonetaryAmount abs() { return createMoneyOperator().apply(toMonetaryAmount().abs()); } @Override default MonetaryAmount negate() { return createMoneyOperator().apply(toMonetaryAmount().negate()); } @Override default MonetaryAmount plus() { return createMoneyOperator().apply(toMonetaryAmount().plus()); } @Override default MonetaryAmount stripTrailingZeros() { return createMoneyOperator().apply(toMonetaryAmount().stripTrailingZeros()); } @Override default int compareTo(MonetaryAmount o) { return toMonetaryAmount().compareTo(o); } @Override default CurrencyUnit getCurrency() { return toMonetaryAmount().getCurrency(); } @Override default NumberValue getNumber() { return toMonetaryAmount().getNumber(); } @Override default <R> R query(MonetaryQuery<R> query) { return toMonetaryAmount().query(query); } @Override default MonetaryAmount with(MonetaryOperator operator) { return toMonetaryAmount().with(operator); } }
Java
CL
6d3a7835570ef836a9223404e4284376fd6dd2f003dd4e21783e2c3626dd713d
// 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.amazon.avod; import android.app.Activity; import java.util.List; public interface MShopAmazonInstantVideo { public abstract void forceRefreshAccount(); public abstract List getGroverRecommendations(); public abstract long getGroverRecommendationsTTLMillis(); public abstract boolean isAIVBeta(); public abstract boolean isPlaybackSustainable(); public abstract boolean isSupported(); public abstract void refreshUserData(); public abstract void startPlayback(Activity activity, String s, long l); public abstract void startTrailer(Activity activity, String s); public abstract void verifyAndroidRuntime(Activity activity, Runnable runnable); public abstract void whisperCache(List list); }
Java
CL
5455e5e9ff20b338c35f12aa8b92c38e2e61234a3753531a45b3de6d017676c4
package day07; import java.io.BufferedInputStream; import java.io.BufferedReader; /** * 流 * 流是java标准的读写操作方式 * 流按功能分为: * 输入流: * 用来读取文件流 * 输出流: * 用来写出文件流 * * 流分为 * 节点流(低级流):数据明确,读写一定建立在低级流 * 上,真实负责在数据源与程序间搬运数据 * 处理流(高级流):不能独立存在(没有意义),需要建立 * 在其他流之上,对其处理,使用处理流的 * 目的在于简化读写操作 * * java.io.FileInputStream * 文件输出流 * * 文件输出流用于将数据写入文件中 * @author soft01 * */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; public class FileOutputStreamDemo { public static void main(String[] args) throws Exception{ /* * 构造方法: * FileOutputStream(String path) * FileOutputStream(File path) * 上面两种形式创建的文件输出流默认为覆盖写操作 * 即:指定的文件若已存在,则会先将该文件所有数据清除, * 然后通过该流写出的内容会作为该文件的内容 * */ FileOutputStream fileOutputStream = new FileOutputStream(new File("Demo.txt"),true); String get = "集哦撒旦回iwqodhiosadwkoxhisabxiuhiowfc"; fileOutputStream.write(get.getBytes("UTF-8")); fileOutputStream.write("wad".getBytes()); fileOutputStream.close(); System.out.println("写入成功"); } }
Java
CL
4b66c665d99bd53afe24791415df70dee8525af43b00e57861201d4df6d62665
package com.jukusoft.mmo.engine.shared.messages; import com.jukusoft.vertx.serializer.SerializableObject; import com.jukusoft.vertx.serializer.annotations.*; import io.vertx.core.json.JsonArray; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * message which is sended from proxy server to gameserver to join player */ @MessageType(type = 0x01, extendedType = 0x07) @ProtocolVersion(1) public class JoinRegionMessage implements SerializableObject { //cluster credentials @SString(maxCharacters = Integer.MAX_VALUE) public String cluster_username = ""; @SString(maxCharacters = Integer.MAX_VALUE) public String cluster_password = ""; //user & character information @SInteger public int cid = -1; @SInteger public int userID = -1; @SString(maxCharacters = 64) public String username = ""; @SString(maxCharacters = Integer.MAX_VALUE) protected String groupsJson = ""; //region information @SLong public long regionID = 0; @SInteger public int instanceID = 0; @SInteger public int shardID = 0; /** * set groups and convert them to internal json array to use for serializer * * @param groups list with all permission group names user belongs to */ public void setGroups (List<String> groups) { JsonArray jsonArray = new JsonArray(); for (String groupName : groups) { jsonArray.add(groupName); } this.groupsJson = jsonArray.encode(); } /** * converts json string to list with groups and returns them * * @return list with all permission group names user belongs to */ public List<String> listGroups () { Objects.requireNonNull(this.groupsJson); if (this.groupsJson.isEmpty()) { throw new IllegalStateException("groupsJson is empty."); } JsonArray jsonArray = new JsonArray(groupsJson); List<String> groups = new ArrayList<>(); for (int i = 0; i < jsonArray.size(); i++) { groups.add(jsonArray.getString(i)); } return groups; } }
Java
CL
f4ca5a3c9c5c34ef418b6679a9b298008ea4637e94b1a9affbadc9f3c2ef379e
package test.connections.snmp; import static org.junit.Assert.*; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.snmp4j.agent.mo.MOAccessImpl; import org.snmp4j.agent.mo.MOScalar; import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString; import org.snmp4j.smi.VariableBinding; import rockthenet.connections.ConnectionException; import rockthenet.connections.snmp.SNMPConnectionFactory; import rockthenet.connections.ReadConnection; import rockthenet.connections.snmp.SNMPv2cConnection; /* TODO: add a real MOTable for testing */ /** * Unit-tests for {@link SNMPv2cConnection} * * @author Elias Frantar * @version 2014-10-05 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class SNMPv2cConnectionTest { private static final String ADDRESS = "127.0.0.1"; private static final int PORT = 1025; private static final String COMMUNITY_NAME = "test"; private static final String SECURITY_NAME = "test"; private static final String OID_1 = "1.3.1.1.1.1.1.1.1.1"; private static final String OID_2 = "1.3.2.1.1.1.1.1.1.1"; private static final String OID_1_TEXT = "This is the first test!"; private static final String OID_2_TEXT = "This is the second test!"; private ReadConnection connection; private SNMPv2Agent snmpAgent = null; /* execute before and after every test-case */ @Before public void setup() throws ConnectionException, IOException { if(snmpAgent == null) snmpAgent = new SNMPv2Agent(ADDRESS, PORT, COMMUNITY_NAME); snmpAgent.start(); snmpAgent.unregisterManagedObject(snmpAgent.getSnmpv2MIB()); snmpAgent.registerManagedObject(new MOScalar(new OID(OID_1), new MOAccessImpl(1), new OctetString(OID_1_TEXT))); snmpAgent.registerManagedObject(new MOScalar(new OID(OID_2), new MOAccessImpl(1), new OctetString(OID_2_TEXT))); connection = SNMPConnectionFactory.createSNMPv2cConnection(ADDRESS, PORT, COMMUNITY_NAME, SECURITY_NAME); } @After public void tearDown() { connection.close(); snmpAgent.stop(); } /* test-cases for successful operations */ @Test public void singleGetTest() throws ConnectionException { String result = connection.get(OID_1).toValueString(); assertEquals(OID_1_TEXT, result); } @Test public void multipleGetTest() throws ConnectionException { VariableBinding[] result = connection.get(new String[]{OID_1, OID_2}); assertEquals(OID_1_TEXT, result[0].toValueString()); assertEquals(OID_2_TEXT, result[1].toValueString()); } @Test public void getTableTest() throws ConnectionException { VariableBinding[] result = connection.getTable(OID_1.substring(0, OID_1.length() - 2)); assertEquals(OID_1_TEXT, result[0].toValueString()); } @Test public void connectTwiceTest() throws ConnectionException { // should still work afterwards connection.establish(); connection.establish(); String result = connection.get(OID_1).toValueString(); assertEquals(OID_1_TEXT, result); } @Test public void reconnectTest() throws ConnectionException { connection.close(); connection.establish(); String result = connection.get(OID_1).toValueString(); assertEquals(OID_1_TEXT, result); } @Test (expected = ConnectionException.class) public void closeTest() throws ConnectionException { connection.close(); connection.get(OID_1); } @Test public void closeTwiceTest() { // should not throw any Exceptions connection.close(); connection.close(); } /* test-cases for failing operations */ @Test public void getWrongOIDTest() throws ConnectionException { String result = connection.get("2.3.4.5").toValueString(); assertEquals("noSuchObject", result); } /* Exception tests */ @Test (expected = ConnectionException.class) public void invalidAddressTest() throws ConnectionException { connection.close(); connection = SNMPConnectionFactory.createSNMPv2cConnection("aaa", PORT, COMMUNITY_NAME, SECURITY_NAME); } @Test (expected = ConnectionException.class) public void notExistingAddressTest() throws ConnectionException { connection.close(); connection = SNMPConnectionFactory.createSNMPv2cConnection("10.10.10.10", PORT, COMMUNITY_NAME, SECURITY_NAME); } @Test (expected = ConnectionException.class) public void getWithClientDownTest() throws ConnectionException { connection.close(); connection.get(OID_1); } @Test (expected = ConnectionException.class) public void getWithServerDownTest() throws ConnectionException { snmpAgent.stop(); connection.get(OID_1); } @Test (expected = ConnectionException.class) public void getTableWithClientDownTest() throws ConnectionException { connection.close(); connection.getTable(OID_1); } @Test (expected = ConnectionException.class) public void getTableWithServerDownTest() throws ConnectionException { snmpAgent.stop(); connection.getTable(OID_1); } }
Java
CL
0e29d4e1b38f19b1ee72420f4fac4cb3fda60e10737354c55ea4f48f622240b5
package com.transvision.trmdisconnreconn.fragments; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.transvision.trmdisconnreconn.MainActivity; import com.transvision.trmdisconnreconn.R; import com.transvision.trmdisconnreconn.adapters.Reconnection_adapter; import com.transvision.trmdisconnreconn.posting.SendingData; import com.transvision.trmdisconnreconn.values.FunctionsCall; import com.transvision.trmdisconnreconn.values.GetSetValues; import java.util.ArrayList; import java.util.Objects; import static android.content.Context.MODE_PRIVATE; import static com.transvision.trmdisconnreconn.values.Constants.PREFS_NAME; import static com.transvision.trmdisconnreconn.values.Constants.RECONNECTION_LIST_FAILURE; import static com.transvision.trmdisconnreconn.values.Constants.RECONNECTION_LIST_SUCCESS; import static com.transvision.trmdisconnreconn.values.Constants.sPref_Login_date; public class Reconnection extends Fragment { View view; FunctionsCall functionsCall; SendingData sendingData; GetSetValues getSetValues; RecyclerView reconnection_view; ArrayList<GetSetValues> reconnection_list; Reconnection_adapter reconnection_adapter; ProgressDialog progressDialog; Context context; SharedPreferences sPref; private Handler reconn_handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what) { case RECONNECTION_LIST_SUCCESS: progressDialog.dismiss(); break; case RECONNECTION_LIST_FAILURE: progressDialog.dismiss(); break; } return false; } }); public Reconnection() { // Required empty public constructor } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_reconnection, container, false); initialize(); functionsCall.showprogressdialog(progressDialog, context.getResources().getString(R.string.reconnection_dlg_title), context.getResources().getString(R.string.reconnection_dlg_msg)); sendingData.new Reconnection_List(reconn_handler, reconnection_list, reconnection_adapter).execute("14001137", functionsCall.convertdateview(sPref.getString(sPref_Login_date, ""), "yy", "-")); return view; } private void initialize() { functionsCall = new FunctionsCall(); sendingData = new SendingData(); getSetValues = ((MainActivity) Objects.requireNonNull(getActivity())).getSetValues(); progressDialog = new ProgressDialog(getActivity()); context = getActivity(); sPref = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE); reconnection_view = view.findViewById(R.id.reconnection_recycler_view); reconnection_list = new ArrayList<>(); reconnection_adapter = new Reconnection_adapter(reconnection_list, context); reconnection_view.setHasFixedSize(true); reconnection_view.setLayoutManager(new LinearLayoutManager(context)); reconnection_view.setAdapter(reconnection_adapter); } @Override public void onDestroyView() { super.onDestroyView(); reconn_handler.removeCallbacksAndMessages(null); } }
Java
CL
876374c1aa91e8e1b65f0b760ae7f60a51ae49cb6e2ee8ef587ddee7ecd3eaf2
package com.moses.cloud.sample.controller; import com.moses.cloud.sample.entity.User; import com.moses.cloud.sample.feign.UserFeignClient; import com.moses.cloud.sample.feign.UserServiceExtend; import com.netflix.discovery.converters.Auto; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class OrderController { private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class); private final String PROVIDER_USER = "http://ms-provider-user"; // @Autowired // private UserFeignClient userFeignClient; @Autowired private UserServiceExtend userServiceExtend; @Autowired private RestTemplate restTemplate; @Autowired private LoadBalancerClient loadBalancerClient; @HystrixCommand( //https://github.com/Netflix/Hystrix/wiki/Configuration#CommandExecution commandProperties = { // 熔断器在整个统计时间内是否开启的阀值 @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="4000"), // 至少有3个请求才进行熔断错误比率计算 // 设置在一个滚动窗口中,打开断路器的最少请求数。 // 比如:如果值是20,在一个窗口内(比如10秒),收到19个请求,即使这19个请求都失败了,断路器也不会打开。 @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "3"), // 当出错率超过50%后熔断器启动 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"), // 熔断器工作时间,超过这个时间,先放一个请求进去,成功的话就关闭熔断,失败就再等一段时间 @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"), // 统计滚动的时间窗口 @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000") }, //https://github.com/Netflix/Hystrix/wiki/Configuration#ThreadPool threadPoolProperties = { @HystrixProperty(name = "coreSize", value = "15"), // BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlockingQueue。 @HystrixProperty(name = "maxQueueSize", value = "15"), // 设置存活时间,单位分钟。如果coreSize小于maximumSize,那么该属性控制一个线程从实用完成到被释放的时间. @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"), //设置队列拒绝的阈值,即使maxQueueSize还没有达到 @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"), @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"), @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000") }, fallbackMethod = "errorContent" ) @GetMapping("/user/{id}") public User findById(@PathVariable Long id) { LOGGER.info("=================请求用户中心接口=================="); return restTemplate.getForObject(PROVIDER_USER + "/" + id, User.class); } public User errorContent(Long id){ User u = new User(); u.setName("ErrorContent: " + id); return u; } @GetMapping("/user-extend/{id}") public User findById2(@PathVariable Long id) { return userServiceExtend.getUser(id); } @GetMapping("/user/getIpAndPort") public String getIpAndPort() { return this.restTemplate.getForObject(PROVIDER_USER + "/getIpAndPort", String.class); } @GetMapping("/log-user-instance") public void logUserInstance() { ServiceInstance serviceInstance = this.loadBalancerClient.choose("ms-provider-user"); // 打印当前选择的是哪个节点 OrderController.LOGGER.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort()); } }
Java
CL
c483c00e3bd4eadab7ad4d2d72bd07374bb46aa47173c7b6655843615fb84069
package co.airy.core.api.communication; import co.airy.avro.communication.Channel; import co.airy.avro.communication.ChannelConnectionState; import co.airy.kafka.test.KafkaTestHelper; import co.airy.kafka.test.junit.SharedKafkaTestResource; import co.airy.spring.core.AirySpringBootApplication; import co.airy.spring.test.WebTestHelper; import org.apache.avro.specific.SpecificRecordBase; import org.apache.kafka.clients.producer.ProducerRecord; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import java.util.UUID; import static co.airy.core.api.communication.util.TestConversation.generateRecords; import static co.airy.core.api.communication.util.Topics.applicationCommunicationChannels; import static co.airy.core.api.communication.util.Topics.getTopics; import static co.airy.test.Timing.retryOnException; import static org.hamcrest.core.Is.is; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AirySpringBootApplication.class) @TestPropertySource(value = "classpath:test.properties") @ExtendWith(SpringExtension.class) @AutoConfigureMockMvc public class MetadataControllerTest { @RegisterExtension public static final SharedKafkaTestResource sharedKafkaTestResource = new SharedKafkaTestResource(); private static KafkaTestHelper kafkaTestHelper; @Autowired private WebTestHelper webTestHelper; private static final Channel channel = Channel.newBuilder() .setConnectionState(ChannelConnectionState.CONNECTED) .setId(UUID.randomUUID().toString()) .setSource("facebook") .setSourceChannelId("ps-id") .build(); @BeforeAll static void beforeAll() throws Exception { kafkaTestHelper = new KafkaTestHelper(sharedKafkaTestResource, getTopics()); kafkaTestHelper.beforeAll(); kafkaTestHelper.produceRecord(new ProducerRecord<>(applicationCommunicationChannels.name(), channel.getId().toString(), channel)); } @AfterAll static void afterAll() throws Exception { kafkaTestHelper.afterAll(); } @BeforeEach void beforeEach() throws Exception { webTestHelper.waitUntilHealthy(); } @Test void canUpsertMetadata() throws Exception { final String conversationId = UUID.randomUUID().toString(); kafkaTestHelper.produceRecord(new ProducerRecord<>(applicationCommunicationChannels.name(), channel.getId(), channel)); final List<ProducerRecord<String, SpecificRecordBase>> producerRecords = generateRecords(conversationId, channel, 1); kafkaTestHelper.produceRecords(producerRecords); final String messageId = producerRecords.get(0).key(); retryOnException( () -> webTestHelper.post("/metadata.upsert", "{\"subject\": \"message\", \"id\": \"" + messageId + "\", \"data\": {\"sentFrom\": \"iPhone\"}}") .andExpect(status().isNoContent()), "Error upserting metadata" ); retryOnException( () -> webTestHelper.post("/conversations.info", "{\"conversation_id\":\"" + conversationId + "\"}") .andExpect(status().isOk()) .andExpect(jsonPath("$.last_message.metadata.user_data.sentFrom", is("iPhone"))), "Conversations list metadata is not present" ); } @Test void failsOnNonStringFieldValues() throws Exception { webTestHelper.post("/metadata.upsert", "{\"subject\": \"channel\", \"id\": \"" + channel.getId() + "\", \"data\": {\"sentFrom\": 123}}") .andExpect(status().isBadRequest()); } }
Java
CL
4e82b087825f965ac8f059e1245b3128fe21ee5533954025c4e3048f54f1efbe
package pe.com.tumi.riesgo.archivo.service; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import pe.com.tumi.common.util.Constante; import pe.com.tumi.framework.negocio.ejb.factory.EJBFactory; import pe.com.tumi.framework.negocio.ejb.factory.EJBFactoryException; import pe.com.tumi.framework.negocio.exception.BusinessException; import pe.com.tumi.framework.negocio.factory.TumiFactory; import pe.com.tumi.parametro.tabla.facade.TablaFacadeRemote; import pe.com.tumi.persona.core.facade.PersonaFacadeRemote; import pe.com.tumi.riesgo.archivo.bo.ConfDetalleBO; import pe.com.tumi.riesgo.archivo.bo.ConfEstructuraBO; import pe.com.tumi.riesgo.archivo.bo.ConfiguracionBO; import pe.com.tumi.riesgo.archivo.bo.NombreBO; import pe.com.tumi.riesgo.archivo.domain.ConfDetalle; import pe.com.tumi.riesgo.archivo.domain.ConfEstructura; import pe.com.tumi.riesgo.archivo.domain.Configuracion; import pe.com.tumi.riesgo.archivo.domain.Nombre; public class ConfiguracionService { protected static Logger log = Logger.getLogger(ConfiguracionService.class); ConfiguracionBO boConfiguracion = (ConfiguracionBO)TumiFactory.get(ConfiguracionBO.class); ConfDetalleBO boConfDetalle = (ConfDetalleBO)TumiFactory.get(ConfDetalleBO.class); NombreBO boNombre = (NombreBO)TumiFactory.get(NombreBO.class); ConfEstructuraBO boConfEstructura = (ConfEstructuraBO)TumiFactory.get(ConfEstructuraBO.class); public Configuracion grabarConfiguracion(Configuracion configuracion, List <ConfDetalle> listaConfDetalle, List<Nombre> listaNombre) throws BusinessException{ try{ log.info(configuracion); boConfiguracion.grabar(configuracion); for(ConfDetalle confDetalle : listaConfDetalle ){ confDetalle.getId().setIntItemConfiguracion(configuracion.getId().getIntItemConfiguracion()); boConfDetalle.grabar(confDetalle); } for(Nombre nombre : listaNombre ){ nombre.getId().setIntItemConfiguracion(configuracion.getId().getIntItemConfiguracion()); boNombre.grabar(nombre); } }catch(BusinessException e){ throw e; }catch(Exception e){ throw new BusinessException(e); } return configuracion; } public Configuracion grabarConfiguracion(Configuracion configuracion, List <ConfDetalle> listaConfDetalle, List<Nombre> listaNombre,ConfEstructura confEstructura) throws BusinessException{ try{ grabarConfiguracion(configuracion, listaConfDetalle, listaNombre); confEstructura.getId().setIntItemConfiguracion(configuracion.getId().getIntItemConfiguracion()); boConfEstructura.grabar(confEstructura); }catch(BusinessException e){ throw e; }catch(Exception e){ throw new BusinessException(e); } return configuracion; } public List<Configuracion> buscarConfiguracion(Configuracion configuracion, Timestamp busquedaInicio, Timestamp busquedaFin) throws BusinessException{ List<Configuracion> listaConfiguracion = null; try{ listaConfiguracion = boConfiguracion.buscar(configuracion, busquedaInicio, busquedaFin); listaConfiguracion = cargarListaConfiguracion(listaConfiguracion); }catch(BusinessException e){ throw e; }catch(Exception e){ throw new BusinessException(e); } return listaConfiguracion; } public List<Configuracion> buscarConfiguracionConEstructura(Configuracion configuracion, Timestamp busquedaInicio, Timestamp busquedaFin) throws BusinessException{ List<Configuracion> listaConfiguracion = null; try{ log.info("bus:"+configuracion); listaConfiguracion = boConfiguracion.buscarConEstructura(configuracion, busquedaInicio, busquedaFin); //Filtro de intParaFormatoArchivoCod List<Configuracion> listaConfiguracionAux = new ArrayList<Configuracion>(); for(Configuracion conf : listaConfiguracion){ log.info("enc:"+configuracion); if(configuracion.getIntParaFormatoArchivoCod().equals(conf.getIntParaFormatoArchivoCod())){ listaConfiguracionAux.add(conf); } } listaConfiguracion = listaConfiguracionAux; listaConfiguracion = cargarListaConfiguracion(listaConfiguracion); }catch(BusinessException e){ throw e; }catch(Exception e){ throw new BusinessException(e); } return listaConfiguracion; } public List<Configuracion> buscarConfiguracionSinEstructura(Configuracion configuracion, Timestamp busquedaInicio, Timestamp busquedaFin) throws BusinessException{ List<Configuracion> listaConfiguracion = null; try{ listaConfiguracion = boConfiguracion.buscarSinEstructura(configuracion, busquedaInicio, busquedaFin); listaConfiguracion = cargarListaConfiguracion(listaConfiguracion); }catch(BusinessException e){ throw e; }catch(Exception e){ throw new BusinessException(e); } return listaConfiguracion; } private List<Configuracion> cargarListaConfiguracion(List<Configuracion> listaConfiguracion) throws EJBFactoryException, BusinessException{ List<Configuracion> listaAux = new ArrayList<Configuracion>(); PersonaFacadeRemote personaFacade = (PersonaFacadeRemote) EJBFactory.getRemote(PersonaFacadeRemote.class); for(Configuracion configura : listaConfiguracion){ log.info(configura); configura.setNatural(personaFacade.getNaturalPorPK(configura.getIntPersPersonaUsuarioPk())); listaAux.add(configura); } listaConfiguracion = listaAux; return listaConfiguracion; } public Configuracion modificarConfiguracion(Configuracion configuracion, List <ConfDetalle> listaConfDetalle, List<Nombre> listaNombre) throws BusinessException{ try{ log.info(configuracion); boConfiguracion.modificar(configuracion); //**Proceso de ConfDetalles** //Obtenemos la lista de confDetalle de la bd List<ConfDetalle> listaConfDetalleBD = boConfDetalle.getPorIntItemConfiguracion(configuracion.getId().getIntItemConfiguracion()); //Los nuevos confDetalle que han ingresado (no tienen id) se graban List <ConfDetalle> listaConfDetalleAux = new ArrayList<ConfDetalle>(); for(ConfDetalle confDetalle : listaConfDetalle){ ConfDetalle confDetalleAux = confDetalle; if(confDetalleAux.getId().getIntItemConfiguracionDetalle()==null){ confDetalleAux.getId().setIntItemConfiguracion(configuracion.getId().getIntItemConfiguracion()); boConfDetalle.grabar(confDetalleAux); }else{ listaConfDetalleAux.add(confDetalle); } } listaConfDetalle = listaConfDetalleAux;//Obtenemos listaConfDetalle libre de confDetalles procesados //Los confDetalle que se han eliminado mediante interfaz pasan a estado Inactivo boolean existe = Boolean.FALSE; for(ConfDetalle confDetalleBD : listaConfDetalleBD){ //Tomamos en cuenta solo los que se encuentran en estado Activo if(confDetalleBD.getIntParaEstadoCod().equals(Constante.PARAM_T_ESTADOUNIVERSAL_ACTIVO)){ existe = Boolean.FALSE; for(ConfDetalle confDetalle : listaConfDetalle){ if(confDetalleBD.getId().getIntItemConfiguracionDetalle().equals(confDetalle.getId().getIntItemConfiguracionDetalle())){ existe = Boolean.TRUE; } } if(!existe){ confDetalleBD.setIntParaEstadoCod(Constante.PARAM_T_ESTADOUNIVERSAL_INACTIVO); boConfDetalle.modificar(confDetalleBD); } } } //**Proceso de Nombres** //Obtenemos la lista de nombre de la bd List<Nombre> listaNombreBD = boNombre.getPorIntItemConfiguracion(configuracion.getId().getIntItemConfiguracion()); //Los nuevos nombre que han ingresado (no tienen id) se graban List <Nombre> listaNombreAux = new ArrayList<Nombre>(); for(Nombre nombre : listaNombre){ if(nombre.getId().getIntItemNombre()==null){ nombre.getId().setIntItemConfiguracion(configuracion.getId().getIntItemConfiguracion()); boNombre.grabar(nombre); }else{ listaNombreAux.add(nombre); } } listaNombre = listaNombreAux;//Obtenemos listaNombre libre de nombres procesados //Los nombre que se han eliminado mediante interfaz pasan a estado Inactivo existe = Boolean.FALSE; for(Nombre nombreBD : listaNombreBD){ //Tomamos en cuenta solo los que se encuentran en estado Activo if(nombreBD.getIntParaEstadoCod().equals(Constante.PARAM_T_ESTADOUNIVERSAL_ACTIVO)){ existe = Boolean.FALSE; for(Nombre nombre : listaNombreAux){ if(nombreBD.getId().getIntItemNombre().equals(nombre.getId().getIntItemNombre())){ existe = Boolean.TRUE; } } if(!existe){ nombreBD.setIntParaEstadoCod(Constante.PARAM_T_ESTADOUNIVERSAL_INACTIVO); boNombre.modificar(nombreBD); } } } }catch(BusinessException e){ throw e; }catch(Exception e){ throw new BusinessException(e); } return configuracion; } public Configuracion modificarConfiguracion(Configuracion configuracion, List <ConfDetalle> listaConfDetalle, List<Nombre> listaNombre,ConfEstructura confEstructura) throws BusinessException{ try{ modificarConfiguracion(configuracion, listaConfDetalle, listaNombre); boConfEstructura.modificar(confEstructura); }catch(BusinessException e){ throw e; }catch(Exception e){ throw new BusinessException(e); } return configuracion; } }
Java
CL
0e84e117adaca1f1aad8623b4763ec76a650ddde738de022c2911d259d28d180
package com.branders.spawnermod.networking.packet; import java.util.function.Supplier; import com.branders.spawnermod.config.SpawnerModConfig; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent; /** * Config values needs to be synced from server to client * * @author Anders <Branders> Blomqvist */ public class SyncSpawnerConfig { private boolean disable_spawner_config; private boolean disable_count; private boolean disable_speed; private boolean disable_range; public SyncSpawnerConfig(boolean spawner_config, boolean count, boolean speed, boolean range) { this.disable_spawner_config = spawner_config; this.disable_count = count; this.disable_speed = speed; this.disable_range = range; } public static void encode(SyncSpawnerConfig msg, PacketBuffer buf) { buf.writeBoolean(msg.disable_spawner_config); buf.writeBoolean(msg.disable_count); buf.writeBoolean(msg.disable_speed); buf.writeBoolean(msg.disable_range); } public static SyncSpawnerConfig decode(PacketBuffer buf) { boolean spawner_config = buf.readBoolean(); boolean count = buf.readBoolean(); boolean speed = buf.readBoolean(); boolean range = buf.readBoolean(); return new SyncSpawnerConfig(spawner_config, count, speed, range); } public static void handle(SyncSpawnerConfig msg, Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { System.out.println("Recieved sync message from server. Setting correct values!"); // Sync config values SpawnerModConfig.sync(msg.disable_spawner_config, msg.disable_count, msg.disable_speed, msg.disable_range); }); } }
Java
CL
dbe8ad281ee1cbe0998b2a49c910733405cf6326624318cabcb33c64d8f06bb2
// // $Id: Piecen.java,v 1.4 2002/12/12 05:51:54 mdb Exp $ package com.samskivert.atlanti.data; import java.io.IOException; import java.io.DataInputStream; import java.io.DataOutputStream; import com.threerings.presents.dobj.DSet; /** * A piecen is a person and a piece all rolled into one! Players can play * a single piecen on a tile feature as a part of their turn and that * piecen then claims that feature and all of the features that are * connected to it forming a claim group. Once a group of features has * been claimed, no further piecens can be placed on the group. Note, * however, that two or more separately claimed feature groups can be * joined by placing a tile that connects the previously disconnected * groups together. In that case, the groups are merged into a single * claim group and all the piecens that were part of the disparate groups * become claimees in the new group. At scoring time, the player with the * most piecens in a group gets the points for the group. If two or more * players have equal numbers of piecens in a group, they each get the * points for the group. */ public class Piecen implements DSet.Entry { /** A color constant. */ public static final int RED = 0; /** A color constant. */ public static final int BLACK = 1; /** A color constant. */ public static final int BLUE = 2; /** A color constant. */ public static final int YELLOW = 3; /** A color constant. */ public static final int GREEN = 4; /** The owner of this piecen. */ public int owner; /** The x and y coordinates of the tile on which this piecen is * placed. */ public int x, y; /** The index in the tile's feature array of the feature on which this * piecen is placed. */ public int featureIndex; /** The claim group to which this piecen belongs. */ public int claimGroup; /** * Construts a piecen with the specified configuration. */ public Piecen (int owner, int x, int y, int featureIndex) { this.owner = owner; this.x = x; this.y = y; this.featureIndex = featureIndex; } /** * Constructs a blank piecen, suitable for unserialization. */ public Piecen () { } // documentation inherited public Comparable getKey () { // our key is our coordinates conflated into one integer return new Integer((x + 128) * 256 + y + 128); } // documentation inherited public void writeTo (DataOutputStream out) throws IOException { out.writeInt(owner); out.writeInt(x); out.writeInt(y); out.writeInt(featureIndex); } // documentation inherited public void readFrom (DataInputStream in) throws IOException { owner = in.readInt(); x = in.readInt(); y = in.readInt(); featureIndex = in.readInt(); } // documentation inherited public boolean equals (Object other) { // we will either be compared to a tile or to a piecen if (other == null) { return false; } else if (other instanceof AtlantiTile) { AtlantiTile tile = (AtlantiTile)other; return (tile.x == x) ? (y == tile.y) : false; } else if (other instanceof Piecen) { Piecen piecen = (Piecen)other; return (piecen.x == x) ? (y == piecen.y) : false; } else { // who knows... return false; } } /** * Generates a string representation of this piecen. */ public String toString () { return "[owner=" + owner + ", pos=" + x + "/" + y + ", feat=" + featureIndex + ", claim=" + claimGroup + "]"; } }
Java
CL
36c4391b927f6bbf234707e81151dea7a94c6f498e31ec09f4901369f19f46ca
package com.vanyne.reservation.domain.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.scripting.support.ResourceScriptSource; /** * @author : Yang Jian * @date : 2021/7/4 0004 17:22 */ @Configuration public class RedisConfiguration { @Autowired private RedisConnectionFactory factory; @Bean public RedisMessageListenerContainer redisMessageListenerContainer() { RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer(); redisMessageListenerContainer.setConnectionFactory(factory); return redisMessageListenerContainer; } @Bean public DefaultRedisScript<Long> defaultRedisScript() { DefaultRedisScript<Long> script = new DefaultRedisScript<>(); script.setResultType(Long.class); script.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis-lock.rua"))); return script; } }
Java
CL
71b3e370a3232712c90c34fe51a1fd7e8dbfb7bacd029ef459cf217f0ddd33fc
package com.generic.data.services.filter; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import com.generic.data.core.common.DataSourceContextHolder; /** * The {@link DataServiceFilter} makes sure that the dataSource context has been * decided and set based on DATA_SOURCE_NAME present in request headers - if the * user hasn't sent DATA_SOURCE_NAME it kicks the request out. * * @author praveen.kumar */ @Component @WebFilter(urlPatterns = { "/api-data*" }, filterName = "DataServiceFilter", asyncSupported = true) public class DataServiceFilter implements Filter { private static final String API_DATA = "api-data"; public static final String DATA_SOURCE_NAME = "X-DATASOURCE"; private static final String INVALID_HEADERS = "Invalid Headers"; private static final Logger LOGGER = LogManager.getLogger(DataServiceFilter.class); @Override public void destroy() { /** do nothing at shut down */ } @Override public void init(FilterConfig filterConfig) throws ServletException { /** initialization to be done by spring */ } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // We implicitly cast to HttpServletRequest, because if it's an instance of // another class we are // in trouble - so either way we want to throw a error 500 HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String url = getUrl(httpServletRequest); if(!API_DATA.contains(url)) { chain.doFilter(httpServletRequest, httpServletResponse); return; } String headers = getHeadersAsString(httpServletRequest); if (validHeaderIsPresent(httpServletRequest)) { LOGGER.printf(Level.TRACE, "url [%s] has valid headers", url); chain.doFilter(httpServletRequest, httpServletResponse); //got response //clear DataSourceContext resources/cache so that it won't impact memory. DataSourceContextHolder.clearDataSourceContext(); } else { LOGGER.printf(Level.TRACE, "For request URL %s%nHeaders present is invalid:%n%s", url, headers); LOGGER.printf(Level.TRACE, "No further action for request URL[%d] ", url); httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType(INVALID_HEADERS); } } /** * * @param request * @return */ private String getHeadersAsString(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); Enumeration<String> headers = request.getHeaderNames(); for (String header : Collections.list(headers)) { String value = request.getHeader(header); sb.append(String.format(" %s:%s%n", header, value)); } return sb.toString(); } /** * * @param httpServletRequest * @return */ private String getUrl(HttpServletRequest httpServletRequest) { String url = httpServletRequest.getRequestURL().toString(); String queryString = httpServletRequest.getQueryString(); String query = queryString == null ? "" : String.format("?%s", queryString); return String.format("%s%s", url, query); } /** * * @param request * @return */ private boolean validHeaderIsPresent(HttpServletRequest request) { String value = request.getHeader(DATA_SOURCE_NAME); return !StringUtils.isEmpty(value); } }
Java
CL
13e80ad5aac92943cd07c1a4c7470302e37bb0b21a0da6ed498770c0bd763823
package modularmachines.api.modules.tools; import modularmachines.api.modules.IModule; import modularmachines.api.modules.ITickable; public interface IModuleTool extends ITickable, IModule { }
Java
CL
05c40742df8c9d3a98a9c38d21265ac37fd24075f4de7be613f5400a4a8230ae
// Copyright (c) 2015-2023 Vladimir Schneider <vladimir.schneider@gmail.com> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.highlighter; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.intellij.openapi.util.io.FileUtil; import com.vladsch.md.nav.MdBundle; import com.vladsch.md.nav.highlighter.api.MdColorSettingsExtension; import com.vladsch.md.nav.settings.MdApplicationSettings; import com.vladsch.md.nav.settings.MdRenderingProfile; import icons.MdIcons; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.Icon; import java.io.InputStreamReader; import java.util.LinkedHashMap; import java.util.Map; public class MdColorSettingsPage implements ColorSettingsPage { private final static Logger LOG = Logger.getInstance(MdColorSettingsPage.class.getName()); protected static final ColorDescriptor[] EMPTY_COLOR_DESCRIPTOR_ARRAY = new ColorDescriptor[] { }; @NonNls public static final String SAMPLE_MARKDOWN_DOCUMENT_PATH = "/com/vladsch/md/nav/samples/sample-document.md"; protected static final LinkedHashMap<String, AttributesDescriptor> attributeDescriptors = new LinkedHashMap<>(); private static final AttributesDescriptor[] EMPTY_DESCRIPTORS = new AttributesDescriptor[0]; private void addTextAttributesKey(String name, TextAttributesKey attributesKey) { if (!attributeDescriptors.containsKey(name)) { attributeDescriptors.put(name, new AttributesDescriptor(name, attributesKey)); } } public MdColorSettingsPage() { MdHighlighterColors highlighterColors = MdHighlighterColors.getInstance(); addTextAttributesKey(MdBundle.message("colors.abbreviation"), highlighterColors.ABBREVIATION_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.abbreviation-short"), highlighterColors.ABBREVIATION_SHORT_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.abbreviation-expanded"), highlighterColors.ABBREVIATION_EXPANDED_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.abbreviated-text"), highlighterColors.ABBREVIATED_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.auto-link"), highlighterColors.AUTO_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.anchor"), highlighterColors.ANCHOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.anchor-id"), highlighterColors.ANCHOR_ID_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.emoji-marker"), highlighterColors.EMOJI_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.emoji-id"), highlighterColors.EMOJI_ID_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.block-quote"), highlighterColors.BLOCK_QUOTE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.bold"), highlighterColors.BOLD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.bold-marker"), highlighterColors.BOLD_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.underline"), highlighterColors.UNDERLINE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.underline-marker"), highlighterColors.UNDERLINE_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.superscript"), highlighterColors.SUPERSCRIPT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.superscript-marker"), highlighterColors.SUPERSCRIPT_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.subscript"), highlighterColors.SUBSCRIPT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.subscript-marker"), highlighterColors.SUBSCRIPT_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.bullet-list"), highlighterColors.BULLET_LIST_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.block-comment"), highlighterColors.BLOCK_COMMENT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.comment"), highlighterColors.COMMENT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.code"), highlighterColors.CODE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.code-marker"), highlighterColors.CODE_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.definition-marker"), highlighterColors.DEFINITION_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.definition-term"), highlighterColors.DEFINITION_TERM_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref"), highlighterColors.LINK_REF_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.atx-header"), highlighterColors.ATX_HEADER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.setext-header"), highlighterColors.SETEXT_HEADER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.header-text"), highlighterColors.HEADER_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.atx-header-marker"), highlighterColors.HEADER_ATX_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.setext-header-marker"), highlighterColors.HEADER_SETEXT_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.hrule"), highlighterColors.HRULE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.html-block"), highlighterColors.HTML_BLOCK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image"), highlighterColors.IMAGE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.inline-html"), highlighterColors.INLINE_HTML_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.html-entity"), highlighterColors.HTML_ENTITY_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.italic"), highlighterColors.ITALIC_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.italic-marker"), highlighterColors.ITALIC_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-front-matter-block"), highlighterColors.JEKYLL_FRONT_MATTER_BLOCK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-front-matter-marker"), highlighterColors.JEKYLL_FRONT_MATTER_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-tag-marker"), highlighterColors.JEKYLL_TAG_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-tag-name"), highlighterColors.JEKYLL_TAG_NAME_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-tag-parameters"), highlighterColors.JEKYLL_TAG_PARAMETERS_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.mail-link"), highlighterColors.MAIL_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.ordered-list"), highlighterColors.ORDERED_LIST_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.quote"), highlighterColors.QUOTE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.quoted-text"), highlighterColors.QUOTED_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.smarts"), highlighterColors.SMARTS_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.special-text"), highlighterColors.SPECIAL_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.special-text-marker"), highlighterColors.SPECIAL_TEXT_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.line-break-spaces"), highlighterColors.LINE_BREAK_SPACES_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.strikethrough"), highlighterColors.STRIKETHROUGH_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.strikethrough-marker"), highlighterColors.STRIKETHROUGH_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table"), highlighterColors.TABLE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-separator"), highlighterColors.TABLE_SEPARATOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-caption"), highlighterColors.TABLE_CAPTION_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-caption-marker"), highlighterColors.TABLE_CAPTION_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-cell-reven-ceven"), highlighterColors.TABLE_CELL_REVEN_CEVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-cell-reven-codd"), highlighterColors.TABLE_CELL_REVEN_CODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-cell-rodd-ceven"), highlighterColors.TABLE_CELL_RODD_CEVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-cell-rodd-codd"), highlighterColors.TABLE_CELL_RODD_CODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-row-even"), highlighterColors.TABLE_ROW_EVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-row-odd"), highlighterColors.TABLE_ROW_ODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-cell-reven-ceven"), highlighterColors.TABLE_HDR_CELL_REVEN_CEVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-cell-reven-codd"), highlighterColors.TABLE_HDR_CELL_REVEN_CODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-cell-rodd-ceven"), highlighterColors.TABLE_HDR_CELL_RODD_CEVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-cell-rodd-codd"), highlighterColors.TABLE_HDR_CELL_RODD_CODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-row-even"), highlighterColors.TABLE_HDR_ROW_EVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-row-odd"), highlighterColors.TABLE_HDR_ROW_ODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-column-even"), highlighterColors.TABLE_SEP_COLUMN_EVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-column-odd"), highlighterColors.TABLE_SEP_COLUMN_ODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.task-item-marker-done"), highlighterColors.TASK_DONE_ITEM_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.task-item-done-text"), highlighterColors.TASK_DONE_ITEM_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.task-item-marker"), highlighterColors.TASK_ITEM_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.text"), highlighterColors.TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-marker"), highlighterColors.WIKI_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-separator"), highlighterColors.WIKI_LINK_SEPARATOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-ref"), highlighterColors.WIKI_LINK_REF_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-ref-anchor"), highlighterColors.WIKI_LINK_REF_ANCHOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-ref-anchor-marker"), highlighterColors.WIKI_LINK_REF_ANCHOR_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-text"), highlighterColors.WIKI_LINK_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-image"), highlighterColors.REFERENCE_IMAGE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-link"), highlighterColors.REFERENCE_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference"), highlighterColors.REFERENCE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.verbatim"), highlighterColors.VERBATIM_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-image-reference"), highlighterColors.REFERENCE_IMAGE_REFERENCE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-image-text"), highlighterColors.REFERENCE_IMAGE_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.explicit-link"), highlighterColors.EXPLICIT_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-link-reference"), highlighterColors.REFERENCE_LINK_REFERENCE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-link-text"), highlighterColors.REFERENCE_LINK_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-address"), highlighterColors.REFERENCE_LINK_REF_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-title"), highlighterColors.REFERENCE_TITLE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-text"), highlighterColors.REFERENCE_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-anchor"), highlighterColors.REFERENCE_ANCHOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-anchor-marker"), highlighterColors.REFERENCE_ANCHOR_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.verbatim-marker"), highlighterColors.VERBATIM_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.verbatim-content"), highlighterColors.VERBATIM_CONTENT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.verbatim-lang"), highlighterColors.VERBATIM_LANG_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref-text"), highlighterColors.LINK_REF_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref-title"), highlighterColors.LINK_REF_TITLE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref-anchor"), highlighterColors.LINK_REF_ANCHOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref-anchor-marker"), highlighterColors.LINK_REF_ANCHOR_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image-link-ref"), highlighterColors.IMAGE_LINK_REF_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image-url-content"), highlighterColors.IMAGE_URL_CONTENT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image-link-ref-title"), highlighterColors.IMAGE_LINK_REF_TITLE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image-alt-text"), highlighterColors.IMAGE_ALT_TEXT_ATTR_KEY); for (MdColorSettingsExtension extension : MdColorSettingsExtension.EXTENSIONS.getValue()) { extension.addTextAttributes(this::addTextAttributesKey); } if (MdApplicationSettings.getInstance().getDebugSettings().getDebugCombinationColors()) { // add the combination colors for (TextAttributesKey key : MdSyntaxHighlighter.getMergedKeys()) { addTextAttributesKey(key.getExternalName(), key); } } } @Nullable public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() { return null; } /** * Get the set of {@link AttributesDescriptor} defining the configurable options in the dialog. * * @return {@link #attributeDescriptors} as an array. */ @NotNull public AttributesDescriptor[] getAttributeDescriptors() { return attributeDescriptors.values().toArray(EMPTY_DESCRIPTORS); } /** * Get the list of descriptors specifying the {@link com.intellij.openapi.editor.colors.ColorKey} instances for which colors are specified in the settings page. * * @return {@link #EMPTY_COLOR_DESCRIPTOR_ARRAY} */ @NotNull public ColorDescriptor[] getColorDescriptors() { return EMPTY_COLOR_DESCRIPTOR_ARRAY; } /** * Returns the text shown in the preview pane. If some elements need to be highlighted in the preview text which are not highlighted by the syntax highlighter, they need to be surrounded by XML-like tags, for example: <code>&lt;class&gt;MyClass&lt;/class&gt;</code>. The mapping between the names of the tags and the text attribute keys used for highlighting is defined by the {@link #getAdditionalHighlightingTagToDescriptorMap()} method. * * @return the text to show in the preview pane. */ @NonNls @NotNull public String getDemoText() { for (MdColorSettingsExtension extension : MdColorSettingsExtension.EXTENSIONS.getValue()) { String demoText = extension.getDemoText(); if (demoText != null) return demoText; } return loadSampleMarkdownDocument(SAMPLE_MARKDOWN_DOCUMENT_PATH); } /** * Get the title of the page, shown as text in the dialog tab. * * @return the name as defined by {@link MdBundle} */ @NotNull public String getDisplayName() { return MdBundle.message("multimarkdown.filetype.name"); } /** * Get the syntax highlighter which is used to highlight the text shown in the preview pane of the page. * * @return an instance of {@link MdSyntaxHighlighter} */ @NotNull public SyntaxHighlighter getHighlighter() { return new MdSyntaxHighlighter(MdRenderingProfile.getFOR_SAMPLE_DOC(), true, false); } /** * Get the icon for the page, shown in the dialog tab. * * @return {@link MdIcons.Document#FILE} */ @Nullable public Icon getIcon() { return MdIcons.getDocumentIcon(); } /** * Load the sample text to be displayed in the preview pane. */ private static String loadSampleMarkdownDocument(String path) { try { return FileUtil.loadTextAndClose(new InputStreamReader(MdColorSettingsPage.class.getResourceAsStream(path))); } catch (Exception e) { LOG.error("Failed loading sample Markdown document", e); } return MdBundle.message("colors.sample-loading-error"); } }
Java
CL
dd6c384d887e3a5a918fc0e52ba9b13f2a5e448150bfe67d46b64d91b431a514
package com.lib.network; import android.annotation.SuppressLint; import android.util.Log; import com.lib.network.factory.NetWorkConverterFactory; import com.lib.network.factory.NobodyConverterFactory; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; /** * 网络请求管理类 */ public abstract class NetworkManager<T> { private static final String TAG = NetworkManager.class.getSimpleName(); private static final long CONNECT_TIME_OUT = 10; private static final long READ_TIME_OUT = 10; private static final long WRITE_TIME_OUT = 10; private static SSLSocketFactory socketFactory; private static X509TrustManager trustManager; protected T createNetworkApi(String baseURL) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseURL) .addConverterFactory(NetWorkConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(createOkHttpClient()) .build(); return retrofit.create(getApiClass()); } /** * Base Url */ // public static Retrofit getRetrofit() { // if (baseUrlRetrofit == null) { // synchronized (OkHttpClientProvider.class) { // if (baseUrlRetrofit == null) { // baseUrlRetrofit = new Retrofit.Builder() // .baseUrl(RuntimeURLFactory.getBaseURL(BaseCleanApplication.getApplication())) // .addConverterFactory(NobodyConverterFactory.create()) // .addConverterFactory(NetWorkConverterFactory.create()) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .client(createOkHttpClient()) // .build(); // } // } // } // return baseUrlRetrofit; // } private static OkHttpClient createOkHttpClient() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); SSLSocketFactory socketFactory = createSSLSocketFactory(); if (socketFactory != null) { //忽略https证书验证 builder.sslSocketFactory(socketFactory, trustManager); builder.hostnameVerifier((hostname, session) -> true); } builder.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS); builder.readTimeout(READ_TIME_OUT, TimeUnit.SECONDS); builder.writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS); builder.addInterceptor(createLogInterceptor()); //禁止重新连接 builder.retryOnConnectionFailure(false); return builder.build(); } @SuppressLint("TrustAllX509TrustManager") private static SSLSocketFactory createSSLSocketFactory() { if (socketFactory == null) { trustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom()); socketFactory = sslContext.getSocketFactory(); } catch (Exception e) { trustManager = null; Log.e(TAG, "NetworkManager createSSLSocketFactory ", e); } } return socketFactory; } private static Interceptor createLogInterceptor(){ return new HttpLoggingInterceptor(message -> Log.i(TAG, message)) .setLevel(HttpLoggingInterceptor.Level.BODY); } public abstract void reset(); protected abstract Class<T> getApiClass(); }
Java
CL
ae5f40d5c9f32689e671aa98b1b9240d102d63880ecfac5f5e2a17cb0c91424d
package com.ss.week1.day1.day1_assignment; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; // Data abstraction is the process of hiding certain details and showing only essential information to the user. // Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter). // The abstract keyword is a non-access modifier, used for classes and methods: // Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). // Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from). @SpringBootApplication public class abstractionExample { // Abstract class public static abstract class Animal { // Abstract method (does not have a body) public abstract void animalSound(); // Regular method public void sleep() { System.out.println("Zzz"); } } // Subclass (inherit from Animal) static class Pig extends Animal { public void animalSound() { // The body of animalSound() is provided here System.out.println("The pig says: oink oink"); } } public static void main(String[] args) { SpringApplication.run(Day1AssignmentApplication.class, args); System.out.println("Welcome"); Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } }
Java
CL
8f883c7b2643afdb193374d36c57992d2e834c2a433ea4c40f5415296807334b
package com.maryanto.dimas.example.controllers; import com.maryanto.dimas.example.model.Request; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.springframework.http.ResponseEntity.ok; @RefreshScope @RestController @RequestMapping("/api") public class ConfigurationApi { @Autowired private Request request; @GetMapping("/configuration") public ResponseEntity getConfiguration() { return ok().body(request); } }
Java
CL
9346c7bf6e5cca40d2353ea54fac4ecaded9657a3f812f98ac7f56f5aecdf47f
package ie.cit.afd.web; import ie.cit.afd.dao.NotificationDetailsRepository; import ie.cit.afd.models.NotificationDetails; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.List; import org.hamcrest.CoreMatchers; import org.hamcrest.Description; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.ui.ExtendedModelMap; public class NotificationDetailsTest { private NotificationDetailsRepository repo; private NotificationDetailsController tested; @Before public void setup() { repo = mock(NotificationDetailsRepository.class); tested = new NotificationDetailsController(repo); } @Test public void testGetAll() { List<NotificationDetails> all = tested.getAllNotificationDetailsItems(); assertThat(all, notNullValue()); verify(repo).getAll(); } @Test public void testGetAllNotificaitonTypeItems() throws Exception { ExtendedModelMap model = new ExtendedModelMap(); String view = tested.getAll(model); assertThat(view, CoreMatchers.equalTo("notificationdetails")); assertThat(model.get("notificationdetails"), notNullValue()); verify(repo).getAll(); } @Test public void testCreate() { tested.create( " NF01", "AbbeyBreaffy Nursing Home", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ac justo volutpat, interdum"); Mockito.verify(repo).insert( Matchers.argThat(new ArgumentMatcher<NotificationDetails>() { @Override public boolean matches(Object argument) { return ((NotificationDetails) argument) .getOrganisationdetailsID().equals( "AbbeyBreaffy Nursing Home"); } @Override public void describeTo(Description description) { description .appendText("expected: some AbbeyBreaffy Nursing Home"); } })); } }
Java
CL
cc86560dbee717e3160cc5fa092b4745c54494a473b6e7e604375ed99981d7a0
package com.reporting.mocks.persistence.mongo; import com.reporting.mocks.model.DataMarkerType; import com.reporting.mocks.model.MarketEnv; import com.reporting.mocks.model.PricingGroup; import com.reporting.mocks.model.id.MarketEnvId; import com.reporting.mocks.persistence.IMarketStore; import java.util.Collection; import java.util.UUID; public class MongoMarketStore implements IMarketStore { protected PricingGroup pricingGroup; protected MarketEnvRepository marketEnvRepository; public MongoMarketStore(PricingGroup pricingGroup, MarketEnvRepository marketEnvRepository) { this.pricingGroup = pricingGroup; this.marketEnvRepository = marketEnvRepository; } @Override public MarketEnv create(DataMarkerType type) { MarketEnv marketEnv = new MarketEnv(this.pricingGroup, type); MarketEnv storedEnv = this.marketEnvRepository.save(marketEnv); return storedEnv; } @Override public MarketEnv create(DataMarkerType type, int dayAdvance) { MarketEnv marketEnv = new MarketEnv(this.pricingGroup, type, dayAdvance); MarketEnv storedEnv = this.marketEnvRepository.save(marketEnv); return storedEnv; } @Override public MarketEnv get(UUID id) { return this.marketEnvRepository.getMarketEnvByMarketEnvId(new MarketEnvId(this.pricingGroup.getName(), id)); } @Override public UUID getStoreId() { return null; } @Override public PricingGroup getPricingGroup() { return this.pricingGroup; } @Override public Collection<MarketEnv> getAll() { return this.marketEnvRepository.getMarketEnvsByPricingGroup(this.pricingGroup); } }
Java
CL
34f4b4d1fee361f24fc137c6e86f30e0957a0d91e7f2a7932b4166ecf9ebbd7d
package io.github.liias.monkey.ide.conf; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.Nullable; import java.util.Objects; @State( name = "MonkeyOptions", // specifies the name of the state (name of the root tag in XML). storages = @Storage("monkey.options.xml") ) public class MonkeyOptions implements PersistentStateComponent<MonkeyOptions> { public String keyPath; public MonkeyOptions() { } // Gets options on application level public static MonkeyOptions getInstance() { return ServiceManager.getService(MonkeyOptions.class); } @Nullable @Override public MonkeyOptions getState() { return this; } @Override public void loadState(MonkeyOptions state) { XmlSerializerUtil.copyBean(state, this); } public String getKeyPath() { return keyPath; } public void setKeyPath(String keyPath) { this.keyPath = keyPath; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MonkeyOptions that = (MonkeyOptions) o; return Objects.equals(getKeyPath(), that.getKeyPath()); } @Override public int hashCode() { return Objects.hash(getKeyPath()); } }
Java
CL
7fffe8f31ebd3ded2907b565b71835f9cd12b949ec63d937f3a40579b13e57a4
package com.onethousandprojects.appoeira.serverStuff.methods; import android.content.Intent; import android.graphics.Bitmap; import android.widget.Toast; import androidx.annotation.NonNull; import com.onethousandprojects.appoeira.R; import com.onethousandprojects.appoeira.commonThings.CommonMethods; import com.onethousandprojects.appoeira.commonThings.Constants; import com.onethousandprojects.appoeira.commonThings.SharedPreferencesManager; import com.onethousandprojects.appoeira.eventDetailView.EventDetailActivity; import com.onethousandprojects.appoeira.eventModificationView.EventModificationActivity; import com.onethousandprojects.appoeira.eventModificationView.fragments.EventMembersConvidedFragment; import com.onethousandprojects.appoeira.eventModificationView.fragments.EventMembersInvitedFragment; import com.onethousandprojects.appoeira.serverStuff.deleteObject.ClientDeleteRequest; import com.onethousandprojects.appoeira.serverStuff.deleteObject.ServerDeleteResponse; import com.onethousandprojects.appoeira.serverStuff.eventDetailMore.ClientEventDetailMoreRequest; import com.onethousandprojects.appoeira.serverStuff.eventDetailMore.ServerEventDetailMoreResponse; import com.onethousandprojects.appoeira.serverStuff.eventModification.ClientEventModificationRequest; import com.onethousandprojects.appoeira.serverStuff.eventModification.ServerEventModificationResponse; import com.onethousandprojects.appoeira.serverStuff.serverAndClient.Client; import com.onethousandprojects.appoeira.serverStuff.serverAndClient.Server; import com.onethousandprojects.appoeira.serverStuff.search.ClientSearchRequest; import com.onethousandprojects.appoeira.serverStuff.search.ServerSearchResponse; import java.io.IOException; import java.util.List; import java.util.Objects; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class EventModificationServer { private ServerEventModificationResponse serverEventModificationResponse; private List<ServerEventDetailMoreResponse> serverEventDetailMoreResponse; private ServerSearchResponse serverSearchResponse; private ServerDeleteResponse serverDeleteResponse; public boolean createdFragment = false; public boolean createdConvidedFragment = false; Client Client; public Server Server; public EventModificationServer() { super(); Client = Client.getInstance(); Server = Client.getServer(); } public void sendModificationsToServer(EventModificationActivity EventModificationActivity, List<Integer> owners, String name, String description, String date, List<Integer> invited, Double latitude, Double longitude, String phone, List<Integer> convided, String key, Integer platform, Bitmap imageBitmap, Integer eventId) throws IOException { ClientEventModificationRequest clientEventModificationRequest = new ClientEventModificationRequest(SharedPreferencesManager.getStringValue(Constants.PERF_TOKEN), eventId, owners, name, description, date, invited, latitude, longitude, phone, convided, key, platform); Call<ServerEventModificationResponse> call = Server.post_event_update(clientEventModificationRequest, CommonMethods.fromBitmapToFile(EventModificationActivity, imageBitmap, "event", "avatar", eventId, 0)); call.enqueue(new Callback<ServerEventModificationResponse>() { @Override public void onResponse(@NonNull Call<ServerEventModificationResponse> call, @NonNull Response<ServerEventModificationResponse> response) { if (response.isSuccessful()){ serverEventModificationResponse = response.body(); Intent toEventDetailActivity = new Intent(EventModificationActivity, EventDetailActivity.class); toEventDetailActivity.putExtra("eventId", serverEventModificationResponse.getId()); toEventDetailActivity.putExtra("ownerRank", CommonMethods.fromRankIdToRankName(SharedPreferencesManager.getIntegerValue(Constants.RANK), EventModificationActivity)); toEventDetailActivity.putExtra("owner", SharedPreferencesManager.getStringValue(Constants.APELHIDO)); EventModificationActivity.startActivity(toEventDetailActivity); EventModificationActivity.finish(); } else { Toast.makeText(EventModificationActivity,R.string.failed, Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(@NonNull Call<ServerEventModificationResponse> call, @NonNull Throwable t) { Toast.makeText(EventModificationActivity, t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } public ServerEventModificationResponse getServerEventModificationResponse() { return serverEventModificationResponse; } public void sendUserSearchToServer(EventModificationActivity EventModificationActivity, String search, boolean invConv) { ClientSearchRequest clientSearchRequest = new ClientSearchRequest(SharedPreferencesManager.getStringValue(Constants.PERF_TOKEN), search, "10000"); Call<ServerSearchResponse> call = Server.post_search(clientSearchRequest); call.enqueue(new Callback<ServerSearchResponse>() { @Override public void onResponse(@NonNull Call<ServerSearchResponse> call, @NonNull Response<ServerSearchResponse> response) { if (response.isSuccessful()){ serverSearchResponse = response.body(); if (!invConv) { if (!createdFragment) { createdFragment = true; EventModificationActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListLayout, new EventMembersInvitedFragment(), "UserListFragment").commit(); } else { EventModificationActivity.getSupportFragmentManager().beginTransaction().remove(Objects.requireNonNull(EventModificationActivity.getSupportFragmentManager().findFragmentByTag("UserListFragment"))).commit(); if (serverSearchResponse.getUserResponses().get(0).getId() != null) { EventModificationActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListLayout, new EventMembersInvitedFragment(), "UserListFragment").commit(); } else { createdFragment = false; } } } else { if (!createdConvidedFragment) { createdConvidedFragment = true; EventModificationActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListConvidedLayout, new EventMembersConvidedFragment(), "ConvidedListFragment").commit(); } else { EventModificationActivity.getSupportFragmentManager().beginTransaction().remove(Objects.requireNonNull(EventModificationActivity.getSupportFragmentManager().findFragmentByTag("ConvidedListFragment"))).commit(); if (serverSearchResponse.getUserResponses().size() > 0) { EventModificationActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListConvidedLayout, new EventMembersConvidedFragment(), "ConvidedListFragment").commit(); } else { createdConvidedFragment = false; } } } } else { Toast.makeText(EventModificationActivity,R.string.failed, Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(@NonNull Call<ServerSearchResponse> call, @NonNull Throwable t) { Toast.makeText(EventModificationActivity, t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } public ServerSearchResponse getSearchResponse() { return serverSearchResponse; } public void getEventDetailMore(EventModificationActivity EventModificationActivity, Integer groupId) { ClientEventDetailMoreRequest clientEventDetailMoreRequest = new ClientEventDetailMoreRequest(SharedPreferencesManager.getStringValue(Constants.PERF_TOKEN), groupId); Call<List<ServerEventDetailMoreResponse>> call = Server.post_event_detail_more(clientEventDetailMoreRequest); call.enqueue(new Callback<List<ServerEventDetailMoreResponse>>() { @Override public void onResponse(@NonNull Call<List<ServerEventDetailMoreResponse>> call, @NonNull Response<List<ServerEventDetailMoreResponse>> response) { if (response.isSuccessful()){ serverEventDetailMoreResponse = response.body(); if (!createdFragment) { createdFragment = true; assert serverEventDetailMoreResponse != null; for (int i = 0; i < serverEventDetailMoreResponse.size(); i++) { if (serverEventDetailMoreResponse.get(i).getUserId().equals(SharedPreferencesManager.getIntegerValue(Constants.ID))) { serverEventDetailMoreResponse.remove(i); break; } } for (int i = 0; i < serverEventDetailMoreResponse.size(); i++) { if (serverEventDetailMoreResponse.get(i).getUserGroupRole().equals(Integer.toString(2))) { EventModificationActivity.invitedMembers.add(serverEventDetailMoreResponse.get(i).getUserId()); } } EventModificationActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListLayout, new EventMembersInvitedFragment(), "UserListFragment").commit(); } else { EventModificationActivity.getSupportFragmentManager().beginTransaction().remove(Objects.requireNonNull(EventModificationActivity.getSupportFragmentManager().findFragmentByTag("UserListFragment"))).commit(); if (serverSearchResponse.getUserResponses().get(0).getId() != null) { EventModificationActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListLayout, new EventMembersInvitedFragment(), "UserListFragment").commit(); } else { createdFragment = false; } } if (!createdConvidedFragment) { createdConvidedFragment = true; assert serverEventDetailMoreResponse != null; for (int i = 0; i < serverEventDetailMoreResponse.size(); i++) { if (serverEventDetailMoreResponse.get(i).getUserId().equals(SharedPreferencesManager.getIntegerValue(Constants.ID))) { serverEventDetailMoreResponse.remove(i); break; } } for (int i = 0; i < serverEventDetailMoreResponse.size(); i++) { if (serverEventDetailMoreResponse.get(i).getUserGroupRole().equals(Integer.toString(3))) { EventModificationActivity.convidedMembers.add(serverEventDetailMoreResponse.get(i).getUserId()); } } EventModificationActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListConvidedLayout, new EventMembersConvidedFragment(), "ConvidedListFragment").commit(); } else { EventModificationActivity.getSupportFragmentManager().beginTransaction().remove(Objects.requireNonNull(EventModificationActivity.getSupportFragmentManager().findFragmentByTag("ConvidedListFragment"))).commit(); if (serverSearchResponse.getUserResponses().get(0).getId() != null) { EventModificationActivity.getSupportFragmentManager().beginTransaction().add(R.id.ListConvidedLayout, new EventMembersConvidedFragment(), "ConvidedListFragment").commit(); } else { createdConvidedFragment = false; } } } else { Toast.makeText(EventModificationActivity, R.string.failed, Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(@NonNull Call<List<ServerEventDetailMoreResponse>> call, @NonNull Throwable t) { Toast.makeText(EventModificationActivity, t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } public List<ServerEventDetailMoreResponse> getMyResponse() { return serverEventDetailMoreResponse; } public void deleteEvent(EventModificationActivity EventModificationActivity, Integer eventId) { ClientDeleteRequest clientDeleteRequest = new ClientDeleteRequest(SharedPreferencesManager.getStringValue(Constants.PERF_TOKEN), eventId, SharedPreferencesManager.getIntegerValue(Constants.ID)); Call<ServerDeleteResponse> call = Server.post_event_delete(clientDeleteRequest); call.enqueue(new Callback<ServerDeleteResponse>() { @Override public void onResponse(@NonNull Call<ServerDeleteResponse> call, @NonNull Response<ServerDeleteResponse> response) { if (response.isSuccessful()){ serverDeleteResponse = response.body(); assert serverDeleteResponse != null; if (serverDeleteResponse.isOk()) { Toast.makeText(EventModificationActivity, R.string.eventDeleted, Toast.LENGTH_SHORT).show(); EventModificationActivity.toEventList(); } else { Toast.makeText(EventModificationActivity, R.string.failed, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(EventModificationActivity, R.string.failed, Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(@NonNull Call<ServerDeleteResponse> call, @NonNull Throwable t) { Toast.makeText(EventModificationActivity, t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }
Java
CL
89c132a57e5d94efab2d3533e9c9ce4015b7ef8e83805f52790c47d0c6edec55
package com.pami; import java.lang.reflect.Method; import android.app.Application; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.util.LruCache; import android.view.Display; import android.view.WindowManager; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.pami.activity.BaseActivity; import com.pami.utils.MLog; import com.pami.utils.ScreenManager; public class PMApplication extends Application { /**存储图片*/ private LruCache<String, Bitmap> mImageLoaderCache = null; public boolean isDown; public boolean isRun; /** * 是否存在 NavigationBar true 表示存在 false 表示不存在 */ public boolean isHasNavigationBar; /** * 全局的volley请求队列 */ private RequestQueue requestQueue; /** * 全局LApplication唯一实例 */ private static PMApplication instance; /** * 全局的是否打开DEBUG模式<br /> * 默认为true */ private boolean dev_mode = true; /** * 全局屏幕宽度 */ private int mDiaplayWidth; /** * 全局屏幕高度 */ private int mDiaplayHeight; /** * 上传log的地址 */ private String exceptionUrl = null; @Override public void onCreate() { super.onCreate(); instance = this; this.requestQueue = Volley.newRequestQueue(getApplicationContext()); isHasNavigationBar = checkDeviceHasNavigationBar(this); int maxMemory = (int) Runtime.getRuntime().maxMemory(); int cacheMemory = maxMemory / 6; MLog.e("yyg", "------应用程序【"+getPackageName()+"】最大使用内存数----->"+(maxMemory/1024)+"KB 分配了:"+(cacheMemory/1024)+"KB 内存用于缓存图片"); mImageLoaderCache = new LruCache<String, Bitmap>(cacheMemory){ @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); } }; } /** * 获取请求队列 * @return */ public RequestQueue getRequestQueue(){ return requestQueue; } /** * 撤销请求 * @param requestTag */ public void clearRequest(String requestTag){ if(requestQueue == null){ return; } requestQueue.cancelAll(requestTag); } /** * 获取一个LApplication的实例 * * @return */ public static synchronized PMApplication getInstance() { if (instance == null) { instance = new PMApplication(); } return instance; } /** * 设置一个LApplication的实例 * * @param app */ public static void setLApplication(PMApplication app) { instance = app; } /** * 获取屏幕宽度 * * @return */ public int getDiaplayWidth() { if (mDiaplayWidth <= 0) { computeDiaplayWidthAndHeight(); } return mDiaplayWidth; } /** * 获取屏幕高度 * * @return */ public int getDiaplayHeight() { if (mDiaplayHeight <= 0) { computeDiaplayWidthAndHeight(); } return mDiaplayHeight; } /** * 初始化屏幕的宽和高 */ private void computeDiaplayWidthAndHeight() { WindowManager mWindowManager = ScreenManager.getScreenManager().currentActivity().getWindowManager(); Display display = mWindowManager.getDefaultDisplay(); mDiaplayWidth = display.getWidth(); mDiaplayHeight = display.getHeight(); } /** * 获取是否启用Debug模式 * * @return */ public boolean getDevMode() { return dev_mode; } /** * 设置是否启用Debug模式 * * @param openDebugMode */ public void setDevMode(boolean openDebugMode) { this.dev_mode = openDebugMode; } /** * 获取存放异常的路径 * @return */ public String getExceptionUrl() { return exceptionUrl; } /** * 设置存放异常的路径 * @param exceptionUrl */ public void setExceptionUrl(String exceptionUrl) { this.exceptionUrl = exceptionUrl; } /** * 获取屏幕是否存在 NavigationBar * @param context * @return */ private boolean checkDeviceHasNavigationBar(Context context) { boolean hasNavigationBar = false; Resources rs = context.getResources(); int id = rs.getIdentifier("config_showNavigationBar", "bool", "android"); if (id > 0) { hasNavigationBar = rs.getBoolean(id); } try { Class systemPropertiesClass = Class.forName("android.os.SystemProperties"); Method m = systemPropertiesClass.getMethod("get", String.class); String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys"); if ("1".equals(navBarOverride)) { hasNavigationBar = false; } else if ("0".equals(navBarOverride)) { hasNavigationBar = true; } } catch (Exception e) { e.printStackTrace(); } return hasNavigationBar; } public LruCache<String, Bitmap> getmImageLoaderCache() { return mImageLoaderCache; } public void setmImageLoaderCache(LruCache<String, Bitmap> mImageLoaderCache) { this.mImageLoaderCache = mImageLoaderCache; } }
Java
CL
4943db373900a8540e3381c76c92c254f0ae1b8ee0dd69364335ce744740bc1e
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.submarine.server.submitter.k8s; import java.io.FileReader; import java.util.HashMap; import java.util.Map; import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; import io.kubernetes.client.ApiClient; import io.kubernetes.client.ApiException; import io.kubernetes.client.Configuration; import io.kubernetes.client.apis.CustomObjectsApi; import io.kubernetes.client.models.V1DeleteOptions; import io.kubernetes.client.models.V1DeleteOptionsBuilder; import io.kubernetes.client.util.ClientBuilder; import io.kubernetes.client.util.KubeConfig; import org.apache.submarine.commons.utils.SubmarineConfiguration; import org.apache.submarine.commons.utils.SubmarineConfVars; import org.apache.submarine.server.api.JobSubmitter; import org.apache.submarine.server.api.exception.UnsupportedJobTypeException; import org.apache.submarine.server.api.job.Job; import org.apache.submarine.server.api.spec.JobSpec; import org.apache.submarine.server.submitter.k8s.model.CustomResourceJob; import org.apache.submarine.server.submitter.k8s.model.CustomResourceJobList; import org.apache.submarine.server.submitter.k8s.model.MLJob; import org.apache.submarine.server.submitter.k8s.parser.JobSpecParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * JobSubmitter for Kubernetes Cluster. */ public class K8sJobSubmitter implements JobSubmitter { private final Logger LOG = LoggerFactory.getLogger(K8sJobSubmitter.class); private String confPath; /** * Key: kind of CRD, such as TFJob/PyTorchJob * Value: the CRD api with version */ private Map<String, String> supportedCRDMap; public K8sJobSubmitter() { } public K8sJobSubmitter(String confPath) { this.confPath = confPath; } @Override public void initialize(SubmarineConfiguration conf) { supportedCRDMap = new HashMap<>(); supportedCRDMap.put("TFJob", "tfjobs"); if (confPath == null || confPath.trim().isEmpty()) { confPath = conf.getString(SubmarineConfVars.ConfVars.SUBMARINE_K8S_KUBE_CONFIG); } loadClientConfiguration(confPath); } private void loadClientConfiguration(String path) { try { KubeConfig config = KubeConfig.loadKubeConfig(new FileReader(path)); ApiClient client = ClientBuilder.kubeconfig(config).build(); Configuration.setDefaultApiClient(client); } catch (Exception e){ LOG.error("Load the K8s client conf failed: " + e.getMessage(), e); } } @Override public String getSubmitterType() { return "k8s"; } @Override public Job submitJob(JobSpec jobSpec) throws UnsupportedJobTypeException { if (!supportedCRDMap.containsKey(jobSpec.getSubmitterSpec().getKind())) { throw new UnsupportedJobTypeException(); } Job job = new Job(); job.setName(jobSpec.getName()); createJob(JobSpecParser.parseTFJob(jobSpec)); return job; } @VisibleForTesting void createJob(MLJob job) { try { CustomObjectsApi api = new CustomObjectsApi(); api.createNamespacedCustomObject(job.getGroup(), job.getVersion(), job.getMetadata().getNamespace(), supportedCRDMap.get(job.getKind()), job, "true"); } catch (ApiException e) { LOG.error("Create {} job: " + e.getMessage(), e); } } @VisibleForTesting CustomResourceJob createCustomJob(K8sJobRequest request) { try { CustomObjectsApi api = new CustomObjectsApi(); K8sJobRequest.Path path = request.getPath(); Object o = api.createNamespacedCustomObject(path.getGroup(), path.getApiVersion(), path.getNamespace(), path.getPlural(), request.getBody(), "true"); Gson gson = new Gson(); return gson.fromJson(gson.toJson(o), CustomResourceJob.class); } catch (ApiException ae) { LOG.error("Create CRD job: " + ae.getMessage(), ae); } return null; } @VisibleForTesting CustomResourceJob getCustomResourceJob(K8sJobRequest request) { try { CustomObjectsApi api = new CustomObjectsApi(); K8sJobRequest.Path path = request.getPath(); Object o = api.getNamespacedCustomObject(path.getGroup(), path.getApiVersion(), path.getNamespace(), path.getPlural(), request.getJobName()); Gson gson = new Gson(); return gson.fromJson(gson.toJson(o), CustomResourceJob.class); } catch (ApiException ae) { LOG.error("Get CRD job: " + ae.getMessage(), ae); } return null; } @VisibleForTesting CustomResourceJob deleteCustomResourceJob(K8sJobRequest request) { try { CustomObjectsApi api = new CustomObjectsApi(); K8sJobRequest.Path path = request.getPath(); V1DeleteOptions body = new V1DeleteOptionsBuilder().withApiVersion(path.getApiVersion()).build(); Object o = api.deleteNamespacedCustomObject(path.getGroup(), path.getApiVersion(), path.getNamespace(), path.getPlural(), request.getJobName(), body, null, null, null); Gson gson = new Gson(); return gson.fromJson(gson.toJson(o), CustomResourceJob.class); } catch (ApiException ae) { LOG.error("Delete CRD job: " + ae.getMessage(), ae); } return null; } @VisibleForTesting CustomResourceJobList listCustomResourceJobs(K8sJobRequest request) { try { CustomObjectsApi api = new CustomObjectsApi(); K8sJobRequest.Path path = request.getPath(); Object o = api.listNamespacedCustomObject(path.getGroup(), path.getApiVersion(), path.getNamespace(), path.getPlural(), "true", null, null, null, null, null); Gson gson = new Gson(); return gson.fromJson(gson.toJson(o), CustomResourceJobList.class); } catch (ApiException ae) { LOG.error("List CRD jobs: " + ae.getMessage(), ae); } return null; } }
Java
CL
99eeee5cbffc16516494c66e71311ab32ca44f727b363ca34a26dc4f7fa7b51d
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.gui; import proguard.*; import javax.swing.*; /** * This <code>ListPanel</code> allows the user to add, edit, move, and remove * KeepClassSpecification entries in a list. * * @author Eric Lafortune */ final class KeepSpecificationsPanel extends ClassSpecificationsPanel { private final boolean markClasses; private final boolean markConditionally; private final boolean markDescriptorClasses; private final boolean allowShrinking; private final boolean allowOptimization; private final boolean allowObfuscation; public KeepSpecificationsPanel(JFrame owner, boolean markClasses, boolean markConditionally, boolean markDescriptorClasses, boolean allowShrinking, boolean allowOptimization, boolean allowObfuscation) { super(owner, true); this.markClasses = markClasses; this.markConditionally = markConditionally; this.markDescriptorClasses = markDescriptorClasses; this.allowShrinking = allowShrinking; this.allowOptimization = allowOptimization; this.allowObfuscation = allowObfuscation; } // Factory methods for ClassSpecificationsPanel. protected ClassSpecification createClassSpecification() { return new KeepClassSpecification(markClasses, markConditionally, markDescriptorClasses, allowShrinking, allowOptimization, allowObfuscation); } protected void setClassSpecification(ClassSpecification classSpecification) { classSpecificationDialog.setKeepSpecification((KeepClassSpecification)classSpecification); } protected ClassSpecification getClassSpecification() { return classSpecificationDialog.getKeepSpecification(); } }
Java
CL
14459f75d6dfe557274a3a5d43f287d10f393545634e7bd3cdf0eee8cefc03bd
package com.quanroon.ysq.testtransaction; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.producer.LocalTransactionState; import org.apache.rocketmq.client.producer.TransactionListener; import org.apache.rocketmq.client.producer.TransactionMQProducer; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.common.message.MessageExt; import java.util.UUID; /** * @author quanroong.ysq * @version 1.0.0 * @description 事务消息:即在发送消息时,先发送预处理消息到broker中,等到本地事务提交完成后,在提交消息确认发送 * @createtime 2020/7/25 15:09 */ public class TransactionProducer { public static void main(String[] args) throws MQClientException { TransactionMQProducer transactionMQProducer = new TransactionMQProducer("transaction-producer"); transactionMQProducer.setNamesrvAddr("127.0.0.1:9876"); //定义事务的监听 transactionMQProducer.setTransactionListener(new TransactionListener(){ //执行本地事务,并发送预处理消息 @Override public LocalTransactionState executeLocalTransaction(Message message, Object o) { //这个事务ID是每条消息中自动生成的,o为我们自定义的事务ID String transactionId = message.getTransactionId(); String defineId = o.toString(); System.out.println("执行事务:"+transactionId + "=======" + defineId); //执行业务逻辑,如果失败,则回滚消息事务,如果成功,则提交事务 //省略业务代码.... return LocalTransactionState.COMMIT_MESSAGE; } //回查机制,当executeLocalTransaction方法中返回的状态未知或未返回状态时,默认一分钟后,broker将检查本地事务 @Override public LocalTransactionState checkLocalTransaction(MessageExt messageExt) { //获取事务ID 这个事务ID是每条消息中自动生成的 String transactionId = messageExt.getTransactionId(); System.out.println("进行回查:"+transactionId); //根据这个事务ID进行本地事务执行情况, //查询方式省略... return LocalTransactionState.COMMIT_MESSAGE; } }); transactionMQProducer.start(); //本次发送的消息对应唯一的事务ID,这个跟业务挂钩。 String transactionId = UUID.randomUUID().toString(); //创建消息,并发送消息 for (String type : new String[]{"你好","晚安啊","走起,我们一起发财"}){ String body = type +" "+System.currentTimeMillis(); Message msg = new Message("TopicOrder", body.getBytes()); //msg:消息体 arg:本地事务ID,用于回查确认消息 transactionMQProducer.sendMessageInTransaction(msg,transactionId); } } }
Java
CL
8a55218c3df2ed80d2ba66234e347a29b4f5ba0f4e6729d1ca14e88a3461bc00
/* Copyright 2018 Softeam Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.qrapids.backlog.openproject.service.data; public class QualityRequirement { private String issue_summary; private String issue_description; private String issue_type; private String project_id; private String decision_rationale; public String getIssue_summary() { return issue_summary; } public void setIssue_summary(String issue_summary) { this.issue_summary = issue_summary; } public String getIssue_description() { return issue_description; } public void setIssue_description(String issue_description) { this.issue_description = issue_description; } public String getIssue_type() { return issue_type; } public void setIssue_type(String issue_type) { this.issue_type = issue_type; } public String getProject_id() { return project_id; } public void setProject_id(String project_id) { this.project_id = project_id; } public String getDecision_rationale() { return decision_rationale; } public void setDecision_rationale(String decision_rationale) { this.decision_rationale = decision_rationale; } }
Java
CL
750587672032fbb6e54c82172ea93fd9acafae232c8d9ce713ed0c76b32db751
package com.ntnu.wip.nabl.MVCView.Register; import com.ntnu.wip.nabl.MVCView.IAbstractMvcView; public interface IRegisterView extends IAbstractMvcView { /** * Methods which this can invoke in Listeners */ interface ToggleListener { /** * Project toggle button pressed */ void projectPressed(); /** * Client toggle button pressed */ void clientPressed(); } /** * Register listener * @param listener ToggleListener */ void registerListener(ToggleListener listener); /** * Set project button text * @param text String */ void setProjectText(String text); /** * Set client button text * @param text String */ void setClientText(String text); }
Java
CL
1ef4189f5ff72ad7b9166ede6587f2517381bdfff93422f2b92910f858c6b9f1
package com.imfbp.rz.util; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import com.platform.common.utils.StringUtil; /** * @Title : 文件操作工具类 * @Description : 文件操作工具类 * @Company :yonyouFintech * @author :Xinggh * @date : 2016年12月1日 上午11:31:17 */ public final class FileUtils { /** * 将文本文件中的内容读入到buffer中 * * @param buffer * buffer * @param filePath * 文件路径 * @throws IOException * 异常 */ public final static void readToBuffer(StringBuffer buffer, String filePath) throws IOException { if (StringUtil.isEmpty(filePath)) { return; } if (buffer == null) { buffer = new StringBuffer(); } InputStream is = new FileInputStream(filePath); String line; // 用来保存每行读取的内容 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); line = reader.readLine(); // 读取第一行 while (line != null) { // 如果 line 为空说明读完了 buffer.append(line); // 将读到的内容添加到 buffer 中 buffer.append("\n"); // 添加换行符 line = reader.readLine(); // 读取下一行 } reader.close(); is.close(); } /** * 读取文本文件内容 * * @param filePath * 文件所在路径 * @return 文本内容 * @throws IOException * 异常 */ public final static String readFile(String filePath) throws IOException { StringBuffer sb = new StringBuffer(); readToBuffer(sb, filePath); return sb.toString(); } @SuppressWarnings("resource") public final byte[] getContent(String filePath) throws IOException { File file = new File(filePath); long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { System.out.println("file too big..."); return null; } FileInputStream fi = new FileInputStream(file); byte[] buffer = new byte[(int) fileSize]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } // 确保所有数据均被读取 if (offset != buffer.length) { throw new IOException("Could not completely read file " + file.getName()); } fi.close(); return buffer; } /** * the traditional io way * * @param filename * @return * @throws IOException */ public final static byte[] toByteArray(String filename) throws IOException { File f = new File(filename); if (!f.exists()) { throw new FileNotFoundException(filename); } ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length()); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(f)); int buf_size = 1024; byte[] buffer = new byte[buf_size]; int len = 0; while (-1 != (len = in.read(buffer, 0, buf_size))) { bos.write(buffer, 0, len); } return bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } bos.close(); } } /** * NIO way * * @param filename * @return * @throws IOException */ public final static byte[] toByteArray2(String filename) throws IOException { File f = new File(filename); if (!f.exists()) { throw new FileNotFoundException(filename); } FileChannel channel = null; FileInputStream fs = null; try { fs = new FileInputStream(f); channel = fs.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size()); while ((channel.read(byteBuffer)) > 0) { // do nothing // System.out.println("reading"); } return byteBuffer.array(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } try { fs.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能 * * @param filename * @return * @throws IOException */ @SuppressWarnings("resource") public final static byte[] file2Byte(String filename) throws IOException { FileChannel fc = null; try { fc = new RandomAccessFile(filename, "r").getChannel(); MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load(); System.out.println(byteBuffer.isLoaded()); byte[] result = new byte[(int) fc.size()]; if (byteBuffer.remaining() > 0) { // System.out.println("remain"); byteBuffer.get(result, 0, byteBuffer.remaining()); } return result; } catch (IOException e) { throw e; } finally { try { fc.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) throws Exception { String filename = "d:/testhtmlPdf1111.html"; System.out.println(new String(file2Byte(filename))); } }
Java
CL
97afeede2928e3fa0e73e8a26eae837060ced17ac841738088d2dd0e7799d17b
package com.cjwsjy.gis.util; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.concurrent.atomic.AtomicInteger; public class SourceAccess { public static final int CONNECT_TIMEOUT = 5000; public static final int READ_TIMEOUT = 8000; private static Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("202.111.31.158", 8080)); public static URLConnection openConnection(URL url) throws IOException { URLConnection connection = null; try { connection = url.openConnection(); connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"); connection.setRequestProperty("Accept", "image/webp,image/*,*/*;q=0.8"); connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch"); connection.setRequestProperty("Accept-Language", "en,en-US;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2"); } catch (IOException e) { throw e; } connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); return connection; } public static URLConnection openTerrainConnection(URL url) throws IOException { URLConnection connection = null; try { connection = url.openConnection(); connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); String extensions = "octvertexnormals-watermask"; String header = "application/vnd.quantized-mesh;extensions=" + extensions + ",application/octet-stream;q=0.9,*/*;q=0.01"; connection.setRequestProperty("Accept", header); connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch, br"); connection.setRequestProperty("Accept-Language", "en,en-US;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2"); } catch (IOException e) { throw e; } connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); return connection; } public static ByteBuffer read(URLConnection connection) throws Exception { try { ByteBuffer buffer = doRead(connection); return buffer; } catch (Exception e) { throw e; } } protected static ByteBuffer doRead(URLConnection connection) throws Exception { if (connection == null) { throw new IllegalArgumentException(); } ByteBuffer buffer; InputStream inputStream = null; try { inputStream = connection.getInputStream(); if (inputStream == null) { return null; } buffer = readNonSpecificStream(inputStream, connection); } catch(Exception ex) { throw ex; } finally { closeStream(inputStream, connection.getURL().toString()); } return buffer; } protected static ByteBuffer readNonSpecificStream(InputStream inputStream, URLConnection connection) throws IOException { if (inputStream == null) { throw new IllegalArgumentException(); } int contentLength = connection.getContentLength(); if (contentLength < 1) { return readNonSpecificStreamUnknownLength(inputStream); } ReadableByteChannel channel = Channels.newChannel(inputStream); ByteBuffer buffer = ByteBuffer.allocate(contentLength); int numBytesRead = 0; AtomicInteger contentLengthRead = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && numBytesRead >= 0 && numBytesRead < buffer.limit()) { int count = channel.read(buffer); if (count > 0) { contentLengthRead.getAndAdd(numBytesRead += count); } } if (buffer != null) { buffer.flip(); } return buffer; } protected static ByteBuffer readNonSpecificStreamUnknownLength(InputStream inputStream) throws IOException { final int pageSize = (int) Math.ceil(Math.pow(2, 15)); ReadableByteChannel channel = Channels.newChannel(inputStream); ByteBuffer buffer = ByteBuffer.allocate(pageSize); int count = 0; int numBytesRead = 0; AtomicInteger contentLengthRead = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && count >= 0) { count = channel.read(buffer); if (count > 0) { contentLengthRead.getAndAdd(numBytesRead += count); } if (count > 0 && !buffer.hasRemaining()) { ByteBuffer biggerBuffer = ByteBuffer.allocate(buffer.limit() + pageSize); biggerBuffer.put((ByteBuffer) buffer.rewind()); buffer = biggerBuffer; } if (count <= 0) { // buffer = null; } } if (buffer != null) { buffer.flip(); } return buffer; } protected static void closeStream(InputStream stream, String name) { if (stream == null) { return; } try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } }
Java
CL
18df9d710b2513bdfd9952b86ffd1a7d5ce5b0a6f6d7356537246572ca87b84e
package uk.ac.soton.ecs.mobilesensors.sensor.maxsum; import maxSumController.discrete.DiscreteVariable; import uk.ac.soton.ecs.mobilesensors.layout.Location; import uk.ac.soton.ecs.mobilesensors.sensor.SensorID; import uk.ac.soton.ecs.mobilesensors.sensor.maxsum.domain.MobileSensorMove; public interface MaxSumMovementVariable<T extends MobileSensorMove> extends DiscreteVariable<T> { /** * * @return the SensorID associated with this variable */ public SensorID getSensorID(); /** * * @return the current location of the sensor associated with this variable */ public Location getLocation(); }
Java
CL
11b6c51777588e91ae7ed97ba2325f8b36d64744276a439faee9435221a72a1b
package no.sysco.middleware.workshops.kafka; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * */ public class IssueConsumerApp { public static void main(String[] args) { createConsumerGroup(); createTxConsumerGroup(); } private static void createTxConsumerGroup() { final ExecutorService executor = Executors.newFixedThreadPool(1); final List<KafkaConsumerLoop> consumers = new ArrayList<>(); //Start Consumer Threads for (int i = 0; i < 1; i++) { final KafkaConsumerLoop consumer = new KafkaConsumerLoop( i, "tx-group-01", Collections.singletonList("issue-events"), true); consumers.add(consumer); executor.submit(consumer); } //Close Consumers Runtime.getRuntime().addShutdownHook(new Thread(() -> { for (KafkaConsumerLoop consumer : consumers) { consumer.shutdown(); } executor.shutdown(); try { executor.awaitTermination(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } })); } private static void createConsumerGroup() { final ExecutorService executor = Executors.newFixedThreadPool(3); final List<KafkaConsumerLoop> consumers = new ArrayList<>(); //Start Consumer Threads for (int i = 0; i < 3; i++) { final KafkaConsumerLoop consumer = new KafkaConsumerLoop( i, "group-01", Collections.singletonList("issue-events"), false); consumers.add(consumer); executor.submit(consumer); } //Close Consumers Runtime.getRuntime().addShutdownHook(new Thread(() -> { for (KafkaConsumerLoop consumer : consumers) { consumer.shutdown(); } executor.shutdown(); try { executor.awaitTermination(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } })); } }
Java
CL
99bfb6ce15cddc28494f78c56f183c4da50994673fe222c65510fa36e7249e43
package com.yasinyazici.riot.request.web; import com.yasinyazici.riot.data.exceptions.DataException; import com.yasinyazici.riot.data.exceptions.ReplyException; import com.yasinyazici.riot.data.exceptions.WrongRequestFormatException; import com.yasinyazici.riot.parsers.JsonDataParser; import com.yasinyazici.riot.request.types.RequestType; import java.io.IOException; import java.io.InputStream; /** * <p>Used as interface to create Requests</p> * * @author Yasin * @see RequestFormat as reference on how the usage of parameters corresponding to the {@link RequestType} should be */ public class RequestCreator { /** * <p>Creates a new request which returns an instance of {@link RequestReply} itself, making it possible to access both response- code and message . <!-- -->Used when debugging/testing requests.</p> * * @param requestProperty the request property to assign towards the request * @return a new {@link RequestReply} instance representing the response of the official REST-API * @throws IOException Thrown when an internet problem occurs * @throws WrongRequestFormatException Thrown when the {@link RequestFormat} given as parameter does not equal the parameters found within the request * @throws DataException Thrown when the data is invalid (e.g. empty) * @throws ReplyException Thrown when the connection was successful, but a bad reply returns (other than 201) * */ public static RequestReply createDebugRequest(RequestProperty requestProperty) throws IOException, WrongRequestFormatException, DataException, ReplyException { return new Request(new RequestLink(requestProperty)).makeRequest(); } /** * <p>Creates a new request which returns the {@link InputStream} of the {@link RequestReply} directly, so the content can be parsed by a corresponding {@link JsonDataParser}</p> * @param requestProperty the request property to assign towards the request * @return the {@link InputStream} of the {@link RequestReply} * @throws IOException Thrown when an internet problem occurs * @throws WrongRequestFormatException Thrown when the {@link RequestFormat} given as parameter does not equal the parameters found within the request * @throws DataException Thrown when the data is invalid (e.g. empty) * @throws ReplyException Thrown when the connection was successful, but a bad reply returns (other than 201) * @see JsonDataParser */ public static String createRequest(RequestProperty requestProperty) throws IOException, WrongRequestFormatException, DataException, ReplyException { return new Request(new RequestLink(requestProperty)).makeRequest().getResponseMessage(); } }
Java
CL
7b5e841522bfbd3fe1730c92a3ef81696764caacc739a7cffddbec555744c112
/******************************************************************************* * Copyright 2009 Robot Media SL * * 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.robotmedia.acv.utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; public class AlertUtils { public static AlertDialog showYesNoAlert(Context context, boolean good, int titleId, int messageId, DialogInterface.OnClickListener positiveListener, DialogInterface.OnClickListener negativeListener) { final AlertDialog dialog = new AlertDialog.Builder(context) .setIcon(good ? android.R.drawable.ic_menu_info_details : android.R.drawable.ic_menu_close_clear_cancel) .setTitle(titleId).setMessage(messageId).setPositiveButton(android.R.string.ok, positiveListener) .setNegativeButton(android.R.string.no, negativeListener).create(); dialog.show(); return dialog; } }
Java
CL
aa5e0f55a87762100f2ffa4fcc13083e6e150d4fa5478c6a43d56eeb414c8e18
package com.webcohesion.enunciate.modules.jaxb.util; import com.webcohesion.enunciate.modules.jaxb.EnunciateJaxbContext; import com.webcohesion.enunciate.modules.jaxb.model.*; import com.webcohesion.enunciate.modules.jaxb.model.types.MapXmlType; import com.webcohesion.enunciate.modules.jaxb.model.types.XmlClassType; import com.webcohesion.enunciate.modules.jaxb.model.types.XmlType; import freemarker.ext.beans.BeansWrapper; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import javax.lang.model.element.TypeElement; import javax.xml.namespace.QName; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Gets all the referenced namespaces for a specific root element. * * @author Ryan Heaton */ public class ReferencedNamespacesMethod implements TemplateMethodModelEx { private final EnunciateJaxbContext context; public ReferencedNamespacesMethod(EnunciateJaxbContext context) { this.context = context; } public Object exec(List list) throws TemplateModelException { if (list.size() < 1) { throw new TemplateModelException("The referencedNamespaces method must have an element as a parameter."); } TemplateModel from = (TemplateModel) list.get(0); Object unwrapped = BeansWrapper.getDefaultInstance().unwrap(from); if (!(unwrapped instanceof ElementDeclaration)) { throw new TemplateModelException("The referencedNamespaces method must have an element as a parameter."); } ElementDeclaration elementDeclaration = (ElementDeclaration) unwrapped; Set<String> referencedNamespaces = new HashSet<String>(); referencedNamespaces.add(elementDeclaration.getNamespace()); if (elementDeclaration instanceof RootElementDeclaration) { TypeDefinition typeDef = ((RootElementDeclaration) elementDeclaration).getTypeDefinition(); addReferencedNamespaces(typeDef, referencedNamespaces); } else if (elementDeclaration instanceof LocalElementDeclaration) { TypeElement typeElement = ((LocalElementDeclaration) elementDeclaration).getElementType(); TypeDefinition typeDefinition = this.context.findTypeDefinition(typeElement); if (typeDefinition != null) { addReferencedNamespaces(typeDefinition, referencedNamespaces); } } referencedNamespaces.remove(null); referencedNamespaces.remove(""); referencedNamespaces.remove("http://www.w3.org/2001/XMLSchema"); return referencedNamespaces; } /** * Adds the referenced namespaces of the given type definition to the given set. * * @param typeDefinition The type definition. * @param referencedNamespaces The set of referenced namespaces. */ private void addReferencedNamespaces(TypeDefinition typeDefinition, Set<String> referencedNamespaces) { for (Attribute attribute : typeDefinition.getAttributes()) { QName ref = attribute.getRef(); if (ref != null) { referencedNamespaces.add(ref.getNamespaceURI()); } else { addReferencedNamespaces(attribute.getBaseType(), referencedNamespaces); } } for (Element element : typeDefinition.getElements()) { for (Element choice : element.getChoices()) { QName ref = choice.getRef(); if (ref != null) { referencedNamespaces.add(ref.getNamespaceURI()); } else { addReferencedNamespaces(choice.getBaseType(), referencedNamespaces); } } } Value value = typeDefinition.getValue(); if (value != null) { addReferencedNamespaces(value.getBaseType(), referencedNamespaces); } if (typeDefinition instanceof QNameEnumTypeDefinition) { for (EnumValue enumValue : ((QNameEnumTypeDefinition) typeDefinition).getEnumValues()) { if (enumValue.getValue() != null) { referencedNamespaces.add(((QName)enumValue.getValue()).getNamespaceURI()); } } } addReferencedNamespaces(typeDefinition.getBaseType(), referencedNamespaces); } /** * Adds the referenced namespaces of the given xml type to the given set. * * @param xmlType The xml type. * @param referencedNamespaces The set of referenced namespaces. */ private void addReferencedNamespaces(XmlType xmlType, Set<String> referencedNamespaces) { if (!xmlType.isAnonymous()) { referencedNamespaces.add(xmlType.getNamespace()); } else if (xmlType instanceof MapXmlType) { referencedNamespaces.add(((MapXmlType) xmlType).getKeyType().getNamespace()); referencedNamespaces.add(((MapXmlType) xmlType).getValueType().getNamespace()); } else if (xmlType instanceof XmlClassType) { addReferencedNamespaces(((XmlClassType) xmlType).getTypeDefinition(), referencedNamespaces); } } }
Java
CL
d107945a7543c15b42a6de4129fec18cba19e1dba7a8c55f9b15a99682ebd473
package controller.app22a; import app21a.domain.Product; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import validator.ProductValidator; /** * Created by lambor on 17-5-20. * 国际化 * ls | grep zh_CN | xargs -I {} native2ascii -encoding UTF-8 {} {} */ @Controller( value = "app22a.ProductController" ) @RequestMapping("/app22a/*") public class ProductController { private static final Log logger = LogFactory.getLog(ProductController.class); @RequestMapping("/product_input") public String inputProduct(Model model) { model.addAttribute("product",new Product()); return "ProductForm22_2"; } @RequestMapping("/product_save") public String saveProduct(@ModelAttribute Product product, BindingResult bindingResult,Model model) { ProductValidator productValidator = new ProductValidator(); productValidator.validate(product,bindingResult); if(bindingResult.hasErrors()) { FieldError fieldError = bindingResult.getFieldError(); logger.info("Code:"+fieldError.getCode() + ", field:" + fieldError.getField()); return "ProductForm"; } model.addAttribute("product",product); return "ProductDetails"; } }
Java
CL
119e579afb64e59b7c9b6a0e8fafca8499c1ccc98a3523f7c94f3cb7a875569a
package br.com.casadocodigo.controller; import br.com.casadocodigo.controller.request.BookRequest; import br.com.casadocodigo.controller.response.BookResponse; import br.com.casadocodigo.controller.response.BookResponseDetail; import br.com.casadocodigo.model.Book; import br.com.casadocodigo.repository.BookRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RestController @RequestMapping(value = "/api/books") public class BookController { @Autowired private BookRepository bookRepository; @PersistenceContext private EntityManager entityManager; @PostMapping @Transactional public ResponseEntity<?> saveBook(@RequestBody @Valid BookRequest bookRequest){ if(bookRequest != null) { bookRepository.save(bookRequest.toModel(entityManager)); return ResponseEntity.ok().build(); } return ResponseEntity.badRequest().build(); } @GetMapping @Transactional public ResponseEntity<List<Book>> listBook(){ List<Book> list = bookRepository.findAll(); return ResponseEntity.ok(list); } @GetMapping(value = "/{id}") public ResponseEntity<BookResponseDetail> detailById(@PathVariable Long id){ Optional<Book> book = bookRepository.findById(id); return book.map(value -> ResponseEntity.ok(new BookResponseDetail(value))).orElseGet(() -> ResponseEntity.notFound().build()); } }
Java
CL
64615dc1de8279b91455e01333df155524262ef6db9eada8ea3693958aeaa556
package com.test.dpg.service; import java.io.FileNotFoundException; import java.util.List; import com.test.dpg.models.EventDetails; public interface EventService { /** * Process all events from provided log file and store them in db * * @param fileName * @return All events after the operation * @throws FileNotFoundException if provided fileName is not valid */ List<EventDetails> logEventsFromFile(String fileName) throws FileNotFoundException; /** * Fetches all logged events from db * @return List of {@link EventDetails} */ List<EventDetails> getLoggedEvents(); /** * Deletes all stored events from event_details db table * @return successMessage */ String deleteLoggedEvents(); }
Java
CL
ef113920ee107031a0e6b31c18272c6165910d881cb83cbb96188b5389dabdea
package com.lachesis.mnis.core.bodysign.entity; import java.util.Date; /** * 注意:每个体征可以输入正常值,也可以输入特殊值(拒测等)和补充说明(说明体温是腋温等) * <ul> * <li>itemName - 项目的名称,如体温</li> * <li>itemCode - 项目的编码,如temperature</li> * <li>itemValue - 项目的正常数字取值, 如37</li> * <li>measureNoteName - 测量说明,如腋温,外出等。当为外出一类的说明是itemvalue为空</li> * <li>measureNoteCode - 测量说明的编码</li> * <ul> * transient :序列化时排除该字段 * @author wenhuan.cui * */ public class BodySignItem { /** 项目记录id */ private int detailRecordId; /** 主表记录id */ private int masterRecordId; /** 项目字段 */ private BodySignDict bodySignDict; /** 项目取值,为null时表示未测量,原因从measureNote中获取 */ private String itemValue; //入院出入量时间差 private String ryHourDiff; /** 测量说明编码 */ private String measureNoteCode; /** 测量说明 */ private String measureNoteName; /** 异常标记(-1-偏低,0-正常,1-偏高) */ private int abnormalFlag; /** 默认true 正常标记,false 特殊处理标记 */ private boolean specMark; /** 该项是否显示在体温单上,默认true都显示 **/ private boolean show = true; /** 项目索引 */ private int index; private String patId; //患者id private Date recordDate; //体征记录时间点 private transient boolean isAdd; // 是否已添加 private String status;//事件状态 01:新建 09:已删除 private String unit;//体征item单位 public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public BodySignItem() { this.bodySignDict = new BodySignDict(); } public BodySignItem(BodySignItem other) { this.itemValue = other.itemValue; this.bodySignDict = BodySignDict.create( other.bodySignDict.getItemCode(), other.bodySignDict.getItemName(), other.bodySignDict.getItemUnit()); this.measureNoteCode = other.measureNoteCode; this.measureNoteName = other.measureNoteName; this.abnormalFlag = other.abnormalFlag; this.index = other.index; this.detailRecordId = other.detailRecordId; this.masterRecordId = other.masterRecordId; } public void setItemCode(String itemCode) { bodySignDict.setItemCode(itemCode); } public void setItemUnit(String itemUnit) { bodySignDict.setItemUnit(itemUnit); } public String getItemCode() { return bodySignDict == null ? null : bodySignDict.getItemCode(); } public String getItemUnit() { return bodySignDict.getItemUnit(); } public String getItemName() { return bodySignDict.getItemName(); } public void setItemName(String itemName) { bodySignDict.setItemName(itemName); } public String getItemValue() { return itemValue; } public void setItemValue(String itemValue) { this.itemValue = itemValue; } public BodySignDict getBodySignDict() { return bodySignDict; } public void setBodySignDict(BodySignDict bodySignDict) { this.bodySignDict = bodySignDict; } public String getMeasureNoteCode() { return measureNoteCode; } public void setMeasureNoteCode(String measureNoteCode) { this.measureNoteCode = measureNoteCode; } public String getMeasureNoteName() { return measureNoteName; } public void setMeasureNoteName(String measureNoteName) { this.measureNoteName = measureNoteName; } public int getAbnormalFlag() { return abnormalFlag; } public void setAbnormalFlag(int abnormalFlag) { this.abnormalFlag = abnormalFlag; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public int getDetailRecordId() { return detailRecordId; } public void setDetailRecordId(int detailRecordId) { this.detailRecordId = detailRecordId; } public int getMasterRecordId() { return masterRecordId; } public void setMasterRecordId(int masterRecordId) { this.masterRecordId = masterRecordId; } public boolean isSpecMark() { return specMark; } public void setSpecMark(boolean specMark) { this.specMark = specMark; } public boolean isShow() { return show; } public void setShow(boolean show) { this.show = show; } @Override public boolean equals(Object otherObject) { if (this == otherObject) { return true; } if (otherObject instanceof String) { BodySignItem another = (BodySignItem) otherObject; if (this.getItemCode() == another.getItemCode()) { return true; } } return false; } public String getPatId() { return patId; } public void setPatId(String patId) { this.patId = patId; } public Date getRecordDate() { return recordDate; } public void setRecordDate(Date recordDate) { this.recordDate = recordDate; } public boolean isAdd() { return isAdd; } public void setAdd(boolean isAdd) { this.isAdd = isAdd; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getRyHourDiff() { return ryHourDiff; } public void setRyHourDiff(String ryHourDiff) { this.ryHourDiff = ryHourDiff; } }
Java
CL
a26af2b0df7b71eee16c934b0a09af21652943f2aeaa79c85df50e53a393c383
package structures; import java.util.ArrayList; /** * Encapsulates an interval tree. * * @author runb-cs112 */ public class IntervalTree { /** * The root of the interval tree */ IntervalTreeNode root; /** * Constructs entire interval tree from set of input intervals. Constructing the tree * means building the interval tree structure and mapping the intervals to the nodes. * * @param intervals Array list of intervals for which the tree is constructed */ public IntervalTree(ArrayList<Interval> intervals) { // COMPLETE THIS CONSTRUCTOR } /** * Sorts a set of intervals in place, according to left or right endpoints. * At the end of the method, the parameter array list is a sorted list. * * @param intervals Array list of intervals to be sorted. * @param lr If 'l', then sort is on left endpoints; if 'r', sort is on right endpoints */ public static ArrayList<Interval> sortIntervals(ArrayList<Interval> intervals, char lr) { // COMPLETE THIS METHOD // THE FOLLOWING LINE HAS BEEN ADDED TO MAKE THE METHOD COMPILE return null; } /** * Given a set of intervals (left sorted and right sorted), extracts the left and right end points, * and returns a sorted list of the combined end points without duplicates. * * @param leftSortedIntervals Array list of intervals sorted according to left endpoints * @param rightSortedIntervals Array list of intervals sorted according to right endpoints * @return Sorted array list of all endpoints without duplicates */ public static ArrayList<Integer> getSortedEndPoints(ArrayList<Interval> leftSortedIntervals, ArrayList<Interval> rightSortedIntervals) { // COMPLETE THIS METHOD // THE FOLLOWING LINE HAS BEEN ADDED TO MAKE THE METHOD COMPILE return null; } /** * Builds the interval tree structure given a sorted array list of end points * without duplicates. * * @param endPoints Sorted array list of end points * @return Root of the tree structure */ public static IntervalTreeNode buildTreeNodes(ArrayList<Integer> endPoints) { // COMPLETE THIS METHOD // THE FOLLOWING LINE HAS BEEN ADDED TO MAKE THE METHOD COMPILE return null; } /** * Returns the root of this interval tree. * * @return Root of interval tree. */ public IntervalTreeNode getRoot() { return root; } /** * Maps a set of intervals to the nodes of this interval tree. * * @param leftSortedIntervals Array list of intervals sorted according to left endpoints * @param rightSortedIntervals Array list of intervals sorted according to right endpoints */ public void mapIntervalsToTree(ArrayList<Interval> leftSortedIntervals, ArrayList<Interval> rightSortedIntervals) { // COMPLETE THIS METHOD } /** * Gets all intervals in this interval tree that intersect with a given interval. * * @param q The query interval for which intersections are to be found * @return Array list of all intersecting intervals; size is 0 if there are no intersections */ public ArrayList<Interval> findIntersectingIntervals(Interval q) { // COMPLETE THIS METHOD // THE FOLLOWING LINE HAS BEEN ADDED TO MAKE THE METHOD COMPILE return null; } }
Java
CL
977c92c1b07108b072e09681c0601eb20711793a50132da4b76d53e381d907df
package com.capgemini.fms.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; import com.capgemini.fms.entity.Airport; import com.capgemini.fms.exception.AirportException; import com.capgemini.fms.service.AirportService; @RestController public class AirportController { @Autowired private AirportService airportservice; @CrossOrigin @PostMapping("/addairport") public ResponseEntity<String> addAirport(@Valid @RequestBody Airport airport, BindingResult br) throws AirportException { String err = ""; if (br.hasErrors()) { List<FieldError> errors = br.getFieldErrors(); for (FieldError error : errors) err += error.getDefaultMessage() + "<br/>"; throw new AirportException(err); } try { airportservice.addairport(airport); return new ResponseEntity<String>("Airport added successfully", HttpStatus.OK); } catch (DataIntegrityViolationException ex) { throw new AirportException("code already exists"); } } @CrossOrigin @GetMapping("/viewallairport") public ResponseEntity<List<Airport>> getAirportlist() { List<Airport> airportList = airportservice.viewallairport(); return new ResponseEntity<List<Airport>>(airportList, HttpStatus.OK); } @CrossOrigin @DeleteMapping("/deleteairport/{airportCode}") public ResponseEntity<String> deleteairport(@PathVariable String airportCode) throws AirportException { try { airportservice.deleteairport(airportCode); return new ResponseEntity<String>("airport is deleted", HttpStatus.OK); } catch (DataIntegrityViolationException ex) { throw new AirportException("airport code doesnot exists"); } } @CrossOrigin @GetMapping("/airportdetails/{airportCode}") public Optional<Airport> airportdetails(@PathVariable String airportCode) throws AirportException{ try { return airportservice.airportdetails(airportCode); } catch (Exception ex) { throw new AirportException(ex.getMessage()); } } @CrossOrigin @PutMapping("/updateairport/{airportCode}") public ResponseEntity<String> updateairport(@Valid @RequestBody Airport airport,@PathVariable String airportCode,BindingResult br ) throws AirportException { String err = ""; if (br.hasErrors()) { List<FieldError> errors = br.getFieldErrors(); for (FieldError error : errors) err += error.getDefaultMessage() + "<br/>"; throw new AirportException(err); } try { airportservice.updateairport(airport,airportCode); return new ResponseEntity<String>("Airport updated successfully", HttpStatus.OK); } catch (DataIntegrityViolationException ex) { throw new AirportException("airport code already exists"); } } }
Java
CL
ce0c7410b6a566c22d666464f523d13d5eb38dff2d58f1a64e95381583aba57d
package com.nicolasmarcosti.cursomc.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.nicolasmarcosti.cursomc.domain.Produto; //Declaração do repositório, com JpaRepository, que por sua vez dependerá da classe Produto para o devido mapeamento funcionar @Repository public interface ProdutoRepository extends JpaRepository<Produto,Integer>{ }
Java
CL
980004e5f90c83d14130990e0d5c01f22d604b3070d730d4669aa951b14cd16e