hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
9fa47a39d13188bd28ecc1281327f4f01bfd210d
583
package com.xuecheng.manage_course.service; import com.xuecheng.framework.domain.course.ext.CategoryNode; import com.xuecheng.manage_course.dao.CategoryMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * User: 李锦卓 * Time: 2019/3/19 11:08 */ @Service @Transactional public class CategoryService { @Autowired private CategoryMapper categoryMapper; public CategoryNode findList() { return categoryMapper.findList(); } }
26.5
64
0.785592
09d0991f82c7164fb47acf08c0d2d23032229853
1,221
package nablarch.common.web.validator; import java.io.Serializable; import nablarch.common.web.interceptor.InjectForm; import nablarch.core.validation.ValidationContext; import nablarch.core.validation.ValidationUtil; import nablarch.fw.web.HttpRequest; import nablarch.fw.web.servlet.ServletExecutionContext; /** * NablarchのFormを使用する場合のリクエスト内容のバリデーション、オブジェクト(Form)生成ロジック. * * <p> * {@link BeanValidationStrategy}とは異なり、 * 本実装ではバリデーションエラーが発生した場合には、 * リクエストパラメータから値をコピーしたオブジェクト(Form)を * リクエストスコープに格納する機能は持たない。 * これは、Nablarchのバリデーションが、(バリデーション前ではなく) * バリデーション成功後にオブジェクトを生成するためである。 * </p> * * @author sumida */ public class NablarchValidationStrategy implements ValidationStrategy { public Serializable validate( HttpRequest request, InjectForm annotation, boolean canValidate, final ServletExecutionContext context) { if (!canValidate) { return null; } ValidationContext<? extends Serializable> validationContext = ValidationUtil.validateAndConvertRequest( annotation.prefix(), annotation.form(), request, annotation.validate()); validationContext.abortIfInvalid(); return validationContext.createObject(); } }
29.071429
117
0.750205
6af15472de8aca27e62c999e5c76148c6f81e26b
2,148
/* * 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.ode.jacob.soup; import java.lang.reflect.Method; /** * Persistent store representation of a message (i.e. method application / * channel write) waiting for a corresponding object (i.e. channel read). This * structure consists of a label identifying the method that should be applied * to the object once it is available, and the arguments that should be applied * to said method. * * @author Maciej Szefler <a href="mailto:mbs@fivesight.com">mbs</a> */ public class CommSend extends Comm { private Object[] _args; private Method _method; protected CommSend() { } public CommSend(CommChannel chnl, Method method, Object[] args) { super(null, chnl); _args = args; _method = method; } public Method getMethod() { return _method; } /** * Get the arguments for the method application. */ public Object[] getArgs() { return _args; } public String toString() { StringBuffer buf = new StringBuffer(getChannel().toString()); buf.append(" ! ").append(_method.getName()).append('('); for (int i = 0; _args != null && i < _args.length; ++i) { if (i != 0) buf.append(','); buf.append(_args[i]); } buf.append(')'); return buf.toString(); } }
31.130435
79
0.663873
8885cb5b2eb1b4739255e14dae7370e2100a9bf9
812
package br.edu.infnet.domain.controller; import br.edu.infnet.domain.service.EnderecoService; import org.hibernate.type.StringNVarcharType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class EnderecoController { @Autowired private EnderecoService enderecoService; @PostMapping(value="/buscarCep") public String buscaCep(Model model, @RequestParam String cep){//clase auxiliar que pega as informações da tela e passa ao controller model.addAttribute("endereco", enderecoService.buscarCep(cep)); return "/usuario/cadastro"; } }
33.833333
136
0.794335
a57859d6c9706b69f996094a0529fdb1cb3483e1
10,662
/* * Copyright 2017-2021 Axway Software * * 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.axway.ats.core.reflect; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.axway.ats.core.BaseTest; public class Test_MethodFinder extends BaseTest { @Test( expected = IllegalArgumentException.class) public void classConstructorNegativeNullClass() throws NoSuchMethodException, AmbiguousMethodException { new MethodFinder(null); } @Test( expected = IllegalArgumentException.class) public void classConstructorNegativePrimitiveType() throws NoSuchMethodException, AmbiguousMethodException { new MethodFinder(Integer.TYPE); } @Test( expected = IllegalArgumentException.class) public void classConstructorNegativeArrayType() throws NoSuchMethodException, AmbiguousMethodException { new MethodFinder( (new byte[]{}).getClass()); } @Test public void findConstructorInClassPositive() throws NoSuchMethodException, AmbiguousMethodException { MethodFinder methodFinder = new MethodFinder(FileInputStream.class); //one argument assertNotNull(methodFinder.findConstructor(new Class<?>[]{ File.class })); //no arguments methodFinder = new MethodFinder(ArrayList.class); assertNotNull(methodFinder.findConstructor(null)); } @Test( expected = NoSuchMethodException.class) public void findConstructorInClassNegative() throws NoSuchMethodException, AmbiguousMethodException { MethodFinder methodFinder = new MethodFinder(FileInputStream.class); //one argument methodFinder.findConstructor(new Class<?>[]{}); } @Test public void findMethodWithNamePositive() throws NoSuchMethodException, AmbiguousMethodException { MethodFinder methodFinder = new MethodFinder(FileInputStream.class); //null argument assertNotNull(methodFinder.findMethod("close", null)); //one argument assertNotNull(methodFinder.findMethod("read", new Class<?>[]{ (new byte[]{}).getClass() })); //several arguments assertNotNull(methodFinder.findMethod("read", new Class<?>[]{ (new byte[]{}).getClass(), Integer.TYPE, Integer.TYPE })); //unboxing assertNotNull(methodFinder.findMethod("read", new Class<?>[]{ (new byte[]{}).getClass(), Integer.class, Integer.class })); //widening conversion assertNotNull(methodFinder.findMethod("read", new Class<?>[]{ (new byte[]{}).getClass(), Byte.class, Short.TYPE })); } @Test( expected = NoSuchMethodException.class) public void findMethodWithNameNegative() throws NoSuchMethodException, AmbiguousMethodException { MethodFinder methodFinder = new MethodFinder(FileInputStream.class); //one argument methodFinder.findMethod("read123", new Class<?>[]{}); } @Test public void findMethodPositive() throws NoSuchMethodException, AmbiguousMethodException { MethodFinder methodFinder = new MethodFinder(FileInputStream.class); //one argument assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass() })); //several arguments assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(), Integer.TYPE, Integer.TYPE })); //unboxing assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(), Integer.class, Integer.class })); //widening conversion assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(), Byte.class, Short.TYPE })); } @Test( expected = NoSuchMethodException.class) public void findMethodNegative() throws NoSuchMethodException, AmbiguousMethodException { MethodFinder methodFinder = new MethodFinder(FileInputStream.class); //one argument methodFinder.findMethod(new Class<?>[]{ Integer.class, Integer.class, Integer.class }); } @Test public void findMethodConstructorMethodListPositive() throws NoSuchMethodException, AmbiguousMethodException { MethodFinder methodFinder = new MethodFinder("methods", Arrays.asList(FileInputStream.class.getDeclaredMethods())); //one argument assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass() })); //several arguments assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(), Integer.TYPE, Integer.TYPE })); //unboxing assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(), Integer.class, Integer.class })); //widening conversion assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(), Byte.class, Short.TYPE })); } @Test( expected = NoSuchMethodException.class) public void findMethodConstructorMethodListNegative() throws NoSuchMethodException, AmbiguousMethodException { MethodFinder methodFinder = new MethodFinder("methods", Arrays.asList(FileInputStream.class.getDeclaredMethods())); //one argument methodFinder.findMethod(new Class<?>[]{ Integer.class, Integer.class, Integer.class }); } @Test( expected = AmbiguousMethodException.class) public void findMethodConstructorMethodListNegativeAmbigous() throws NoSuchMethodException, AmbiguousMethodException { MethodFinder methodFinder = new MethodFinder("ambiguous", Arrays.asList(MethodFinderTester.class.getDeclaredMethods())); //no arguments methodFinder.findMethod("ambiguousMethod", new Class<?>[]{ Void.TYPE }); } @Test public void findMethodConstructorMethodListCustomRulesPositive() throws NoSuchMethodException, AmbiguousMethodException { List<TypeComparisonRule> typeComparisonRules = new ArrayList<TypeComparisonRule>(); typeComparisonRules.add(new CustomTypeComparisonRule()); MethodFinder methodFinder = new MethodFinder("methods", Arrays.asList(MethodFinderTester.class.getDeclaredMethods()), typeComparisonRules); //one argument - this argument will be evaulated as String in our custom rule assertNotNull(methodFinder.findMethod(new Class<?>[]{ Test_MethodFinder.class })); } @Test public void getParameterTypesFromPositive() { //no arguments Assert.assertArrayEquals(new Class<?>[]{}, MethodFinder.getParameterTypesFrom(new Object[]{})); //two parameters and null Assert.assertArrayEquals(new Class<?>[]{ String.class, Void.TYPE, Integer.class }, MethodFinder.getParameterTypesFrom(new Object[]{ new String("adf"), null, 3 })); } @Test public void getParameterTypesFromByClassNamePositive() throws ClassNotFoundException { //two parameters Assert.assertArrayEquals(new Class<?>[]{ Byte.TYPE, String.class }, MethodFinder.getParameterTypesFrom(new String[]{ "byte", "java.lang.String" })); } @Test public void getParameterTypesFromByClassNameClassLoaderPositive() throws ClassNotFoundException { //two parameters Assert.assertArrayEquals(new Class<?>[]{ Byte.TYPE, Test_MethodFinder.class }, MethodFinder.getParameterTypesFrom(new String[]{ "byte", Test_MethodFinder.class.getName() }, Test_MethodFinder.class.getClassLoader())); } private static class CustomTypeComparisonRule implements TypeComparisonRule { public boolean isCompatible( Class<?> argType, Class<?> parameterType ) { if (argType == Test_MethodFinder.class && parameterType == String.class) { return true; } return false; } } }
42.142292
119
0.554868
c499a1cf9af6667df66b924ab475d76d2b78c948
330
import com.subodh.javatraining.oop.classExamples.Stack; public class StackTest { public static void main(String[] args) { Stack stack1 = new Stack(); stack1.pop(); stack1.push(1); stack1.push(2); stack1.push(3); stack1.pop(); System.out.println(stack1.peek()); } }
23.571429
55
0.587879
25e5d5974be93f4daa226f2d93ea61608ace2bc1
8,401
package com.koala.springComponents.springContext.context.support; import com.koala.springComponents.springContext.context.ConfigurableApplicationContext; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextException; import org.springframework.context.support.LiveBeansViewMBean; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; /** * Create by koala on 2021-08-26 */ @Deprecated public class LiveBeansView implements LiveBeansViewMBean, ApplicationContextAware { public static final String MBEAN_DOMAIN_PROPERTY_NAME = "spring.liveBeansView.mbeanDomain"; public static final String MBEAN_APPLICATION_KEY = "application"; private static final Set<ConfigurableApplicationContext> applicationContexts = new LinkedHashSet<>(); @Nullable private static String applicationName; static void registerApplicationContext(ConfigurableApplicationContext applicationContext) { String mbeanDomain = applicationContext.getEnvironment().getProperty(MBEAN_DOMAIN_PROPERTY_NAME); if (mbeanDomain != null) { synchronized (applicationContexts) { if (applicationContexts.isEmpty()) { try { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); applicationName = applicationContext.getApplicationName(); server.registerMBean(new org.springframework.context.support.LiveBeansView(), new ObjectName(mbeanDomain, MBEAN_APPLICATION_KEY, applicationName)); } catch (Throwable ex) { throw new ApplicationContextException("Failed to register LiveBeansView MBean", ex); } } applicationContexts.add(applicationContext); } } } static void unregisterApplicationContext(ConfigurableApplicationContext applicationContext) { synchronized (applicationContexts) { if (applicationContexts.remove(applicationContext) && applicationContexts.isEmpty()) { try { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); String mbeanDomain = applicationContext.getEnvironment().getProperty(MBEAN_DOMAIN_PROPERTY_NAME); if (mbeanDomain != null) { server.unregisterMBean(new ObjectName(mbeanDomain, MBEAN_APPLICATION_KEY, applicationName)); } } catch (Throwable ex) { throw new ApplicationContextException("Failed to unregister LiveBeansView MBean", ex); } finally { applicationName = null; } } } } @Nullable private ConfigurableApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { Assert.isTrue(applicationContext instanceof ConfigurableApplicationContext, "ApplicationContext does not implement ConfigurableApplicationContext"); this.applicationContext = (ConfigurableApplicationContext) applicationContext; } @Override public String getSnapshotAsJson() { Set<ConfigurableApplicationContext> contexts; if (this.applicationContext != null) { contexts = Collections.singleton(this.applicationContext); } else { contexts = findApplicationContexts(); } return generateJson(contexts); } protected Set<ConfigurableApplicationContext> findApplicationContexts() { synchronized (applicationContexts) { return new LinkedHashSet<>(applicationContexts); } } protected String generateJson(Set<ConfigurableApplicationContext> contexts) { StringBuilder result = new StringBuilder("[\n"); for (Iterator<ConfigurableApplicationContext> it = contexts.iterator(); it.hasNext();) { ConfigurableApplicationContext context = it.next(); result.append("{\n\"context\": \"").append(context.getId()).append("\",\n"); if (context.getParent() != null) { result.append("\"parent\": \"").append(context.getParent().getId()).append("\",\n"); } else { result.append("\"parent\": null,\n"); } result.append("\"beans\": [\n"); ConfigurableListableBeanFactory bf = context.getBeanFactory(); String[] beanNames = bf.getBeanDefinitionNames(); boolean elementAppended = false; for (String beanName : beanNames) { BeanDefinition bd = bf.getBeanDefinition(beanName); if (isBeanEligible(beanName, bd, bf)) { if (elementAppended) { result.append(",\n"); } result.append("{\n\"bean\": \"").append(beanName).append("\",\n"); result.append("\"aliases\": "); appendArray(result, bf.getAliases(beanName)); result.append(",\n"); String scope = bd.getScope(); if (!StringUtils.hasText(scope)) { scope = BeanDefinition.SCOPE_SINGLETON; } result.append("\"scope\": \"").append(scope).append("\",\n"); Class<?> beanType = bf.getType(beanName); if (beanType != null) { result.append("\"type\": \"").append(beanType.getName()).append("\",\n"); } else { result.append("\"type\": null,\n"); } result.append("\"resource\": \"").append(getEscapedResourceDescription(bd)).append("\",\n"); result.append("\"dependencies\": "); appendArray(result, bf.getDependenciesForBean(beanName)); result.append("\n}"); elementAppended = true; } } result.append("]\n"); result.append("}"); if (it.hasNext()) { result.append(",\n"); } } result.append("]"); return result.toString(); } protected boolean isBeanEligible(String beanName, BeanDefinition bd, ConfigurableBeanFactory bf) { return (bd.getRole() != BeanDefinition.ROLE_INFRASTRUCTURE && (!bd.isLazyInit() || bf.containsSingleton(beanName))); } @Nullable protected String getEscapedResourceDescription(BeanDefinition bd) { String resourceDescription = bd.getResourceDescription(); if (resourceDescription == null) { return null; } StringBuilder result = new StringBuilder(resourceDescription.length() + 16); for (int i = 0; i < resourceDescription.length(); i++) { char character = resourceDescription.charAt(i); if (character == '\\') { result.append('/'); } else if (character == '"') { result.append("\\").append('"'); } else { result.append(character); } } return result.toString(); } private void appendArray(StringBuilder result, String[] arr) { result.append('['); if (arr.length > 0) { result.append('\"'); } result.append(StringUtils.arrayToDelimitedString(arr, "\", \"")); if (arr.length > 0) { result.append('\"'); } result.append(']'); } }
42.005
117
0.597191
a54108d8483e015f0575d00391e6c90635830acb
9,741
/** * Copyright (c) 2009-2011 Misys Open Source Solutions (MOSS) and others * * 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. * * Contributors: * Misys Open Source Solutions - initial API and implementation * - */ package org.openhealthtools.openxds.common; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openhealthtools.openexchange.actorconfig.IBrokerController; import org.openhealthtools.openxds.registry.api.XdsRegistry; import org.openhealthtools.openxds.repository.api.XdsRepository; import org.openhealthtools.openxds.xca.api.XcaIG; import org.openhealthtools.openxds.xca.api.XcaRG; /** * This class presents a single global <code>XdsBroker</code> * instance to the OpenXDS code. It can simply be * initialized and then requested from any code whenever necessary. * * @author <a href="mailto:wenzhi.li@misys.com">Wenzhi Li</a> */ public class XdsBroker { /** A single instance for this class */ private static XdsBroker singleton = null; /** Log for problems encountered by the XdsBroker */ private static final Log log = LogFactory.getLog(XdsBroker.class); /** A list of all known xds registries */ private Vector<XdsRegistry> xdsRegistries = new Vector<XdsRegistry>(); /** A list of all known xds repositories */ private Vector<XdsRepository> xdsRepositories = new Vector<XdsRepository>(); /** A list of all known xca responding gateway */ private Vector<XcaRG> xcaRGs = new Vector<XcaRG>(); /** A list of all known xca Initiating gateway */ private Vector<XcaIG> xcaIGs = new Vector<XcaIG>(); /** * A private constructor for creating the singleton instance. */ private XdsBroker() { super(); } /** * Gets the single global instance of the <code>XdsBroker</code>. * * @return the patient broker */ public static synchronized XdsBroker getInstance() { if (singleton == null) { singleton = new XdsBroker(); } return singleton; } /** * Gets a collection of XDS Registry actors * * @return the XdsRegistry Collection */ public Collection<XdsRegistry> getXdsRegistries(){ return Collections.unmodifiableCollection(this.xdsRegistries); } /** * Gets a collection of XDS Repository actors * * @return the XdsRepository Collection */ public Collection<XdsRepository> getXdsRepositories(){ return Collections.unmodifiableCollection(this.xdsRepositories); } /** * Gets a collection of XCA Responding Gateway actors * * @return the XCA Responding Gateway Collection */ public Collection<XcaRG> getXcaRG(){ return Collections.unmodifiableCollection(this.xcaRGs); } /** * Gets a collection of XCA Initiating Gateway actors * * @return the XCA Initiating Gateway Collection */ public Collection<XcaIG> getXcaIG(){ return Collections.unmodifiableCollection(this.xcaIGs); } /** * Registers a new XDS Registry. This method * is typically called when an XDS Registry server is started. * * @param xdsRegistry an XDS Registry * @return <code>true</code> if this XDS Registry was successfully added */ public synchronized boolean registerXdsRegistry(XdsRegistry xdsRegistry) { // If the xdsRegistry is new, add it to the list if ((xdsRegistry != null) && (!xdsRegistries.contains(xdsRegistry))) { xdsRegistry.start(); xdsRegistries.add(xdsRegistry); return true; } else { return false; } } /** * Registers a new XDS Repository. This method * is typically called when an XDS Repository server is started. * * @param xdsRepository an XDS Repository * @return <code>true</code> if this XDS Repository was successfully added */ public synchronized boolean registerXdsRepository(XdsRepository xdsRepository) { // If the xdsRepository is new, add it to the list if ((xdsRepository != null) && (!xdsRepositories.contains(xdsRepository))) { xdsRepository.start(); xdsRepositories.add(xdsRepository); return true; } else { return false; } } /** * Unregisters the active XDS Registries specified by the controller. If the * controller is null unregister all XDS Registries. An XDS Registry is stopped * when it is unregistered. * * @param controller the controller specifying which XDS Registry to unregister. All XDS * Registries will be unregistered if it is null. * @return <code>true</code> if all Registries were actually unregistered */ public synchronized boolean unregisterXdsRegistries(IBrokerController controller) { ArrayList<XdsRegistry> removed = new ArrayList<XdsRegistry>(); // Find all the sources to remove for (XdsRegistry actor: xdsRegistries) { if ((controller == null) || controller.shouldUnregister(actor)) { removed.add(actor); } } if (removed.isEmpty()) return false; // Remove them xdsRegistries.removeAll(removed); // Stop them all too for (XdsRegistry actor: removed) actor.stop(); return true; } /** * Unregisters the active XDS Repositories specified by the controller. If the * controller is null unregister all XDS Repositories. An XDS Repository is stopped * when it is unregistered. * * @param controller the controller specifying which XDS Repository to unregister. All XDS * Repositories will be unregistered if it is null. * @return <code>true</code> if all Repositories were actually unregistered */ public synchronized boolean unregisterXdsRepositories(IBrokerController controller) { ArrayList<XdsRepository> removed = new ArrayList<XdsRepository>(); // Find all the sources to remove for (XdsRepository actor: xdsRepositories) { if ((controller == null) || controller.shouldUnregister(actor)) { removed.add(actor); } } if (removed.isEmpty()) return false; // Remove them xdsRepositories.removeAll(removed); // Stop them all too for (XdsRepository actor: removed) actor.stop(); return true; } /** * Registers a new XCA Responding Gateway. This method * is typically called when an XCA Gateway server is started. * * @param xcaRG an XCA Responding Gateway * @return <code>true</code> if this XCA Responding Gateway was successfully added */ public synchronized boolean registerXcaRG(XcaRG xcaRG) { // If the xcaRG is new, add it to the list if ((xcaRG != null) && (!xcaRGs.contains(xcaRG))) { xcaRG.start(); xcaRGs.add(xcaRG); return true; } else { return false; } } /** * Unregisters the active XCA Responding Gateway specified by the controller. If the * controller is null unregister all XCA Responding Gateway. An XCA Responding Gateway is stopped * when it is unregistered. * * @param controller the controller specifying which XCA Responding Gatway to unregister. All XDS * Responding Gateways will be unregistered if it is null. * @return <code>true</code> if all Responding Gateways were actually unregistered */ public synchronized boolean unregisterXcaRG(IBrokerController controller) { ArrayList<XcaRG> removed = new ArrayList<XcaRG>(); // Find all the sources to remove for (XcaRG actor: xcaRGs) { if ((controller == null) || controller.shouldUnregister(actor)) { removed.add(actor); } } if (removed.isEmpty()) return false; // Remove them xcaRGs.removeAll(removed); // Stop them all too for (XcaRG actor: removed) actor.stop(); return true; } /** * Registers a new XCA Initiating Gateway. This method * is typically called when an XCA Gateway server is started. * * @param xcaRG an XCA Initiating Gateway * @return <code>true</code> if this XCA Initiating Gateway was successfully added */ public synchronized boolean registerXcaIG(XcaIG xcaIG) { // If the xcaRG is new, add it to the list if ((xcaIG != null) && (!xcaIGs.contains(xcaIG))) { xcaIG.start(); xcaIGs.add(xcaIG); return true; } else { return false; } } /** * Unregisters the active XCA Initiating Gateway specified by the controller. If the * controller is null unregister all XCA Initiating Gateway. An XCA Initiating Gateway is stopped * when it is unregistered. * * @param controller the controller specifying which XCA Initiating Gatway to unregister. All XDS * Initiating Gateways will be unregistered if it is null. * @return <code>true</code> if all Initiating Gateways were actually unregistered */ public synchronized boolean unregisterXcaIG(IBrokerController controller) { ArrayList<XcaIG> removed = new ArrayList<XcaIG>(); // Find all the sources to remove for (XcaIG actor: xcaIGs) { if ((controller == null) || controller.shouldUnregister(actor)) { removed.add(actor); } } if (removed.isEmpty()) return false; // Remove them xcaIGs.removeAll(removed); // Stop them all too for (XcaIG actor: removed) actor.stop(); return true; } }
33.705882
104
0.698902
b89a0378c6ea4e552c5447d4a24624fa1ad37712
1,280
package com.maximchuk.rest.api.client.util; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; /** * @author Maxim Maximchuk * date 14.07.2015. */ public class StringParamBuilder { private Map<String, Object> params; public StringParamBuilder(){ params = new HashMap<String, Object>(); } public StringParamBuilder(Map<String, Object> params) { this.params = params; } public void putParam(String key, Object value) { params.put(key, value); } public String build() { StringBuilder paramBuilder = new StringBuilder(); for (Map.Entry<String, Object> param: params.entrySet()) { paramBuilder.append(urlEncode(param.getKey())).append("=").append(urlEncode(param.getValue().toString())) .append("&"); } if (paramBuilder.length() > 0) { paramBuilder.deleteCharAt(paramBuilder.length() - 1); } return paramBuilder.toString(); } private String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
26.122449
117
0.615625
13d75e49907bb61f87c4a64d0cc16413be52abce
3,203
/* * $Id: AbstractSelectAction.java 421119 2006-07-12 04:49:11Z wsmoak $ * * Copyright 2003-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.struts.chain.commands; import org.apache.struts.chain.contexts.ActionContext; import org.apache.struts.config.ActionConfig; import org.apache.struts.config.ModuleConfig; /** * <p>Cache the <code>ActionConfig</code> instance for the action to be used * for processing this request.</p> * * @version $Rev: 421119 $ $Date: 2005-11-05 21:44:59 -0500 (Sat, 05 Nov 2005) * $ */ public abstract class AbstractSelectAction extends ActionCommandBase { // ---------------------------------------------------------- Public Methods /** * <p>Cache the <code>ActionConfig</code> instance for the action to be * used for processing this request.</p> * * @param actionCtx The <code>Context</code> for the current request * @return <code>false</code> so that processing continues * @throws InvalidPathException if no valid action can be identified for * this request * @throws Exception if thrown by the Action class */ public boolean execute(ActionContext actionCtx) throws Exception { // Identify the matching path for this request String path = getPath(actionCtx); // Cache the corresponding ActonConfig instance ModuleConfig moduleConfig = actionCtx.getModuleConfig(); ActionConfig actionConfig = moduleConfig.findActionConfig(path); if (actionConfig == null) { // NOTE Shouldn't this be the responsibility of ModuleConfig? // Locate the mapping for unknown paths (if any) ActionConfig[] configs = moduleConfig.findActionConfigs(); for (int i = 0; i < configs.length; i++) { if (configs[i].getUnknown()) { actionConfig = configs[i]; break; } } } if (actionConfig == null) { throw new InvalidPathException("No action config found for the specified url.", path); } actionCtx.setActionConfig(actionConfig); return (false); } // ------------------------------------------------------- Protected Methods /** * <p>Return the path to be used to select the <code>ActionConfig</code> * for this request.</p> * * @param context The <code>Context</code> for this request * @return Path to be used to select the ActionConfig */ protected abstract String getPath(ActionContext context); }
36.397727
91
0.625663
f4a6ec2d68f50e9293e06424bc2bba9142efc3f0
1,147
package helpers; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; public class BullshifierException extends Exception { private static final ConcurrentMap<String, AtomicInteger> pathToCounterMap = new ConcurrentHashMap<String, AtomicInteger>(); private final Context context; public BullshifierException(Context context) { this.context = context; String pathString = context.toPathString(); if (!pathToCounterMap.containsKey(pathString)) { pathToCounterMap.putIfAbsent(pathString, new AtomicInteger()); } AtomicInteger pathCounter = pathToCounterMap.get(pathString); pathCounter.addAndGet(1); } public Context getContext() { return context; } @Override public String toString() { if (context == null) { return "context is null"; } String pathString = context.toPathString(); AtomicInteger pathCounter = pathToCounterMap.get(pathString); return "unique ex: " + pathToCounterMap.size() + ", happened: " + pathCounter.toString() + " times" + ", context is: " + context.toString(); } }
25.488889
77
0.737576
8c6b6aa45caa466b1def5a534c4a2de36c21392c
1,858
package com.threathunter.greyhound.server.esper.eplgen; import com.threathunter.model.VariableMeta; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Helper class for read variables or events from file * * @author daisy */ public class JsonFileReader { private static final ObjectMapper MAPPER = new ObjectMapper(); public static <T> T getFromResourceFile(String file, Class<T> valueType) throws IOException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(file); try { return MAPPER.readValue(is, valueType); } finally { if (is != null) { is.close(); } } } public static List<Object> getValuesFromFile(String file, ClassType type) throws IOException { if (type == ClassType.MAP) { Map<String, Object> map = getFromResourceFile(file, Map.class); return (List<Object>) map.get("values"); } else if (type == ClassType.LIST) { return getFromResourceFile(file, List.class); } throw new RuntimeException("cannot read from json file, object is neither a map nor a list"); } public static List<VariableMeta> getVariableMetas(String file, ClassType type) throws IOException { List<Object> values = JsonFileReader.getValuesFromFile(file, type); List<VariableMeta> metas = new ArrayList<>(); for (Object map : values) { try { metas.add(VariableMeta.from_json_object(map)); } catch (Exception e) { e.printStackTrace(); } } return metas; } public enum ClassType { MAP, LIST } }
30.966667
103
0.6324
26db02e39d63dafb1128e0b36babc493a8209ad2
23,849
/** * 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.tajo.pullserver; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DataInputByteBuffer; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.ReadaheadPool; import org.apache.hadoop.mapred.FadvisedChunkedFile; import org.apache.hadoop.metrics2.MetricsSystem; import org.apache.hadoop.metrics2.annotation.Metric; import org.apache.hadoop.metrics2.annotation.Metrics; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.metrics2.lib.MutableCounterInt; import org.apache.hadoop.metrics2.lib.MutableCounterLong; import org.apache.hadoop.metrics2.lib.MutableGaugeInt; import org.apache.hadoop.security.ssl.SSLFactory; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServices; import org.apache.hadoop.yarn.service.AbstractService; import org.apache.tajo.QueryId; import org.apache.tajo.catalog.Schema; import org.apache.tajo.conf.TajoConf; import org.apache.tajo.conf.TajoConf.ConfVars; import org.apache.tajo.pullserver.retriever.FileChunk; import org.apache.tajo.storage.RowStoreUtil; import org.apache.tajo.storage.RowStoreUtil.RowStoreDecoder; import org.apache.tajo.storage.Tuple; import org.apache.tajo.storage.TupleComparator; import org.apache.tajo.storage.index.bst.BSTIndex; import org.apache.tajo.util.TajoIdUtils; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.*; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.frame.TooLongFrameException; import org.jboss.netty.handler.codec.http.*; import org.jboss.netty.handler.ssl.SslHandler; import org.jboss.netty.handler.stream.ChunkedWriteHandler; import org.jboss.netty.util.CharsetUtil; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.net.InetSocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static org.jboss.netty.handler.codec.http.HttpHeaders.isKeepAlive; import static org.jboss.netty.handler.codec.http.HttpHeaders.setContentLength; import static org.jboss.netty.handler.codec.http.HttpMethod.GET; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*; import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1; public class PullServerAuxService extends AbstractService implements AuxServices.AuxiliaryService { private static final Log LOG = LogFactory.getLog(PullServerAuxService.class); public static final String SHUFFLE_MANAGE_OS_CACHE = "tajo.pullserver.manage.os.cache"; public static final boolean DEFAULT_SHUFFLE_MANAGE_OS_CACHE = true; public static final String SHUFFLE_READAHEAD_BYTES = "tajo.pullserver.readahead.bytes"; public static final int DEFAULT_SHUFFLE_READAHEAD_BYTES = 4 * 1024 * 1024; private int port; private ChannelFactory selector; private final ChannelGroup accepted = new DefaultChannelGroup(); private HttpPipelineFactory pipelineFact; private int sslFileBufferSize; private ApplicationId appId; private QueryId queryId; private FileSystem localFS; /** * Should the shuffle use posix_fadvise calls to manage the OS cache during * sendfile */ private boolean manageOsCache; private int readaheadLength; private ReadaheadPool readaheadPool = ReadaheadPool.getInstance(); public static final String PULLSERVER_SERVICEID = "tajo.pullserver"; private static final Map<String,String> userRsrc = new ConcurrentHashMap<String,String>(); private static String userName; public static final String SUFFLE_SSL_FILE_BUFFER_SIZE_KEY = "tajo.pullserver.ssl.file.buffer.size"; public static final int DEFAULT_SUFFLE_SSL_FILE_BUFFER_SIZE = 60 * 1024; @Metrics(name="PullServerShuffleMetrics", about="PullServer output metrics", context="tajo") static class ShuffleMetrics implements ChannelFutureListener { @Metric({"OutputBytes","PullServer output in bytes"}) MutableCounterLong shuffleOutputBytes; @Metric({"Failed","# of failed shuffle outputs"}) MutableCounterInt shuffleOutputsFailed; @Metric({"Succeeded","# of succeeded shuffle outputs"}) MutableCounterInt shuffleOutputsOK; @Metric({"Connections","# of current shuffle connections"}) MutableGaugeInt shuffleConnections; @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { shuffleOutputsOK.incr(); } else { shuffleOutputsFailed.incr(); } shuffleConnections.decr(); } } final ShuffleMetrics metrics; PullServerAuxService(MetricsSystem ms) { super("httpshuffle"); metrics = ms.register(new ShuffleMetrics()); } @SuppressWarnings("UnusedDeclaration") public PullServerAuxService() { this(DefaultMetricsSystem.instance()); } /** * Serialize the shuffle port into a ByteBuffer for use later on. * @param port the port to be sent to the ApplciationMaster * @return the serialized form of the port. */ public static ByteBuffer serializeMetaData(int port) throws IOException { //TODO these bytes should be versioned DataOutputBuffer port_dob = new DataOutputBuffer(); port_dob.writeInt(port); return ByteBuffer.wrap(port_dob.getData(), 0, port_dob.getLength()); } /** * A helper function to deserialize the metadata returned by PullServerAuxService. * @param meta the metadata returned by the PullServerAuxService * @return the port the PullServer Handler is listening on to serve shuffle data. */ public static int deserializeMetaData(ByteBuffer meta) throws IOException { //TODO this should be returning a class not just an int DataInputByteBuffer in = new DataInputByteBuffer(); in.reset(meta); return in.readInt(); } @Override public void initApp(String user, ApplicationId appId, ByteBuffer secret) { // TODO these bytes should be versioned // TODO: Once SHuffle is out of NM, this can use MR APIs this.appId = appId; this.queryId = TajoIdUtils.parseQueryId(appId.toString()); this.userName = user; userRsrc.put(appId.toString(), user); } @Override public void stopApp(ApplicationId appId) { userRsrc.remove(appId.toString()); } @Override public synchronized void init(Configuration conf) { try { manageOsCache = conf.getBoolean(SHUFFLE_MANAGE_OS_CACHE, DEFAULT_SHUFFLE_MANAGE_OS_CACHE); readaheadLength = conf.getInt(SHUFFLE_READAHEAD_BYTES, DEFAULT_SHUFFLE_READAHEAD_BYTES); ThreadFactory bossFactory = new ThreadFactoryBuilder() .setNameFormat("PullServerAuxService Netty Boss #%d") .build(); ThreadFactory workerFactory = new ThreadFactoryBuilder() .setNameFormat("PullServerAuxService Netty Worker #%d") .build(); selector = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory)); localFS = new LocalFileSystem(); super.init(new Configuration(conf)); } catch (Throwable t) { LOG.error(t); } } // TODO change AbstractService to throw InterruptedException @Override public synchronized void start() { Configuration conf = getConfig(); ServerBootstrap bootstrap = new ServerBootstrap(selector); try { pipelineFact = new HttpPipelineFactory(conf); } catch (Exception ex) { throw new RuntimeException(ex); } bootstrap.setPipelineFactory(pipelineFact); port = conf.getInt(ConfVars.PULLSERVER_PORT.varname, ConfVars.PULLSERVER_PORT.defaultIntVal); Channel ch = bootstrap.bind(new InetSocketAddress(port)); accepted.add(ch); port = ((InetSocketAddress)ch.getLocalAddress()).getPort(); conf.set(ConfVars.PULLSERVER_PORT.varname, Integer.toString(port)); pipelineFact.PullServer.setPort(port); LOG.info(getName() + " listening on port " + port); super.start(); sslFileBufferSize = conf.getInt(SUFFLE_SSL_FILE_BUFFER_SIZE_KEY, DEFAULT_SUFFLE_SSL_FILE_BUFFER_SIZE); } public int getPort() { return port; } @Override public synchronized void stop() { try { accepted.close().awaitUninterruptibly(10, TimeUnit.SECONDS); ServerBootstrap bootstrap = new ServerBootstrap(selector); bootstrap.releaseExternalResources(); pipelineFact.destroy(); localFS.close(); } catch (Throwable t) { LOG.error(t); } finally { super.stop(); } } @Override public synchronized ByteBuffer getMeta() { try { return serializeMetaData(port); } catch (IOException e) { LOG.error("Error during getMeta", e); // TODO add API to AuxiliaryServices to report failures return null; } } class HttpPipelineFactory implements ChannelPipelineFactory { final PullServer PullServer; private SSLFactory sslFactory; public HttpPipelineFactory(Configuration conf) throws Exception { PullServer = new PullServer(conf); if (conf.getBoolean(ConfVars.SHUFFLE_SSL_ENABLED_KEY.varname, ConfVars.SHUFFLE_SSL_ENABLED_KEY.defaultBoolVal)) { sslFactory = new SSLFactory(SSLFactory.Mode.SERVER, conf); sslFactory.init(); } } public void destroy() { if (sslFactory != null) { sslFactory.destroy(); } } @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); if (sslFactory != null) { pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine())); } pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("chunking", new ChunkedWriteHandler()); pipeline.addLast("shuffle", PullServer); return pipeline; // TODO factor security manager into pipeline // TODO factor out encode/decode to permit binary shuffle // TODO factor out decode of index to permit alt. models } } class PullServer extends SimpleChannelUpstreamHandler { private final Configuration conf; private final LocalDirAllocator lDirAlloc = new LocalDirAllocator(ConfVars.WORKER_TEMPORAL_DIR.varname); private int port; public PullServer(Configuration conf) { this.conf = conf; this.port = conf.getInt(ConfVars.PULLSERVER_PORT.varname, ConfVars.PULLSERVER_PORT.defaultIntVal); } public void setPort(int port) { this.port = port; } private List<String> splitMaps(List<String> mapq) { if (null == mapq) { return null; } final List<String> ret = new ArrayList<String>(); for (String s : mapq) { Collections.addAll(ret, s.split(",")); } return ret; } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } // Parsing the URL into key-values final Map<String, List<String>> params = new QueryStringDecoder(request.getUri()).getParameters(); final List<String> types = params.get("type"); final List<String> taskIdList = params.get("ta"); final List<String> subQueryIds = params.get("sid"); final List<String> partitionIds = params.get("p"); if (types == null || taskIdList == null || subQueryIds == null || partitionIds == null) { sendError(ctx, "Required type, taskIds, subquery Id, and partition id", BAD_REQUEST); return; } if (types.size() != 1 || subQueryIds.size() != 1) { sendError(ctx, "Required type, taskIds, subquery Id, and partition id", BAD_REQUEST); return; } final List<FileChunk> chunks = Lists.newArrayList(); String repartitionType = types.get(0); String sid = subQueryIds.get(0); String partitionId = partitionIds.get(0); List<String> taskIds = splitMaps(taskIdList); // the working dir of tajo worker for each query String queryBaseDir = queryId + "/output" + "/"; LOG.info("PullServer request param: repartitionType=" + repartitionType + ", sid=" + sid + ", partitionId=" + partitionId + ", taskIds=" + taskIdList); String taskLocalDir = conf.get(ConfVars.WORKER_TEMPORAL_DIR.varname); if (taskLocalDir == null || taskLocalDir.equals("")) { LOG.error("Tajo local directory should be specified."); } LOG.info("PullServer baseDir: " + taskLocalDir + "/" + queryBaseDir); // if a subquery requires a range partitioning if (repartitionType.equals("r")) { String ta = taskIds.get(0); Path path = localFS.makeQualified( lDirAlloc.getLocalPathToRead(queryBaseDir + "/" + sid + "/" + ta + "/output/", conf)); String startKey = params.get("start").get(0); String endKey = params.get("end").get(0); boolean last = params.get("final") != null; FileChunk chunk; try { chunk = getFileCunks(path, startKey, endKey, last); } catch (Throwable t) { LOG.error("ERROR Request: " + request.getUri(), t); sendError(ctx, "Cannot get file chunks to be sent", BAD_REQUEST); return; } if (chunk != null) { chunks.add(chunk); } // if a subquery requires a hash repartition } else if (repartitionType.equals("h")) { for (String ta : taskIds) { Path path = localFS.makeQualified( lDirAlloc.getLocalPathToRead(queryBaseDir + "/" + sid + "/" + ta + "/output/" + partitionId, conf)); File file = new File(path.toUri()); FileChunk chunk = new FileChunk(file, 0, file.length()); chunks.add(chunk); } } else { LOG.error("Unknown repartition type: " + repartitionType); return; } // Write the content. Channel ch = e.getChannel(); if (chunks.size() == 0) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NO_CONTENT); ch.write(response); if (!isKeepAlive(request)) { ch.close(); } } else { FileChunk[] file = chunks.toArray(new FileChunk[chunks.size()]); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); long totalSize = 0; for (FileChunk chunk : file) { totalSize += chunk.length(); } setContentLength(response, totalSize); // Write the initial line and the header. ch.write(response); ChannelFuture writeFuture = null; for (FileChunk chunk : file) { writeFuture = sendFile(ctx, ch, chunk); if (writeFuture == null) { sendError(ctx, NOT_FOUND); return; } } // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. writeFuture.addListener(ChannelFutureListener.CLOSE); } } } private ChannelFuture sendFile(ChannelHandlerContext ctx, Channel ch, FileChunk file) throws IOException { RandomAccessFile spill; try { spill = new RandomAccessFile(file.getFile(), "r"); } catch (FileNotFoundException e) { LOG.info(file.getFile() + " not found"); return null; } ChannelFuture writeFuture; if (ch.getPipeline().get(SslHandler.class) == null) { final FadvisedFileRegionWrapper partition = new FadvisedFileRegionWrapper(spill, file.startOffset, file.length(), manageOsCache, readaheadLength, readaheadPool, file.getFile().getAbsolutePath()); writeFuture = ch.write(partition); writeFuture.addListener(new ChannelFutureListener() { // TODO error handling; distinguish IO/connection failures, // attribute to appropriate spill output @Override public void operationComplete(ChannelFuture future) { partition.releaseExternalResources(); } }); } else { // HTTPS cannot be done with zero copy. final FadvisedChunkedFile chunk = new FadvisedChunkedFile(spill, file.startOffset, file.length, sslFileBufferSize, manageOsCache, readaheadLength, readaheadPool, file.getFile().getAbsolutePath()); writeFuture = ch.write(chunk); } metrics.shuffleConnections.incr(); metrics.shuffleOutputBytes.incr(file.length); // optimistic return writeFuture; } private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { sendError(ctx, "", status); } private void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.setContent( ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8)); // Close the connection as soon as the error message is sent. ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Channel ch = e.getChannel(); Throwable cause = e.getCause(); if (cause instanceof TooLongFrameException) { sendError(ctx, BAD_REQUEST); return; } LOG.error("PullServer error: ", cause); if (ch.isConnected()) { LOG.error("PullServer error " + e); sendError(ctx, INTERNAL_SERVER_ERROR); } } } public FileChunk getFileCunks(Path outDir, String startKey, String endKey, boolean last) throws IOException { BSTIndex index = new BSTIndex(new TajoConf()); BSTIndex.BSTIndexReader idxReader = index.getIndexReader(new Path(outDir, "index")); idxReader.open(); Schema keySchema = idxReader.getKeySchema(); TupleComparator comparator = idxReader.getComparator(); LOG.info("BSTIndex is loaded from disk (" + idxReader.getFirstKey() + ", " + idxReader.getLastKey()); File data = new File(URI.create(outDir.toUri() + "/output")); byte [] startBytes = Base64.decodeBase64(startKey); byte [] endBytes = Base64.decodeBase64(endKey); RowStoreDecoder decoder = RowStoreUtil.createDecoder(keySchema); Tuple start; Tuple end; try { start = decoder.toTuple(startBytes); } catch (Throwable t) { throw new IllegalArgumentException("StartKey: " + startKey + ", decoded byte size: " + startBytes.length, t); } try { end = decoder.toTuple(endBytes); } catch (Throwable t) { throw new IllegalArgumentException("EndKey: " + endKey + ", decoded byte size: " + endBytes.length, t); } if(!comparator.isAscendingFirstKey()) { Tuple tmpKey = start; start = end; end = tmpKey; } LOG.info("GET Request for " + data.getAbsolutePath() + " (start="+start+", end="+ end + (last ? ", last=true" : "") + ")"); if (idxReader.getFirstKey() == null && idxReader.getLastKey() == null) { // if # of rows is zero LOG.info("There is no contents"); return null; } if (comparator.compare(end, idxReader.getFirstKey()) < 0 || comparator.compare(idxReader.getLastKey(), start) < 0) { LOG.info("Out of Scope (indexed data [" + idxReader.getFirstKey() + ", " + idxReader.getLastKey() + "], but request start:" + start + ", end: " + end); return null; } long startOffset; long endOffset; try { startOffset = idxReader.find(start); } catch (IOException ioe) { LOG.error("State Dump (the requested range: " + "[" + start + ", " + end +")" + ", idx min: " + idxReader.getFirstKey() + ", idx max: " + idxReader.getLastKey()); throw ioe; } try { endOffset = idxReader.find(end); if (endOffset == -1) { endOffset = idxReader.find(end, true); } } catch (IOException ioe) { LOG.error("State Dump (the requested range: " + "[" + start + ", " + end +")" + ", idx min: " + idxReader.getFirstKey() + ", idx max: " + idxReader.getLastKey()); throw ioe; } // if startOffset == -1 then case 2-1 or case 3 if (startOffset == -1) { // this is a hack // if case 2-1 or case 3 try { startOffset = idxReader.find(start, true); } catch (IOException ioe) { LOG.error("State Dump (the requested range: " + "[" + start + ", " + end +")" + ", idx min: " + idxReader.getFirstKey() + ", idx max: " + idxReader.getLastKey()); throw ioe; } } if (startOffset == -1) { throw new IllegalStateException("startOffset " + startOffset + " is negative \n" + "State Dump (the requested range: " + "[" + start + ", " + end +")" + ", idx min: " + idxReader.getFirstKey() + ", idx max: " + idxReader.getLastKey()); } // if greater than indexed values if (last || (endOffset == -1 && comparator.compare(idxReader.getLastKey(), end) < 0)) { endOffset = data.length(); } FileChunk chunk = new FileChunk(data, startOffset, endOffset - startOffset); LOG.info("Retrieve File Chunk: " + chunk); return chunk; } }
35.917169
108
0.669504
55560d6ccb57a5bc8c2c2a5798b54b24202e8ea7
1,929
package org.webharvest.gui.component; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; /** * Common popup menu. */ public class WHPopupMenu extends JPopupMenu { // single currently opened popup menu private static WHPopupMenu openPopup = null; public static WHPopupMenu getOpenPopup() { return openPopup; } private Map submenus = new LinkedHashMap(); public WHPopupMenu() { addPopupMenuListener(new PopupMenuListener() { public void popupMenuWillBecomeVisible(PopupMenuEvent e) { openPopup = WHPopupMenu.this; } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { openPopup = null; } public void popupMenuCanceled(PopupMenuEvent e) { } }); MenuElements.setPopupMenuLook(this); } public void show(Component invoker, int x, int y) { int lastCompIndex = getComponentCount() - 1; if (lastCompIndex >= 0) { Component lastComp = getComponent(lastCompIndex); if (lastComp instanceof JSeparator) { remove(lastCompIndex); } } super.show(invoker, x, y); } public void addSeparator() { int count = getComponentCount(); if (count == 0) { return; } int lastCompIndex = count - 1; if (lastCompIndex >= 0) { Component lastComp = getComponent(lastCompIndex); if (lastComp instanceof JSeparator) { return; } } JSeparator separator = new JSeparator(JSeparator.HORIZONTAL); add(separator); } }
28.367647
73
0.582685
b3d4f9803ef0e2edc1212853d1314acc9125dc97
1,209
public class Time extends ReplacedPlaybook { public synchronized boolean isComplete() { return Bases[29] != null; } public synchronized boolean ensureAppeals(Methods rifeSue) { if (Bases[0] == null) { return false; } for (int i = 0; i < Bases.length; i++) { if (Bases[i] == null) return false; if (Bases[i].canGetCycle() == rifeSue.goQuod() && rifeSue.fixOrders().peek().equals(Bases[i].catchIbid())) { return true; } } return false; } public synchronized void travelMouse() { live++; if (live == 30) live = 0; } public Chapter[] Bases = null; public int live = 0; public Time() { live = 0; this.Bases = new Chapter[30]; } protected synchronized void extendFolio(Chapter layout, Methods thisMethods) { if (Bases[live] == null) { Bases[live] = layout; this.travelMouse(); return; } while (Bases[live].canGetCycle() != thisMethods.goQuod() && Bases[live].fixLot() == 0) { if (Bases[live].canGetCycle() == thisMethods.goQuod()) { Bases[live].trancheAnticipate(); } travelMouse(); } Bases[live] = layout; travelMouse(); } }
20.491525
92
0.581472
6b08e92577f5b80be504e95c6155045d9dd5c687
5,474
/* * Copyright 2019 Arcus Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.iris.common.subsystem.lawnngarden.model.schedules; import static com.iris.messages.type.IrrigationScheduleStatus.ATTR_CONTROLLER; import static com.iris.messages.type.IrrigationScheduleStatus.ATTR_ENABLED; import static com.iris.messages.type.IrrigationScheduleStatus.ATTR_MODE; import static com.iris.messages.type.IrrigationScheduleStatus.ATTR_NEXTEVENT; import static com.iris.messages.type.IrrigationScheduleStatus.ATTR_SKIPPEDUNTIL; import java.util.Date; import java.util.Map; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.iris.common.subsystem.lawnngarden.util.LawnNGardenTypeUtil; import com.iris.common.subsystem.lawnngarden.util.Mapifiable; import com.iris.messages.address.Address; import com.iris.type.handler.TypeHandlerImpl; public class ScheduleStatus implements Mapifiable { private final ScheduleMode mode; private final Address controller; private final boolean enabled; private final Date skippedUntil; private final Transition nextTransition; private ScheduleStatus(ScheduleMode mode, Address controller, boolean enabled, Date skippedUntil, Transition nextTransition) { this.mode = mode; this.controller = controller; this.enabled = enabled; this.skippedUntil = skippedUntil; this.nextTransition = nextTransition; } public ScheduleMode mode() { return mode; } public Address controller() { return controller; } public boolean enabled() { return enabled; } public Date skippedUntil() { return skippedUntil; } public Transition nextTransition() { return nextTransition; } @Override public Map<String, Object> mapify() { ImmutableMap.Builder<String,Object> builder = ImmutableMap.<String,Object>builder() .put(ATTR_CONTROLLER, controller.getRepresentation()) .put(ATTR_ENABLED, enabled) .put(ATTR_MODE, mode.name()); if(nextTransition != null) { builder.put(ATTR_NEXTEVENT, nextTransition.mapify()); } if(skippedUntil != null) { builder.put(ATTR_SKIPPEDUNTIL, skippedUntil.getTime()); } return builder.build(); } public static class Builder { private ScheduleMode mode; private Address controller; private boolean enabled = false; private Date skippedUntil; private Transition nextTransition; private Builder() { } public Builder withMode(ScheduleMode mode) { this.mode = mode; return this; } public Builder withController(Address controller) { this.controller = controller; return this; } public Builder withEnabled(boolean enabled) { this.enabled = enabled; return this; } public Builder withSkippedUntil(Date skippedUntil) { this.skippedUntil = skippedUntil; return this; } public Builder withNextTransition(Transition nextTransition) { this.nextTransition = nextTransition; return this; } public ScheduleStatus build() { Preconditions.checkNotNull(mode); Preconditions.checkNotNull(controller); Date skip = skippedUntil == null ? null : (Date) skippedUntil.clone(); return new ScheduleStatus(mode, controller, enabled, skip, nextTransition); } } public static Builder builder() { return new Builder(); } public static Builder builder(ScheduleStatus status) { Builder builder = builder(); if(status != null) { builder .withController(status.controller()) .withEnabled(status.enabled()) .withMode(status.mode()) .withSkippedUntil(status.skippedUntil()) .withNextTransition(status.nextTransition()); } return builder; } @SuppressWarnings("serial") private static class TypeHandler extends TypeHandlerImpl<ScheduleStatus> { private TypeHandler() { super(ScheduleStatus.class, Map.class); } @SuppressWarnings("unchecked") @Override protected ScheduleStatus convert(Object value) { Map<String,Object> map = (Map<String, Object>) value; return ScheduleStatus.builder() .withController(LawnNGardenTypeUtil.address(map.get(ATTR_CONTROLLER))) .withEnabled(LawnNGardenTypeUtil.bool(map.get(ATTR_ENABLED))) .withMode(LawnNGardenTypeUtil.INSTANCE.coerce(ScheduleMode.class, map.get(ATTR_MODE))) .withNextTransition(LawnNGardenTypeUtil.transition(map.get(ATTR_NEXTEVENT))) .withSkippedUntil(LawnNGardenTypeUtil.date(map.get(ATTR_SKIPPEDUNTIL))) .build(); } } public static TypeHandler typeHandler() { return new TypeHandler(); } }
31.28
129
0.688162
8385f2068d871f216f35be4523267ee4a980adeb
9,863
package edu.sfsu.cs.orange.ocr; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import android.widget.TextView; import com.google.firebase.database.FirebaseDatabase; import android.view.View; import android.widget.Button; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import java.util.Random; public class Get_User_Data extends AppCompatActivity { private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); private DatabaseReference databaseReference = firebaseDatabase.getReference(); private Button Btn; private String user_Age; private String user_Diseases; private String user_Email; private String user_Medicine; private String user_Phone; private TextView textView_Email; private TextView textView_Age; private TextView textView_Phone; private TextView textView_Diseases; private TextView textView_Medicine; private ListView listview_pres; private String user_email; private String user_age; private String user_phone; private String user_diseases; private String user_medicine; private String pres_name; private String pres_time; //private String [] drug_list = new String[5]; private String user_db; private String user_info; private TextView textView1; private TextView textView2; private String[] user_DB = new String[8]; private int t; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_get__user__data); textView_Email = (TextView)findViewById(R.id.textview_email); textView_Age = (TextView)findViewById(R.id.textview2_age); textView_Phone = (TextView)findViewById(R.id.textview3_phone); textView_Diseases = (TextView)findViewById(R.id.textview4_diseases); textView_Medicine = (TextView)findViewById(R.id.textView5_medicine); //textView1 = (TextView)findViewById(R.id.textview_email); //textView2 = (TextView)findViewById(R.id.textview2_age); //final Random rando = new Random(); Btn = (Button)findViewById(R.id.btn_pls); Btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView_Email.setText(user_email); textView_Age.setText(user_age); textView_Phone.setText(user_phone); textView_Diseases.setText(user_diseases); textView_Medicine.setText(user_medicine); /* t = rando.nextInt(7); textView1.setText(user_Medicine); textView1.setText(user_Diseases); textView1.setText(user_Email); textView1.setText(user_Age); textView1.setText(user_db); textView2.setText(user_DB[t]); */ } }); databaseReference.child("user_db").orderByKey().equalTo("email").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { user_email = dataSnapshot.getValue().toString(); /* for(int t = 0;t<7;t++){ user_DB[t] = dataSnapshot.getValue().toString(); } */ } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); databaseReference.child("user_db").orderByKey().equalTo("age").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { user_age = dataSnapshot.getValue().toString(); //user_db = dataSnapshot.getValue().toString(); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); databaseReference.child("user_db").orderByKey().equalTo("phone").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { user_phone = dataSnapshot.getValue().toString(); //user_db = dataSnapshot.getValue().toString(); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); databaseReference.child("user_db").orderByKey().equalTo("diseases").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { user_diseases =dataSnapshot.getValue().toString(); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); databaseReference.child("user_db").orderByKey().equalTo("medicine").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { user_medicine = dataSnapshot.getValue().toString(); //user_db = dataSnapshot.getValue().toString(); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); databaseReference.child("Prescription").orderByKey().equalTo("Pres_name").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { pres_name = dataSnapshot.getValue().toString(); //user_db = dataSnapshot.getValue().toString(); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); databaseReference.child("Prescription").orderByKey().equalTo("Pres_time").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { pres_time = dataSnapshot.getValue().toString(); //user_db = dataSnapshot.getValue().toString(); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); // databaseReference.child("Prescription").orderByKey().equalTo("druglist").addChildEventListener(new ChildEventListener() { // @Override // public void onChildAdded(DataSnapshot dataSnapshot, String s) { // for(int i = 0 ; i< 5 ;i ++) // drug_list[i] = dataSnapshot.getValue().toString(); // //user_db = dataSnapshot.getValue().toString(); // } // // @Override // public void onChildChanged(DataSnapshot dataSnapshot, String s) { // // } // // @Override // public void onChildRemoved(DataSnapshot dataSnapshot) { // // } // // @Override // public void onChildMoved(DataSnapshot dataSnapshot, String s) { // // } // // @Override // public void onCancelled(DatabaseError databaseError) { // // } // }); } }
30.441358
131
0.600629
990b4c98b75041d65ab2298243d6576389452b08
1,024
package com.itgacl.magic4j.common.validator; import com.itgacl.magic4j.libcommon.exception.IncorrectParameterException; import java.util.UUID; public class Validator { public static void validateString(String val, String errorMessage) { if (val == null || val.isEmpty()) { throw new IncorrectParameterException(errorMessage); } } public static void validatePositiveNumber(long val, String errorMessage) { if (val <= 0) { throw new IncorrectParameterException(errorMessage); } } public static void validateId(UUID id, String errorMessage) { if (id == null) { throw new IncorrectParameterException(errorMessage); } } public static void validateId(Long id, String errorMessage) { if (id == null) { throw new IncorrectParameterException(errorMessage); } } public static void validateId(String id, String errorMessage) { validateString(id,errorMessage); } }
25.6
78
0.65625
d64eddc62ede9b410960b0d03a67ec7c2642fe28
4,492
package cz.nkp.urnnbn.services; import cz.nkp.urnnbn.core.*; import cz.nkp.urnnbn.core.dto.*; import cz.nkp.urnnbn.services.exceptions.ContentNotFoundException; import cz.nkp.urnnbn.services.exceptions.NotAdminException; import cz.nkp.urnnbn.services.exceptions.RegistrarScopeIdentifierNotDefinedException; import cz.nkp.urnnbn.services.exceptions.UnknownUserException; import org.joda.time.DateTime; import java.util.List; import java.util.Set; import java.util.logging.Logger; /** * TODO: zbavit se DatabaseException (resp. přeložit na RuntimeException) * * @author Martin Řehánek */ public interface DataAccessService extends BusinessService { static final Logger logger = Logger.getLogger(DataAccessService.class.getName()); public UrnNbnWithStatus urnByRegistrarCodeAndDocumentCode(RegistrarCode registrarCode, String documentCode, boolean withPredecessorsAndSuccessors); public DigitalDocument digDocByInternalId(long digDocId); public UrnNbn urnByDigDocId(long id, boolean withPredecessorsAndSuccessors); public List<RegistrarScopeIdentifier> registrarScopeIdentifiers(long digDocId); public RegistrarScopeIdentifier registrarScopeIdentifier(long digDocId, RegistrarScopeIdType type) throws RegistrarScopeIdentifierNotDefinedException; public Registrar registrarById(long id); public Archiver archiverById(long id); public List<Archiver> archivers(); public IntelectualEntity entityById(long id); public List<IntelectualEntity> entitiesByIdValue(String value); public List<IntelectualEntity> entitiesByIdValues(List<Long> ids); public List<IntEntIdentifier> intEntIdentifiersByIntEntId(long intEntId); // pokud nenajde, vrati null public Publication publicationByIntEntId(long intEntId); // pokud nenajde, vrati null public Originator originatorByIntEntId(long intEntId); // pokud nenajde, vrati null public SourceDocument sourceDocumentByIntEntId(long intEntId); public Registrar registrarByCode(RegistrarCode code); public List<DigitalLibrary> librariesByRegistrarId(long registrarId); public List<Catalog> catalogsByRegistrarId(long registrarId); public List<Catalog> catalogs(); public List<Registrar> registrars(); public int digitalDocumentsCount(long registrarId); public DigitalDocument digDocByIdentifier(RegistrarScopeIdentifier id); public List<DigitalDocument> digDocsByIsbn(String isbn); public List<DigitalDocument> digDocsByIssn(String issn); public List<DigitalDocument> digDocsOfIntEnt(long intEntId); public List<DigitalDocument> digDocsByModificationDate(DateTime from, DateTime until); public long digitalInstancesCount(); public DigitalInstance digInstanceByInternalId(long id); public List<DigitalInstance> digInstancesByDigDocId(long digDocId); public List<DigitalInstance> digInstancesByUrl(String url); public DigitalLibrary libraryByInternalId(long libraryId); /** * @param login login of user performing this operation * @return * @throws UnknownUserException * @throws NotAdminException */ public List<User> users(String login) throws UnknownUserException, NotAdminException; /** * @param login login of user that is being lookuped * @return * @throws UnknownUserException */ public User userByLogin(String login) throws UnknownUserException; /** * @param userId * @param login login of user performing this operation * @return * @throws UnknownUserException * @throws NotAdminException */ public List<Registrar> registrarsManagedByUser(long userId, String login) throws UnknownUserException, NotAdminException; public Set<UrnNbn> urnNbnsOfChangedRecords(DateTime from, DateTime until); public Set<UrnNbn> urnNbnsOfChangedRecordsOfRegistrar(Registrar registrar, DateTime from, DateTime until); public List<UrnNbn> urnNbnsOfRegistrar(RegistrarCode registrarCode); public Content contentByNameAndLanguage(String name, String language) throws ContentNotFoundException; public List<UrnNbnExport> selectByCriteria(String languageCode, UrnNbnExportFilter filter, boolean withDigitalInstances); public List<DiExport> listDiExport(List<String> registrarCodes, List<String> entityTypes, boolean includeUrnActive, boolean includeUrnDeactivated, boolean includeDiActive, boolean includeDiDeactivated); }
35.09375
151
0.776046
be3428c202ebb34404ab4bdc15531059e35b4927
145
package org.shujito.cartonbox.view.listener; public interface TagListItemSelectedCallback { public void tagListItemSelected(String tag); }
24.166667
46
0.813793
7c2be9fe44ba78b7789b44fd645265b3e6940f9e
13,648
/* * 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.cassandra.db; import java.security.MessageDigest; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.Arrays; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.db.context.CounterContext; import static org.apache.cassandra.db.context.CounterContext.ContextState; import org.apache.cassandra.io.util.DataOutputBuffer; import org.apache.cassandra.utils.*; public class CounterColumnTest extends SchemaLoader { private static final CounterContext cc = new CounterContext(); private static final int idLength; private static final int clockLength; private static final int countLength; private static final int stepLength; static { idLength = CounterId.LENGTH; clockLength = 8; // size of long countLength = 8; // size of long stepLength = idLength + clockLength + countLength; } @Test public void testCreate() throws UnknownHostException { long delta = 3L; CounterUpdateColumn cuc = new CounterUpdateColumn(ByteBufferUtil.bytes("x"), delta, 1L); CounterColumn column = cuc.localCopy(Keyspace.open("Keyspace5").getColumnFamilyStore("Counter1")); assert delta == column.total(); assert 1 == column.value().getShort(0); assert 0 == column.value().getShort(2); assert CounterId.wrap(column.value(), 4).isLocalId(); assert 1L == column.value().getLong(4 + 0*stepLength + idLength); assert delta == column.value().getLong(4 + 0*stepLength + idLength + clockLength); } @Test public void testReconcile() throws UnknownHostException { Column left; Column right; Column reconciled; ByteBuffer context; // tombstone + tombstone left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 1L); right = new DeletedColumn(ByteBufferUtil.bytes("x"), 2, 2L); assert left.reconcile(right).getMarkedForDeleteAt() == right.getMarkedForDeleteAt(); assert right.reconcile(left).getMarkedForDeleteAt() == right.getMarkedForDeleteAt(); // tombstone > live left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 2L); right = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 1L); assert left.reconcile(right) == left; // tombstone < live last delete left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 1L); right = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 4L, 2L); assert left.reconcile(right) == right; // tombstone == live last delete left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 2L); right = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 4L, 2L); assert left.reconcile(right) == right; // tombstone > live last delete left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 4L); right = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 9L, 1L); reconciled = left.reconcile(right); assert reconciled.name() == right.name(); assert reconciled.value() == right.value(); assert reconciled.timestamp() == right.timestamp(); assert ((CounterColumn)reconciled).timestampOfLastDelete() == left.getMarkedForDeleteAt(); // live < tombstone left = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 1L); right = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 2L); assert left.reconcile(right) == right; // live last delete > tombstone left = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 4L, 2L); right = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 1L); assert left.reconcile(right) == left; // live last delete == tombstone left = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 4L, 2L); right = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 2L); assert left.reconcile(right) == left; // live last delete < tombstone left = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 9L, 1L); right = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 4L); reconciled = left.reconcile(right); assert reconciled.name() == left.name(); assert reconciled.value() == left.value(); assert reconciled.timestamp() == left.timestamp(); assert ((CounterColumn)reconciled).timestampOfLastDelete() == right.getMarkedForDeleteAt(); // live < live last delete left = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(CounterId.fromInt(1), 2L, 3L, false), 1L, Long.MIN_VALUE); right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(CounterId.fromInt(1), 1L, 1L, false), 4L, 3L); assert left.reconcile(right) == right; // live last delete > live left = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(CounterId.fromInt(1), 2L, 3L, false), 6L, 5L); right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(CounterId.fromInt(1), 1L, 1L, false), 4L, 3L); assert left.reconcile(right) == left; // live + live left = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(CounterId.fromInt(1), 1L, 1L, false), 4L, Long.MIN_VALUE); right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(CounterId.fromInt(1), 2L, 3L, false), 1L, Long.MIN_VALUE); reconciled = left.reconcile(right); assert reconciled.name().equals(left.name()); assert ((CounterColumn)reconciled).total() == 3L; assert reconciled.timestamp() == 4L; left = reconciled; right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(CounterId.fromInt(2), 1L, 5L, false), 2L, Long.MIN_VALUE); reconciled = left.reconcile(right); assert reconciled.name().equals(left.name()); assert ((CounterColumn)reconciled).total() == 8L; assert reconciled.timestamp() == 4L; left = reconciled; right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(CounterId.fromInt(2), 2L, 2L, false), 6L, Long.MIN_VALUE); reconciled = left.reconcile(right); assert reconciled.name().equals(left.name()); assert ((CounterColumn)reconciled).total() == 5L; assert reconciled.timestamp() == 6L; context = reconciled.value(); int hd = 2; // header assert hd + 2 * stepLength == context.remaining(); assert Util.equalsCounterId(CounterId.fromInt(1), context, hd + 0 * stepLength); assert 2L == context.getLong(hd + 0*stepLength + idLength); assert 3L == context.getLong(hd + 0*stepLength + idLength + clockLength); assert Util.equalsCounterId(CounterId.fromInt(2), context, hd + 1 * stepLength); assert 2L == context.getLong(hd + 1*stepLength + idLength); assert 2L == context.getLong(hd + 1*stepLength + idLength + clockLength); assert ((CounterColumn)reconciled).timestampOfLastDelete() == Long.MIN_VALUE; } @Test public void testDiff() throws UnknownHostException { Allocator allocator = HeapAllocator.instance; ContextState left; ContextState right; CounterColumn leftCol; CounterColumn rightCol; // timestamp leftCol = new CounterColumn(ByteBufferUtil.bytes("x"), 0, 1L); rightCol = new CounterColumn(ByteBufferUtil.bytes("x"), 0, 2L); assert rightCol == leftCol.diff(rightCol); assert null == rightCol.diff(leftCol); // timestampOfLastDelete leftCol = new CounterColumn(ByteBufferUtil.bytes("x"), 0, 1L, 1L); rightCol = new CounterColumn(ByteBufferUtil.bytes("x"), 0, 1L, 2L); assert rightCol == leftCol.diff(rightCol); assert null == rightCol.diff(leftCol); // equality: equal nodes, all counts same left = ContextState.allocate(3, 0, allocator); left.writeElement(CounterId.fromInt(3), 3L, 0L); left.writeElement(CounterId.fromInt(6), 2L, 0L); left.writeElement(CounterId.fromInt(9), 1L, 0L); right = new ContextState(ByteBufferUtil.clone(left.context), 2); leftCol = new CounterColumn(ByteBufferUtil.bytes("x"), left.context, 1L); rightCol = new CounterColumn(ByteBufferUtil.bytes("x"), right.context, 1L); assert leftCol.diff(rightCol) == null; // greater than: left has superset of nodes (counts equal) left = ContextState.allocate(4, 0, allocator); left.writeElement(CounterId.fromInt(3), 3L, 0L); left.writeElement(CounterId.fromInt(6), 2L, 0L); left.writeElement(CounterId.fromInt(9), 1L, 0L); left.writeElement(CounterId.fromInt(12), 0L, 0L); right = ContextState.allocate(3, 0, allocator); right.writeElement(CounterId.fromInt(3), 3L, 0L); right.writeElement(CounterId.fromInt(6), 2L, 0L); right.writeElement(CounterId.fromInt(9), 1L, 0L); leftCol = new CounterColumn(ByteBufferUtil.bytes("x"), left.context, 1L); rightCol = new CounterColumn(ByteBufferUtil.bytes("x"), right.context, 1L); assert leftCol.diff(rightCol) == null; // less than: right has subset of nodes (counts equal) assert leftCol == rightCol.diff(leftCol); // disjoint: right and left have disjoint node sets left = ContextState.allocate(3, 0, allocator); left.writeElement(CounterId.fromInt(3), 1L, 0L); left.writeElement(CounterId.fromInt(4), 1L, 0L); left.writeElement(CounterId.fromInt(9), 1L, 0L); right = ContextState.allocate(3, 0, allocator); right.writeElement(CounterId.fromInt(3), 1L, 0L); right.writeElement(CounterId.fromInt(6), 1L, 0L); right.writeElement(CounterId.fromInt(9), 1L, 0L); leftCol = new CounterColumn(ByteBufferUtil.bytes("x"), left.context, 1L); rightCol = new CounterColumn(ByteBufferUtil.bytes("x"), right.context, 1L); assert rightCol == leftCol.diff(rightCol); assert leftCol == rightCol.diff(leftCol); } @Test public void testSerializeDeserialize() throws IOException { Allocator allocator = HeapAllocator.instance; CounterContext.ContextState state = CounterContext.ContextState.allocate(4, 2, allocator); state.writeElement(CounterId.fromInt(1), 4L, 4L); state.writeElement(CounterId.fromInt(2), 4L, 4L, true); state.writeElement(CounterId.fromInt(3), 4L, 4L); state.writeElement(CounterId.fromInt(4), 4L, 4L, true); CounterColumn original = new CounterColumn(ByteBufferUtil.bytes("x"), state.context, 1L); DataOutputBuffer bufOut = new DataOutputBuffer(); Column.serializer.serialize(original, bufOut); byte[] serialized = bufOut.getData(); ByteArrayInputStream bufIn = new ByteArrayInputStream(serialized, 0, serialized.length); CounterColumn deserialized = (CounterColumn) Column.serializer.deserialize(new DataInputStream(bufIn)); assert original.equals(deserialized); bufIn = new ByteArrayInputStream(serialized, 0, serialized.length); CounterColumn deserializedOnRemote = (CounterColumn) Column.serializer.deserialize(new DataInputStream(bufIn), ColumnSerializer.Flag.FROM_REMOTE); assert deserializedOnRemote.name().equals(original.name()); assert deserializedOnRemote.total() == original.total(); assert deserializedOnRemote.value().equals(cc.clearAllDelta(original.value())); assert deserializedOnRemote.timestamp() == deserialized.timestamp(); assert deserializedOnRemote.timestampOfLastDelete() == deserialized.timestampOfLastDelete(); } @Test public void testUpdateDigest() throws Exception { Allocator allocator = HeapAllocator.instance; MessageDigest digest1 = MessageDigest.getInstance("md5"); MessageDigest digest2 = MessageDigest.getInstance("md5"); CounterContext.ContextState state = CounterContext.ContextState.allocate(4, 2, allocator); state.writeElement(CounterId.fromInt(1), 4L, 4L); state.writeElement(CounterId.fromInt(2), 4L, 4L, true); state.writeElement(CounterId.fromInt(3), 4L, 4L); state.writeElement(CounterId.fromInt(4), 4L, 4L, true); CounterColumn original = new CounterColumn(ByteBufferUtil.bytes("x"), state.context, 1L); CounterColumn cleared = new CounterColumn(ByteBufferUtil.bytes("x"), cc.clearAllDelta(state.context), 1L); original.updateDigest(digest1); cleared.updateDigest(digest2); assert Arrays.equals(digest1.digest(), digest2.digest()); } }
42.918239
154
0.668889
cd580948ea1a8371b73581add1e48e134ee00781
1,320
package com.us.example.service; import com.us.example.bean.Person; import com.us.example.dao.PersonRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.stereotype.Service; /** * Created by yangyibo on 17/3/2. */ @Service public class PersonService { @Autowired CacheManager cacheManager; @Autowired private PersonRepository personRepository; public Person findOne(Long id) { Person person = getCache(id, cacheManager); if (person != null) { System.out.println("从缓存中取出:" + person.toString()); } else { person = personRepository.findOne(id); System.out.println("从数据库中取出:" + person.toString()); } return person; } public Person save(Person person) { Person p = personRepository.save(person); return p; } public Person getCache(Long id, CacheManager cacheManager) { // Person person=(Person) cacheManager.getCache(id.toString()).get(id).get(); Cache cache = cacheManager.getCache(id.toString()); Cache.ValueWrapper valueWrapper = cache.get(id); Person person = (Person) valueWrapper.get(); return person; } }
26.4
79
0.671212
74016245c3378210f6d646729fa7e1afe8af93e9
381
package github.gx.jumptable.dto; import lombok.Data; /** * @program: RedisGrowUp * @description: 跳表每层后置节点维护对象 * @author: gaoxiang * @email: 630268696@qq.com * @create: 2021-03-11 16:01 **/ @Data public class JumpFloorNode { /** * 下一个节点引用地址 */ private JumpNode forwardNode; /** * 当前节点 与 下个节点之间的节点个数,记录跳过了多少个节点 */ private int spanNum; }
15.24
36
0.632546
9976c33b97c640486296b58a8dccedb5d3ff3577
3,887
// Copyright (c) 2017, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.compatproguard; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import com.android.tools.r8.code.ConstString; import com.android.tools.r8.code.InvokeStatic; import com.android.tools.r8.code.ReturnVoid; import com.android.tools.r8.graph.DexCode; import com.android.tools.r8.smali.SmaliBuilder; import com.android.tools.r8.utils.AndroidApiLevel; import com.android.tools.r8.utils.codeinspector.ClassSubject; import com.android.tools.r8.utils.codeinspector.CodeInspector; import com.android.tools.r8.utils.codeinspector.MethodSubject; import org.junit.Test; public class ForNameTest extends CompatProguardSmaliTestBase { private final String CLASS_NAME = "Example"; private final static String BOO = "Boo"; @Test public void forName_renamed() throws Exception { SmaliBuilder builder = new SmaliBuilder(CLASS_NAME); builder.addMainMethod( 1, "const-string v0, \"" + BOO + "\"", "invoke-static {v0}, Ljava/lang/Class;->forName(Ljava/lang/String;)Ljava/lang/Class;", "move-result-object v0", "return-void"); builder.addClass(BOO); CodeInspector inspector = runCompatProguard( builder, testBuilder -> testBuilder .addKeepMainRule(CLASS_NAME) // Add main dex rule to disable Class.forName() optimization. .addMainDexRules("-keep class " + CLASS_NAME) .noOptimization() .noTreeShaking() .setMinApi(AndroidApiLevel.B)); ClassSubject clazz = inspector.clazz(CLASS_NAME); assertTrue(clazz.isPresent()); MethodSubject method = clazz.method(CodeInspector.MAIN); assertTrue(method.isPresent()); DexCode code = method.getMethod().getCode().asDexCode(); assertTrue(code.instructions[0] instanceof ConstString); ConstString constString = (ConstString) code.instructions[0]; assertNotEquals(BOO, constString.getString().toString()); assertTrue(code.instructions[1] instanceof InvokeStatic); assertTrue(code.instructions[2] instanceof ReturnVoid); } @Test public void forName_noMinification() throws Exception { SmaliBuilder builder = new SmaliBuilder(CLASS_NAME); builder.addMainMethod( 1, "const-string v0, \"" + BOO + "\"", "invoke-static {v0}, Ljava/lang/Class;->forName(Ljava/lang/String;)Ljava/lang/Class;", "move-result-object v0", "return-void"); builder.addClass(BOO); CodeInspector inspector = runCompatProguard( builder, testBuilder -> testBuilder .addKeepMainRule(CLASS_NAME) // Add main dex rule to disable Class.forName() optimization. .addMainDexRules("-keep class " + CLASS_NAME) .noOptimization() .noMinification() .noTreeShaking() .setMinApi(AndroidApiLevel.B)); ClassSubject clazz = inspector.clazz(CLASS_NAME); assertTrue(clazz.isPresent()); MethodSubject method = clazz.method(CodeInspector.MAIN); assertTrue(method.isPresent()); DexCode code = method.getMethod().getCode().asDexCode(); assertTrue(code.instructions[0] instanceof ConstString); ConstString constString = (ConstString) code.instructions[0]; assertEquals(BOO, constString.getString().toString()); assertTrue(code.instructions[1] instanceof InvokeStatic); assertTrue(code.instructions[2] instanceof ReturnVoid); } }
38.87
94
0.674813
dc92ecdb0676fda28f0945fe725e60ddf0401950
4,520
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import java.io.IOException; import javax.naming.ConfigurationException; public final class Config { //constants public static final String DEFAULT_DBPORT = "3306"; public static final int DEFAULT_RCONPORT = 28960; public static final int DEFAULT_LISTENPORT = 21300; // database variables /** * database hostname */ private static String dbHost; /** * database user name */ private static String dbUser; /** * database password */ private static String dbPassword; /** * database port, defaults to 3306 */ private static String dbPort; /** * database name to access */ private static String database; // gameserver variables /** * rcon password for the gameserver */ private static String rconPassword; /** * server port used by the gameserver. Default 28960 */ private static int serverPort; /** * hostname of the gameserver */ private static String serverHost; /** * port number that this application will listen on */ private static int listenPort; public static void init(String fileName) throws NumberFormatException, IOException, ConfigurationException { Properties props = new Properties(); InputStream is = new FileInputStream(fileName); props.load(is); dbHost = props.getProperty("db_host"); dbUser = props.getProperty("db_user"); dbPassword = props.getProperty("db_password"); database = props.getProperty("database"); dbPort = props.getProperty("db_port"); rconPassword = props.getProperty("rcon_password"); serverPort = Integer.parseInt(props.getProperty("server_port")); serverHost = props.getProperty("server_host"); listenPort = Integer.parseInt(props.getProperty("listen_port")); checkValues(); } // some settings can be blank, and we can assign defaults // others we absolutely need (ex serverHost, dbHost) public static void checkValues() throws ConfigurationException { /* REQUIRED settings for database */ String message = " configuration property is required. Shutting down program..."; if (dbHost == null || dbHost.equals("")) { throw new ConfigurationException("db_host" + message); } if (dbUser == null || dbUser.equals("")) { throw new ConfigurationException("db_user" + message); } if (dbPassword == null || dbPassword.equals("")) { throw new ConfigurationException("db_password" + message); } if (database == null || database.equals("")) { throw new ConfigurationException("database" + message); } /* Optional settings for database. If not initialized, do it here */ if (dbPort == null || dbPort.equals("")) { dbPort = DEFAULT_DBPORT; } /* REQUIRED settings for the gameserver */ if (rconPassword == null || rconPassword.equals("")) { throw new ConfigurationException("rcon_password" + message); } if (serverHost == null || serverHost.equals("")) { throw new ConfigurationException("server_host" + message); } /* Optional settings for the gameserver. */ if (serverPort == 0) { serverPort = DEFAULT_RCONPORT; } if (listenPort == 0) { listenPort = DEFAULT_LISTENPORT; } } //jdbc:mysql://<dbHost>:<dbPort>/<database> public static String getDatabaseUrl() { String str = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + database; return str; } public static String getDatabase() { return database; } public static String getRconPassword() { return rconPassword; } public static String getServerHost() { return serverHost; } public static int getServerPort() { return serverPort; } public static int getListenPort() { return listenPort; } public static String getDatabaseUser() { return dbUser; } public static String getDatabasePassword() { return dbPassword; } }
26.432749
110
0.603761
78a48110043a42e343b4eea62da78102a314e126
4,103
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.simpleinstruments.pricing; import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve; /** * Market data requirements for pricing the SimpleFuture and EquityFuture. * <p> * NOTE: Each EquityFuturesPricingMethod requires different data. Some members of the data bundle may be null! */ public class SimpleFutureDataBundle { private final YieldAndDiscountCurve _fundingCurve; /** MARK_TO_MARKET */ private final Double _marketPrice; /** DIVIDEND_YIELD */ private final Double _spotValue; private final Double _dividendYield; /** COST_OF_CARRY */ private final Double _costOfCarry; /** * @param fundingCurve * Used for discounting * @param marketPrice * Quoted futures price * @param spotValue * Quoted market spot value of the underlying * @param dividendYield * An estimate of the continuous dividend yield over the life of the future * @param costOfCarry * An estimate of the cost of carry, as a rate =&gt; FwdPrice = Spot * exp(costOfCarry * T) */ public SimpleFutureDataBundle(final YieldAndDiscountCurve fundingCurve, final Double marketPrice, final Double spotValue, final Double dividendYield, final Double costOfCarry) { _fundingCurve = fundingCurve; _marketPrice = marketPrice; _spotValue = spotValue; _dividendYield = dividendYield; _costOfCarry = costOfCarry; } /** * Gets the fundingCurve. * * @return the fundingCurve */ public final YieldAndDiscountCurve getFundingCurve() { return _fundingCurve; } /** * Gets the marketPrice. * * @return the marketPrice */ public final Double getMarketPrice() { return _marketPrice; } /** * Gets the spotValue. * * @return the spotValue */ public final Double getSpotValue() { return _spotValue; } /** * Gets the dividendYield. * * @return the dividendYield */ public final Double getDividendYield() { return _dividendYield; } /** * Gets the costOfCarry. * * @return the costOfCarry */ public final Double getCostOfCarry() { return _costOfCarry; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (_costOfCarry == null ? 0 : _costOfCarry.hashCode()); result = prime * result + (_dividendYield == null ? 0 : _dividendYield.hashCode()); result = prime * result + (_fundingCurve == null ? 0 : _fundingCurve.hashCode()); result = prime * result + (_marketPrice == null ? 0 : _marketPrice.hashCode()); result = prime * result + (_spotValue == null ? 0 : _spotValue.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof SimpleFutureDataBundle)) { return false; } final SimpleFutureDataBundle other = (SimpleFutureDataBundle) obj; if (_costOfCarry == null) { if (other._costOfCarry != null) { return false; } } else if (!_costOfCarry.equals(other._costOfCarry)) { return false; } if (_dividendYield == null) { if (other._dividendYield != null) { return false; } } else if (!_dividendYield.equals(other._dividendYield)) { return false; } if (_fundingCurve == null) { if (other._fundingCurve != null) { return false; } } else if (!_fundingCurve.equals(other._fundingCurve)) { return false; } if (_marketPrice == null) { if (other._marketPrice != null) { return false; } } else if (!_marketPrice.equals(other._marketPrice)) { return false; } if (_spotValue == null) { if (other._spotValue != null) { return false; } } else if (!_spotValue.equals(other._spotValue)) { return false; } return true; } }
26.301282
151
0.649037
afcea064586b48c118bf6866a4b5e4676ba3c3c1
3,352
__________________________________________________________________________________________________ sample 1 ms submission class Solution { public boolean splitArraySameAverage(int[] A) { return useDFS(A); } private boolean useDFS(int[] a) { int n = a.length; // claculate the total sum int sum = getSum(a); // check possibility // sum / n == sum1 / k == sum2 / (n - k) // k is number of elements, k <= n / 2 // if possible, there should be some k where (sum * k % n) is 0 if (!isPossible(a, sum)) { return false; } Arrays.sort(a); // i is number of elements for (int i = 1; i <= n / 2; ++i) { // ensure possibility if (sum * i % n == 0 && dfs(a, sum * i / n, i, 0)) { return true; } } return false; } private boolean dfs(int[] a, int remainingSum, int curNum, int start) { if (curNum == 0) { // no available element // check remainingSum return remainingSum == 0; } if (a[start] > remainingSum / curNum) { // the starting element already exceeds the average in an increasing subarray return false; } // ensure there are (curNum - 1) elements for the next round for (int i = start; i < a.length - curNum + 1; ++i) { if (i > start && a[i] == a[i - 1]) { // de-dupe continue; } // update remainingSum, curNum and starting index if (dfs(a, remainingSum - a[i], curNum - 1, i + 1)) { return true; } } return false; } private boolean isPossible(int[] a, int sum) { int n = a.length; boolean possible = false; for (int i = 1; i <= n / 2 && !possible; ++i) { if (sum * i % n == 0) { possible = true; break; } } return possible; } private int getSum(int[] a) { int sum = 0; for (int i : a) { sum += i; } return sum; } } __________________________________________________________________________________________________ sample 35372 kb submission class Solution { public boolean check(int[] A, int leftSum, int leftNum, int startIndex) { if (leftNum == 0) return leftSum == 0; if ((A[startIndex]) > leftSum / leftNum) return false; for (int i = startIndex; i < A.length - leftNum + 1; i ++) { if (i > startIndex && A[i] == A[i - 1]) continue; if (check(A, leftSum - A[i], leftNum - 1, i + 1)) return true; } return false; } public boolean splitArraySameAverage(int[] A) { if (A.length == 1) return false; int sumA = 0; for (int a: A) sumA += a; Arrays.sort(A); for (int lenOfB = 1; lenOfB <= A.length / 2; lenOfB ++) { if ((sumA * lenOfB) % A.length == 0) { if (check(A, (sumA * lenOfB) / A.length, lenOfB, 0)) return true; } } return false; } } __________________________________________________________________________________________________
32.862745
98
0.507458
fd6d4a712670c66124b141f18efc4a34669908f6
704
package com.example.wyattfraley.golftracker; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import java.util.List; @Dao public interface ScoreEntryDao { @Query("SELECT * FROM ScoreEntry") List<ScoreEntry> getAll(); @Query("Select uId, finalscore, parPlayed FROM ScoreEntry") List<ScoreEntryDisplayRound> getRoundsForDisplay(); @Query("SELECT * FROM ScoreEntry WHERE uid IS (:userID)") ScoreEntry loadSingleRound(String userID); @Insert void insertAll(ScoreEntry... ScoreEntries); @Delete void delete(ScoreEntry MyScoreEntry); }
26.074074
63
0.752841
4ce7ecabb8b5bcffcd0e4b41879befb4ab9d60b2
7,883
package seedu.address.model.application; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.testutil.Assert.assertThrows; import static seedu.address.testutil.TypicalApplications.AMAZON; import static seedu.address.testutil.TypicalApplications.BYTEDANCE; import static seedu.address.testutil.TypicalApplications.GRAB; import static seedu.address.testutil.TypicalApplications.getTypicalInternship; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import seedu.address.model.application.exceptions.ApplicationNotFoundException; import seedu.address.model.application.exceptions.DuplicateApplicationException; import seedu.address.testutil.ApplicationBuilder; public class UniqueApplicationListTest { private final UniqueApplicationList uniqueApplicationList = new UniqueApplicationList(); @Test public void contains_nullApplication_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueApplicationList.contains(null)); } @Test public void contains_applicationNotInList_returnsFalse() { assertFalse(uniqueApplicationList.contains(AMAZON)); } @Test public void contains_applicationInList_returnsTrue() { uniqueApplicationList.add(AMAZON); assertTrue(uniqueApplicationList.contains(AMAZON)); } @Test public void contains_applicationWithSameIdentityFieldsInList_returnsTrue() { uniqueApplicationList.add(AMAZON); Application editedAlice = new ApplicationBuilder(AMAZON) .build(); assertTrue(uniqueApplicationList.contains(editedAlice)); } @Test public void add_nullApplication_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueApplicationList.add(null)); } @Test public void add_duplicateApplication_throwsDuplicateApplicationException() { uniqueApplicationList.add(AMAZON); assertThrows(DuplicateApplicationException.class, () -> uniqueApplicationList.add(AMAZON)); } @Test public void setApplication_nullTargetApplication_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueApplicationList.setApplication(null, AMAZON)); } @Test public void setApplication_nullEditedApplication_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueApplicationList.setApplication(AMAZON, null)); } @Test public void setApplication_targetApplicationNotInList_throwsApplicationNotFoundException() { assertThrows(ApplicationNotFoundException.class, () -> uniqueApplicationList.setApplication(AMAZON, AMAZON)); } @Test public void setApplication_editedApplicationIsSameApplication_success() { uniqueApplicationList.add(AMAZON); uniqueApplicationList.setApplication(AMAZON, AMAZON); UniqueApplicationList expectedUniqueApplicationList = new UniqueApplicationList(); expectedUniqueApplicationList.add(AMAZON); assertEquals(expectedUniqueApplicationList, uniqueApplicationList); } @Test public void setApplication_editedApplicationHasSameIdentity_success() { uniqueApplicationList.add(AMAZON); Application editedAlice = new ApplicationBuilder(AMAZON) .build(); uniqueApplicationList.setApplication(AMAZON, editedAlice); UniqueApplicationList expectedUniqueApplicationList = new UniqueApplicationList(); expectedUniqueApplicationList.add(editedAlice); assertEquals(expectedUniqueApplicationList, uniqueApplicationList); } @Test public void setApplication_editedApplicationHasDifferentIdentity_success() { uniqueApplicationList.add(AMAZON); uniqueApplicationList.setApplication(AMAZON, BYTEDANCE); UniqueApplicationList expectedUniqueApplicationList = new UniqueApplicationList(); expectedUniqueApplicationList.add(BYTEDANCE); assertEquals(expectedUniqueApplicationList, uniqueApplicationList); } @Test public void setApplication_editedApplicationHasNonUniqueIdentity_throwsDuplicateApplicationException() { uniqueApplicationList.add(AMAZON); uniqueApplicationList.add(BYTEDANCE); assertThrows(DuplicateApplicationException.class, () -> uniqueApplicationList.setApplication( AMAZON, BYTEDANCE)); } @Test public void remove_nullApplication_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueApplicationList.remove(null)); } @Test public void remove_applicationDoesNotExist_throwsApplicationNotFoundException() { assertThrows(ApplicationNotFoundException.class, () -> uniqueApplicationList.remove(AMAZON)); } @Test public void remove_existingApplication_removesApplication() { uniqueApplicationList.add(AMAZON); uniqueApplicationList.remove(AMAZON); UniqueApplicationList expectedUniqueApplicationList = new UniqueApplicationList(); assertEquals(expectedUniqueApplicationList, uniqueApplicationList); } @Test public void setApplications_nullUniqueApplicationList_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueApplicationList .setApplications((UniqueApplicationList) null)); } @Test public void setApplications_uniqueApplicationList_replacesOwnListWithProvidedUniqueApplicationList() { uniqueApplicationList.add(AMAZON); UniqueApplicationList expectedUniqueApplicationList = new UniqueApplicationList(); expectedUniqueApplicationList.add(BYTEDANCE); uniqueApplicationList.setApplications(expectedUniqueApplicationList); assertEquals(expectedUniqueApplicationList, uniqueApplicationList); } @Test public void setApplications_nullList_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueApplicationList.setApplications((List<Application>) null)); } @Test public void setApplications_list_replacesOwnListWithProvidedList() { uniqueApplicationList.add(AMAZON); List<Application> applicationList = Collections.singletonList(BYTEDANCE); uniqueApplicationList.setApplications(applicationList); UniqueApplicationList expectedUniqueApplicationList = new UniqueApplicationList(); expectedUniqueApplicationList.add(BYTEDANCE); assertEquals(expectedUniqueApplicationList, uniqueApplicationList); } @Test public void setApplications_listWithDuplicateApplications_throwsDuplicateApplicationException() { List<Application> listWithDuplicateApplications = Arrays.asList(AMAZON, AMAZON); assertThrows(DuplicateApplicationException.class, () -> uniqueApplicationList .setApplications(listWithDuplicateApplications)); } @Test public void asUnmodifiableObservableList_modifyList_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> uniqueApplicationList.asUnmodifiableObservableList().remove(0)); } @Test public void equals() { // same object -> return true assertTrue(uniqueApplicationList.equals(uniqueApplicationList)); // null -> return false assertFalse(uniqueApplicationList.equals(null)); } @Test public void toHashCode_success() { uniqueApplicationList.add(AMAZON); uniqueApplicationList.add(BYTEDANCE); uniqueApplicationList.add(GRAB); assertEquals(getTypicalInternship().hashCode(), uniqueApplicationList.hashCode()); } }
41.272251
120
0.761639
b349e4ecfa1d1443009fef9463b91f8c7a8b1f0b
3,273
package ru.romashov.blogapp.tests.repositories; 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.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import ru.romashov.blogapp.model.Tag; import ru.romashov.blogapp.repositories.TagsRepository; import javax.validation.ConstraintViolationException; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @DataJpaTest @TestPropertySource(locations = "classpath:application-test.yml") public class TagRepositoryTests { /** * IMPORTANT: Do not forget to add .env variables into your configuration * in case of testing each individual test */ @Autowired private TagsRepository tagsRepository; private Tag tag; @Before public void init() { tag = new Tag(); tag.setName("Hot"); } @Test public void testSaveAndGetTag() { assertNotNull(tag); Tag savedTag = tagsRepository.save(tag); assertNotNull(savedTag); Tag tagFromDB = tagsRepository.findById(savedTag.getId()).orElse(null); assertNotNull(tagFromDB); assertEquals(savedTag.getName(), tagFromDB.getName()); assertEquals(0, tagFromDB.getPosts().size()); } @Test public void testDeleteTag() { assertNotNull(tag); Tag savedTag = tagsRepository.save(tag); assertNotNull(savedTag); tagsRepository.delete(tag); Tag deletedTag = tagsRepository.findById(savedTag.getId()).orElse(null); assertNull(deletedTag); } @Test(expected = EmptyResultDataAccessException.class) public void testDeleteNonExistentTag() { tagsRepository.deleteById(-1); } @Test(expected = ConstraintViolationException.class) public void testCantAddTagWithBlankName() { assertNotNull(tag); tag.setName(""); tagsRepository.save(tag); } @Test(expected = ConstraintViolationException.class) public void testCantAddTagWithNameMoreThan255Symbols() { assertNotNull(tag); tag.setName("A".repeat(260)); tagsRepository.save(tag); } @Test(expected = DataIntegrityViolationException.class) public void testCantAddAnotherTagWithSameEmail() { assertNotNull(tag); Tag anotherTag = new Tag(); anotherTag.setName("Hot"); Tag savedUser = tagsRepository.save(tag); assertNotNull(savedUser); tagsRepository.save(anotherTag); } @Test public void testAddMultipleTags() { final byte NUM_TAGS = 5; for (int i = 0; i < NUM_TAGS; i++) { Tag tag = new Tag(); tag.setName("Tag" + i); tagsRepository.save(tag); } Set<Tag> tags = new HashSet<>(); tagsRepository.findAll().forEach(tags::add); assertNotNull(tags); assertEquals(NUM_TAGS, tags.size()); } }
27.504202
80
0.681638
479a7034339bfb2754b4b8bc9d2c8c321a62efe6
27,594
package org.terifan.ui.listview; import org.terifan.ui.listview.util.Orientation; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.InputEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseWheelEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.ScrollPaneConstants; import javax.swing.Scrollable; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.terifan.ui.listview.layout.DetailItemRenderer; import org.terifan.ui.listview.util.Cache; import org.terifan.ui.listview.util.ImageCacheKey; public class ListView<T> extends JComponent implements Scrollable { private static final long serialVersionUID = 1L; private final Rectangle mSelectionRectangle; private final HashSet<T> mSelectedItems; private ListViewModel<T> mModel; private LocationInfo<T> mRolloverInfo; private T mFocusItem; private ListViewHeaderRenderer mHeaderRenderer; private ListViewBarRenderer mBarRenderer; private ListViewItemRenderer mItemRenderer; private ListViewLayout<T> mLayout; private SelectionMode mSelectionMode; private boolean mRolloverEnabled; private boolean mIsConfigured; private Styles mStyles; private T mAnchorItem; private ArrayList<ListViewListener> mEventListeners; private ListViewGroupRenderer mGroupRenderer; private String mPlaceholder; private ListViewMouseListener mMouseListener; private ListViewPopupFactory<T> mPopupFactory; private ViewportMonitor<T> mViewportMonitor; private double mAdjustmentListenerExtraFactor; private MouseAdapter mSmoothScrollMouseAdapter; private int mMinRowHeight; private int mMaxRowHeight; private double mSmoothScrollSpeedMultiplier; private ArrayList<ViewAdjustmentListener> mAdjustmentListeners; private SmoothScrollController mSmoothScroll; @Deprecated private Cache<ImageCacheKey, BufferedImage> mImageCache; public ListView() { this(null); } public ListView(ListViewModel<T> aModel) { mStyles = new Styles(); mSelectedItems = new HashSet<>(); mEventListeners = new ArrayList<>(); mImageCache = new Cache<>(1 * 1024 * 1024); mSelectionRectangle = new Rectangle(); mAdjustmentListeners = new ArrayList<>(); mSmoothScrollSpeedMultiplier = 1; mMinRowHeight = 0; mMaxRowHeight = Integer.MAX_VALUE; super.setOpaque(true); super.setFocusable(true); super.setBackground(mStyles.itemBackground); super.setForeground(mStyles.itemForeground); mMouseListener = new ListViewMouseListener(this); super.addMouseListener(mMouseListener); super.addMouseMotionListener(mMouseListener); super.addKeyListener(new ListViewKeyListener(this)); super.addFocusListener(mFocusListener); // override JScrollPane actions... AbstractAction action = new AbstractAction() { @Override public void actionPerformed(ActionEvent aEvent) { } }; super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), JComponent.WHEN_FOCUSED); super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), JComponent.WHEN_FOCUSED); super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), JComponent.WHEN_FOCUSED); super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), JComponent.WHEN_FOCUSED); super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), JComponent.WHEN_FOCUSED); super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), JComponent.WHEN_FOCUSED); super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), JComponent.WHEN_FOCUSED); super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), JComponent.WHEN_FOCUSED); super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_HOME, InputEvent.CTRL_MASK), JComponent.WHEN_FOCUSED); super.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_END, InputEvent.CTRL_MASK), JComponent.WHEN_FOCUSED); setHeaderRenderer(new ColumnHeaderRenderer()); setItemRenderer(new DetailItemRenderer()); setGroupRenderer(new ListViewGroupRenderer()); setSelectionMode(SelectionMode.ROW); setModel(aModel); } @Deprecated public Cache<ImageCacheKey, BufferedImage> getImageCache() { return mImageCache; } @Deprecated public void setImageCache(Cache<ImageCacheKey, BufferedImage> aImageCache) { mImageCache = aImageCache; } public Styles getStyles() { return mStyles; } public void setGroupRenderer(ListViewGroupRenderer<T> aGroupRenderer) { mGroupRenderer = aGroupRenderer; } public ListViewGroupRenderer<T> getGroupRenderer() { return mGroupRenderer; } public ListView<T> setItemRenderer(ListViewItemRenderer<T> aItemRenderer) { mItemRenderer = aItemRenderer; setListViewLayout(mItemRenderer.createListViewLayout(this)); return this; } public void setListViewLayout(ListViewLayout<T> aLayout) { mLayout = aLayout; } public ListViewLayout<T> getListViewLayout() { return mLayout; } public ListViewItemRenderer<T> getItemRenderer() { return mItemRenderer; } public void setRolloverEnabled(boolean aState) { mRolloverEnabled = aState; } public boolean getRolloverEnabled() { return mRolloverEnabled; } public void setModel(ListViewModel<T> aModel) { mModel = aModel; mAnchorItem = null; mFocusItem = null; mRolloverInfo = null; mSelectedItems.clear(); mSelectionRectangle.setSize(0, 0); } public ListViewModel<T> getModel() { return mModel; } public ListView<T> setHeaderRenderer(ListViewHeaderRenderer<T> aRenderer) { mHeaderRenderer = aRenderer; if (mIsConfigured) { configureEnclosingScrollPane(); } return this; } public ListViewHeaderRenderer getHeaderRenderer() { return mHeaderRenderer; } public ListView<T> setBarRenderer(ListViewBarRenderer aRenderer) { mBarRenderer = aRenderer; if (mIsConfigured) { configureEnclosingScrollPane(); } return this; } public ListViewBarRenderer getBarRenderer() { return mBarRenderer; } public ListView<T> setSelectionMode(SelectionMode aMode) { mSelectionMode = aMode; return this; } public SelectionMode getSelectionMode() { return mSelectionMode; } public T getFocusItem() { return mFocusItem; } public ListView<T> setFocusItem(T aItem) { setFocusItem(aItem, false); return this; } public ListView<T> setFocusItem(T aItem, boolean aSetAnchor) { mFocusItem = aItem; if (aSetAnchor) { mAnchorItem = aItem; } return this; } public ListView<T> setPlaceholder(String aMessage) { mPlaceholder = aMessage; return this; } public String getPlaceholder() { return mPlaceholder; } public int translateColumnIndex(int aIndex) { return aIndex; } public void updateColumnSize(int aColumnIndex) { System.out.println("TODO: updateColumnSize " + aColumnIndex); } protected void updateRollover(Point aPoint) { if (mRolloverEnabled) { LocationInfo<T> info = mLayout.getLocationInfo(aPoint); if (info == null && mRolloverInfo != null || info != null && !info.equals(mRolloverInfo)) { mRolloverInfo = info; repaint(); } } } @Override protected void paintChildren(Graphics aGraphics) { super.paintChildren(aGraphics); Rectangle r = (Rectangle)mSelectionRectangle.clone(); if (!r.isEmpty()) { aGraphics.setColor(new Color(111, 167, 223, 128)); aGraphics.fillRect(r.x + 1, r.y + 1, r.width, r.height); aGraphics.setColor(new Color(105, 153, 201, 128)); aGraphics.drawRect(r.x, r.y, r.width, r.height); if (!r.equals(mSelectionRectangle)) { repaint(); } } } @Override public void paintComponent(Graphics aGraphics) { super.paintComponent(aGraphics); Graphics2D g = (Graphics2D)aGraphics; g.setFont(mStyles.itemFont); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); JScrollPane scrollPane = getEnclosingScrollPane(); if (scrollPane != null) { Rectangle viewport = scrollPane.getViewport().getViewRect(); g.setClip(viewport.x, viewport.y, viewport.width, viewport.height); } mLayout.paint(g); if (mModel.getItemCount() == 0) { paintPlaceHolder(g); } } protected void paintPlaceHolder(Graphics2D aGraphics) { if (mPlaceholder != null && !mPlaceholder.isEmpty()) { aGraphics.setFont(mStyles.placeholderFont); aGraphics.setColor(mStyles.placeholderColor); aGraphics.drawString(mPlaceholder, (getWidth() - aGraphics.getFontMetrics().stringWidth(mPlaceholder)) / 2, Math.min(50, getHeight() - 5)); } } @Override public void addNotify() { super.addNotify(); configureEnclosingScrollPane(); } public void configureEnclosingScrollPane() { mIsConfigured = true; JScrollPane scrollPane = getEnclosingScrollPane(); if (scrollPane != null) { JViewport viewport = scrollPane.getViewport(); if (viewport == null || viewport.getView() != this) { return; } viewport.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (mRolloverEnabled) { Point p1 = MouseInfo.getPointerInfo().getLocation(); SwingUtilities.convertPointFromScreen(p1, ListView.this); updateRollover(p1); } // // JScrollBar horizontalScrollBar = scrollPane.getHorizontalScrollBar(); // JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar(); // // Dimension totalSize = viewport.getView().getSize(); // int scrollX = horizontalScrollBar.getValue(); // int scrollY = verticalScrollBar.getValue(); // boolean dragged = verticalScrollBar.getValueIsAdjusting() || horizontalScrollBar.getValueIsAdjusting(); // Dimension visibleSize = viewport.getSize(); triggerViewportChange(); } }); JPanel columnHeaderView = new JPanel(new BorderLayout()); columnHeaderView.add(new ListViewBar(this), BorderLayout.NORTH); columnHeaderView.add(new ListViewHeader(this, ListViewHeader.COLUMN_HEADER), BorderLayout.SOUTH); scrollPane.setRowHeaderView(new ListViewHeader(this, ListViewHeader.ROW_HEADER)); scrollPane.setColumnHeaderView(columnHeaderView); scrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, new ListViewHeader(this, ListViewHeader.UPPER_LEFT_CORNER)); scrollPane.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, new ListViewHeader(this, ListViewHeader.UPPER_RIGHT_CORNER)); scrollPane.setBorder(null); JScrollBar vsb = scrollPane.getVerticalScrollBar(); vsb.setUnitIncrement(mMinRowHeight); vsb.setBlockIncrement(mMinRowHeight); } } protected JScrollPane getEnclosingScrollPane() { return (JScrollPane)SwingUtilities.getAncestorOfClass(JScrollPane.class, this); } @Override public Dimension getPreferredSize() { return mLayout.getPreferredSize(); } @Override public Dimension getMinimumSize() { return mLayout.getMinimumSize(); } @Override public Dimension getPreferredScrollableViewportSize() { return (Dimension)getPreferredSize().clone(); } @Override public boolean getScrollableTracksViewportHeight() { if (mLayout.getLayoutOrientation() == Orientation.VERTICAL) { return getParent() instanceof JViewport && (((JViewport)getParent()).getHeight() > getPreferredSize().height); } return getParent() instanceof JViewport && (((JViewport)getParent()).getHeight() > getMinimumSize().height); } @Override public boolean getScrollableTracksViewportWidth() { if (mLayout.getLayoutOrientation() == Orientation.VERTICAL) { return getParent() instanceof JViewport && (((JViewport)getParent()).getWidth() > getMinimumSize().width); } return getParent() instanceof JViewport && (((JViewport)getParent()).getWidth() > getPreferredSize().width); } @Override public int getScrollableUnitIncrement(Rectangle aVisibleRect, int aOrientation, int aDirection) { int v = aOrientation == SwingConstants.VERTICAL ? mItemRenderer.getItemPreferredHeight(this) : mItemRenderer.getItemPreferredWidth(this) + mItemRenderer.getItemSpacing(this).x; return (int)Math.ceil(v / 3.0); } @Override public int getScrollableBlockIncrement(Rectangle aVisibleRect, int aOrientation, int aDirection) { if (getParent() instanceof JViewport) { JViewport vp = (JViewport)getParent(); return aOrientation == SwingConstants.VERTICAL ? vp.getHeight() : vp.getWidth(); } int v = aOrientation == SwingConstants.VERTICAL ? mItemRenderer.getItemPreferredHeight(this) : mItemRenderer.getItemPreferredWidth(this) + mItemRenderer.getItemSpacing(this).x; return (int)Math.ceil(v / 3.0); } public void validateLayout() { getModel().validate(); revalidate(); repaint(); } // public ListView addItem(T aItem) // { // mModel.addItem(aItem); // return this; // } public boolean isItemSelected(T aItem) { return mSelectedItems.contains(aItem); } /** * Return true if an unselected item was selected or if an selected item was unselected. */ public boolean setItemSelected(T aItem, boolean aSelected) { if (aSelected) { return mSelectedItems.add(aItem); } else { return mSelectedItems.remove(aItem); } } public void setItemsSelected(Iterable<T> aItems, boolean aSelected) { if (aSelected) { for (T item : aItems) { mSelectedItems.add(item); } } else { for (T item : aItems) { mSelectedItems.remove(item); } } } /** * Either marks all items selected or unselected in this ListView. * * @param aSelected * the new state of all items. */ public void setItemsSelected(boolean aSelected) { if (aSelected) { mSelectedItems.clear(); for (int i = 0; i < mModel.getItemCount(); i++) { mSelectedItems.add(mModel.getItem(i)); } } else { mSelectedItems.clear(); } } /** * Either marks all items selected or unselected in this ListView. * * @param aSelected * the new state of all items. */ public void setItemsSelected(int aStartIndex, int aEndIndex, boolean aSelected) { aEndIndex = Math.min(aEndIndex, mModel.getItemCount()); for (int i = aStartIndex; i < aEndIndex; i++) { if (aSelected) { mSelectedItems.add(mModel.getItem(i)); } else { mSelectedItems.remove(mModel.getItem(i)); } } } public void invertItemSelection(T aItem) { if (mSelectedItems.contains(aItem)) { mSelectedItems.remove(aItem); } else { mSelectedItems.add(aItem); } } public synchronized void addListViewListener(ListViewListener aListViewListener) { mEventListeners.add(aListViewListener); } public synchronized void removeListViewListener(ListViewListener aListViewListener) { mEventListeners.remove(aListViewListener); } protected synchronized void fireSelectionChanged(ListViewEvent aEvent) { for (ListViewListener listener : mEventListeners) { listener.selectionChanged(aEvent); } } protected synchronized void fireSelectionAction(ListViewEvent aEvent) { for (ListViewListener listener : mEventListeners) { listener.selectionAction(aEvent); } } protected synchronized void fireSortedColumnWillChange(ListViewEvent aEvent) { for (ListViewListener listener : mEventListeners) { listener.sortedColumnWillChange(aEvent); } } protected synchronized void fireSortedColumnChanged(ListViewEvent aEvent) { for (ListViewListener listener : mEventListeners) { listener.sortedColumnChanged(aEvent); } } /** * Create and display a pop-up. * * Note: this code also ensure that if the right click occurred on an item the item will be selected before the pop-up is displayed. * * @return * */ protected boolean firePopupMenu(Point aPoint, LocationInfo<T> aLocationInfo) { ListViewPopupFactory<T> factory = getPopupFactory(); if (factory == null) { return false; } JPopupMenu menu = factory.createPopup(this, aPoint, aLocationInfo); if (menu == null) { return false; } menu.show(ListView.this, aPoint.x, aPoint.y); return true; } /** * Sets the pop-up factory for this ListView. * * @param aMenu * a pop-up factory or null if non should exist */ public void setPopupFactory(ListViewPopupFactory<T> aPopupFactory) { mPopupFactory = aPopupFactory; } /** * Returns the pop-up factory assigned for this ListView using setPopupFactory. * * @return * a PopupFactory or null if one doesn't exists */ public ListViewPopupFactory<T> getPopupFactory() { return mPopupFactory; } public void ensureItemIsVisible(T aItem) { if (aItem != null) { Rectangle rect = new Rectangle(); mLayout.getItemBounds(aItem, rect); scrollRectToVisible(rect); } } /** * Gets all selected items from this ListView in the order they are * currently displayed. * * @return * a list of all selected items. */ public ArrayList<T> getSelectedItems() { ArrayList<T> list = new ArrayList<>(mSelectedItems.size()); ItemVisitor<T> visitor = (T aItem) -> { if (mSelectedItems.contains(aItem)) { list.add(aItem); } return null; }; mModel.visitItems(true, visitor); return list; } /** * Gets all items from this ListView in the order they are currently * displayed. * * @return * a list of all items. */ public ArrayList<T> getItems() { ArrayList<T> list = new ArrayList<>(mModel.getItemCount()); ItemVisitor<T> visitor = aItem -> { list.add(aItem); return null; }; mModel.visitItems(true, visitor); return list; } public T getRolloverItem() { return mRolloverInfo == null ? null : mRolloverInfo.getItem(); } public ListViewGroup<T> getRolloverGroup() { return mRolloverInfo == null ? null : mRolloverInfo.getGroup(); } // TODO: replace public void configureKeys() { addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_A) { setItemsSelected(true); repaint(); } } }); } @Override public void revalidate() { if (mModel != null) { mModel.validate(); } super.revalidate(); } /** * Return true if the item is currently probably visible. TODO: only jscrollpane supported!!! * * @param aItem * the item * @param aExpandView * include neighbouring items * @return * true if the item is probably visible */ public boolean isItemDisplayable(T aItem, boolean aExpandView) { Rectangle itemRect = new Rectangle(); if (!mLayout.getItemBounds(aItem, itemRect)) { return false; } Container p = getParent(); if (p instanceof JViewport) { Container gp = p.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane)gp; JViewport viewport = scrollPane.getViewport(); if (viewport != null && viewport.getView() == this) { int x = scrollPane.getHorizontalScrollBar().getValue(); int y = scrollPane.getVerticalScrollBar().getValue(); int w = viewport.getWidth(); int h = viewport.getHeight(); if (aExpandView) { x -= itemRect.width * 2; y -= itemRect.height * 2; w += itemRect.width * 4; h += itemRect.height * 4; } return !SwingUtilities.computeIntersection(x, y, w, h, itemRect).isEmpty(); } } } return true; } protected T getAnchorItem() { return mAnchorItem; } protected void setAnchorItem(T aItem) { mAnchorItem = aItem; } protected HashSet<T> getSelectedItemsMap() { return mSelectedItems; } public void setRowHeaderRenderer() { } protected Rectangle getSelectionRectangle() { return mSelectionRectangle; } public T getItemAt(Point aPoint) { LocationInfo<T> info = mLayout.getLocationInfo(aPoint); if (info != null && info.isItem()) { return info.getItem(); } return null; } public void addDropTargetListener(DropTargetListener aDropTargetListener) { new DropTarget(this, aDropTargetListener).setActive(true); } /** * Return true if the border of a item icon should be drawn. Default implementation return true whenever there is an icon otherwise false. Override this method for custom handling. */ // public boolean isItemBorderPainted(T aItem) // { // return aItem.getIcon() != null; // } private FocusListener mFocusListener = new FocusAdapter() { @Override public void focusGained(FocusEvent aE) { repaint(); } @Override public void focusLost(FocusEvent aE) { repaint(); } }; public ArrayList<T> getVisibleItems() { return getVisibleItems(0.0); } public ArrayList<T> getVisibleItems(double aExtraFactor) { JScrollPane scrollPane = getEnclosingScrollPane(); ArrayList<T> list = new ArrayList<>(); if (scrollPane != null) { Rectangle viewRect = scrollPane.getViewport().getViewRect(); if (aExtraFactor > 0) { int w = (int)(aExtraFactor * viewRect.width); int h = (int)(aExtraFactor * viewRect.height); viewRect.x -= w; viewRect.y -= h; viewRect.width += 2 * w; viewRect.height += 2 * h; } mLayout.getItemsIntersecting(viewRect, list); } else { mLayout.getItemsIntersecting(new Rectangle(0, 0, getWidth(), getHeight()), list); } return list; } /** * Add listeners receiving reports on items entering or leaving the view * of the ListView viewport assuming it is enclosed in a JScrollPane. */ public void addAdjustmentListener(ViewAdjustmentListener aAdjustmentListener) { mAdjustmentListeners.add(aAdjustmentListener); if (mViewportMonitor == null) { mViewportMonitor = new ViewportMonitor<>(); } } public void removeAdjustmentListener(ViewAdjustmentListener aAdjustmentListener) { mAdjustmentListeners.remove(aAdjustmentListener); if (mViewportMonitor != null && mAdjustmentListeners.isEmpty()) { mViewportMonitor = null; } } public void setSmoothScrollController(SmoothScrollController aSmoothScrollController) { mSmoothScroll = aSmoothScrollController; } public double getSmoothScrollSpeedMultiplier() { return mSmoothScrollSpeedMultiplier; } public void setSmoothScrollSpeedMultiplier(double aMultiplier) { mSmoothScroll = null; mSmoothScrollSpeedMultiplier = aMultiplier; } public void smoothScroll(double aPreciseWheelRotation) { SmoothScrollController ss = mSmoothScroll; if (ss == null) { mSmoothScroll = ss = new SmoothScrollController(this, 10, (int)(mSmoothScrollSpeedMultiplier * (mItemRenderer.getItemPreferredHeight(this) + mItemRenderer.getItemSpacing(this).y)), 500); } ss.smoothScroll(aPreciseWheelRotation); } public int getMinRowHeight() { return mMinRowHeight; } public void setMinRowHeight(int aMinRowHeight) { mMinRowHeight = aMinRowHeight; } public int getMaxRowHeight() { return mMaxRowHeight; } public void setMaxRowHeight(int aMaxRowHeight) { mMaxRowHeight = aMaxRowHeight; } public double getAdjustmentListenerExtraFactor() { return mAdjustmentListenerExtraFactor; } /** * Extend the range in which items are reported to be added or removed by the AdjustmentListener, by this factor. */ public void setAdjustmentListenerExtraFactor(double aFactor) { mAdjustmentListenerExtraFactor = aFactor; } protected synchronized void triggerViewportChange() { ViewportMonitor monitor = mViewportMonitor; if (monitor != null) { monitor.register(getVisibleItems(mAdjustmentListenerExtraFactor)); } } private class ViewportMonitor<T> { private HashSet<T> mVisibleItems = new HashSet<>(); private final HashSet<T> mRemovedItems = new HashSet<>(); private final HashSet<T> mAddedItems = new HashSet<>(); synchronized void register(ArrayList<T> aVisibleItems) { HashSet<T> v = new HashSet<>(aVisibleItems); extractDifferences(v, mVisibleItems, mAddedItems); extractDifferences(mVisibleItems, v, mRemovedItems); mVisibleItems = v; if (!mRemovedItems.isEmpty() || !mAddedItems.isEmpty()) { for (ViewAdjustmentListener listener : mAdjustmentListeners) { listener.viewChanged(mVisibleItems, mAddedItems, mRemovedItems); } } } private void extractDifferences(Collection<T> aListA, Collection<T> aListB, Collection<T> aOutput) { aOutput.clear(); for (T a : aListA) { boolean found = false; for (T b : aListB) { if (a == b) { found = true; break; } } if (!found) { aOutput.add(a); } } } } public boolean isSmoothScrollEnabled() { return mSmoothScrollMouseAdapter != null; } public void setSmoothScrollEnabled(boolean aState) { JScrollPane scrollPane = getEnclosingScrollPane(); if (scrollPane == null) { throw new IllegalStateException("The ListView must have an enclosing JScrollPane."); } if (aState) { mSmoothScrollMouseAdapter = new MouseAdapter() { @Override public void mouseWheelMoved(MouseWheelEvent aEvent) { smoothScroll(aEvent.getPreciseWheelRotation()); } }; scrollPane.setWheelScrollingEnabled(false); scrollPane.addMouseWheelListener(mSmoothScrollMouseAdapter); } else if (isSmoothScrollEnabled()) { scrollPane.setWheelScrollingEnabled(true); scrollPane.removeMouseWheelListener(mSmoothScrollMouseAdapter); mSmoothScrollMouseAdapter = null; } } }
22.562551
190
0.695187
cdcc10026d78542cd4fe426306457a6c5719664b
2,044
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.core.impl.score.director.easy; import org.junit.Test; import org.optaplanner.core.api.score.buildin.simple.SimpleScore; import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor; import org.optaplanner.core.impl.testdata.domain.TestdataSolution; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class EasyScoreDirectorFactoryTest { @Test public void getEasyScoreCalculator() { EasyScoreCalculator scoreCalculator = mock(EasyScoreCalculator.class); EasyScoreDirectorFactory directorFactory = new EasyScoreDirectorFactory(scoreCalculator); assertSame(scoreCalculator, directorFactory.getEasyScoreCalculator()); } @Test public void buildScoreDirector() { SolutionDescriptor solutionDescriptor = TestdataSolution.buildSolutionDescriptor(); EasyScoreCalculator scoreCalculator = mock(EasyScoreCalculator.class); when(scoreCalculator.calculateScore(any(TestdataSolution.class))).thenReturn(SimpleScore.valueOf(-10)); EasyScoreDirectorFactory directorFactory = new EasyScoreDirectorFactory(scoreCalculator); directorFactory.setSolutionDescriptor(solutionDescriptor); EasyScoreDirector director = directorFactory.buildScoreDirector(false); director.setWorkingSolution(new TestdataSolution()); assertEquals(SimpleScore.valueOf(-10), director.calculateScore()); } }
40.88
111
0.769569
c84e70fdc788f485ebb2a294614470de9c697b1e
737
package com.packt.springboot.securityintro.logic; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @Service public class ShortMessageService { private List<ShortMessage> shortMessages = new LinkedList<>(); /** Low-level access, unsecured */ void add(Author author, LocalDateTime postedTime, String messageText) { ShortMessage shortMessage = new ShortMessage(author, postedTime, messageText); shortMessages.add(shortMessage); } public List<ShortMessage> findAll() { // If you want to use @PostFilter, use a modifiable copy! return new ArrayList<>(shortMessages); } }
29.48
86
0.7327
0f98d499f1f69397d3924fb322442c4fd5d56ddb
2,201
package com.cky.learnandroiddetails; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.View; import android.widget.TextView; import java.util.ArrayList; public class TestViewAct extends AppCompatActivity implements onStartDragListener { ArrayList<Contact> mContacts; RecyclerViewPlus mRecyclerViewPlus; ContactAdapter mContactAdapter; ItemTouchHelper touchHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_view); mContacts = Contact.createList(20); mContactAdapter = new ContactAdapter(TestViewAct.this, mContacts, this); mRecyclerViewPlus = (RecyclerViewPlus) findViewById(R.id.rvPlus); mRecyclerViewPlus.setLayoutManager(new LinearLayoutManager(this)); TextView textView1 = new TextView(TestViewAct.this); TextView textView2= new TextView(TestViewAct.this); textView1.setText("Header-1"); textView2.setText("Footer-1"); //mContactAdapter.addHeader(textView1); //mContactAdapter.addFooter(textView2); DividerItemDecoration itemDecoration = new DividerItemDecoration(TestViewAct.this, DividerItemDecoration.VERTICAL_LIST); mRecyclerViewPlus.addItemDecoration(itemDecoration); mRecyclerViewPlus.setAdapter(mContactAdapter); ItemTouchHelper.Callback callback = new MyItemTouchHelperCallBack(mContactAdapter); touchHelper = new ItemTouchHelper(callback); touchHelper.attachToRecyclerView(mRecyclerViewPlus); mContactAdapter.setOnItemClickListener(new ContactAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { ToastUtil.showToast(TestViewAct.this, position + ""); } }); } @Override public void onStartDrag(RecyclerView.ViewHolder viewHolder) { touchHelper.startDrag(viewHolder); } }
31.898551
128
0.736938
4eb0c1863038cbb0a050af49aaf5cfca502ea03b
370
package io.appium.java_client.pagefactory_tests.widgets.android.extended; import io.appium.java_client.pagefactory_tests.widgets.android.annotated.AnnotatedAndroidReview; import org.openqa.selenium.WebElement; public class ExtendedAndroidReview extends AnnotatedAndroidReview{ protected ExtendedAndroidReview(WebElement element) { super(element); } }
30.833333
96
0.824324
108a1a3ece1f07abb96484e5d2f04edbd9dc3865
327
package backtype.storm.topology; import backtype.storm.task.TopologyContext; import backtype.storm.tuple.Tuple; import java.util.Map; public interface IBasicBolt extends IComponent { void prepare(Map stormConf, TopologyContext context); void execute(Tuple input, BasicOutputCollector collector); void cleanup(); }
29.727273
62
0.795107
0ed87c8d58e9e5a1ef72dd61ba2238f42b024665
581
package com.patrykkosieradzki.quizletify.ui; import com.patrykkosieradzki.quizletify.Word; public class CheckBoxListItem { private Word word; public CheckBoxListItem(Word word) { this.word = word; } private boolean isSelected = false; public boolean isSelected() { return isSelected; } public void setSelected(boolean isSelected) { this.isSelected = isSelected; } public String getWord() { return word.getWord(); } public String getTranslation() { return word.getTranslation(); } }
17.606061
49
0.652324
a9857f54f43f6b156c22cd8e2504138b581c1296
891
package search; import java.io.File; import java.util.Observer; import javafx.collections.ObservableList; /** * Created by: Aleksandr * Date: 08.01.2017 * Project: FileFinder * <p> * "The more we do, the more we can do" © */ public class Search { private static volatile Search instance; private boolean searchActive = false; private ObservableList<?> result; private boolean searchInFiles = false; public static Search getInstance() { Search localInstance = instance; if (localInstance == null) { synchronized (Search.class) { localInstance = instance; if (localInstance == null) { instance = localInstance = new Search(); } } } return localInstance; } public void findFile(String request, Observer updater) { Result requestResult = new Result<File>(); requestResult.addObserver(updater); } }
22.846154
58
0.672278
889da320f93a84f634b43bbd524343a64df8e0af
1,671
package com.goodjoon.guppy.engine.common.mybatis.typehandler; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedJdbcTypes; import org.apache.ibatis.type.MappedTypes; import org.apache.ibatis.type.TypeHandler; import com.goodjoon.guppy.engine.common.Constants; // TODO: JDBC 쪽의 NULL 값 처리도 해줘야 한다. @MappedTypes(String[].class) @MappedJdbcTypes(value=JdbcType.VARCHAR, includeNullJdbcType=true) public class ArrayForVarcharTypeHandler implements TypeHandler<String[]> { @Override public void setParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException { String param = ""; for (int nParamIndex = 0 ; nParamIndex < parameter.length ; nParamIndex++) { param += parameter[nParamIndex]; if (nParamIndex+1 < parameter.length) param += Constants.DB_FIELD_SEPERATOR; } ps.setString(i, param); } @Override public String[] getResult(ResultSet rs, String columnName) throws SQLException { String[] values = rs.getString(columnName).split(Constants.DB_FIELD_SEPERATOR); return values; } @Override public String[] getResult(ResultSet rs, int columnIndex) throws SQLException { String[] values = rs.getString(columnIndex).split(Constants.DB_FIELD_SEPERATOR); return values; } @Override public String[] getResult(CallableStatement cs, int columnIndex) throws SQLException { String[] values = cs.getString(columnIndex).split(Constants.DB_FIELD_SEPERATOR); return values; } }
30.944444
83
0.745063
c59b808a2e186dad737d71b1567b5095057e2c3d
4,047
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.aeox.business.login.boundary; import com.aeox.business.common.boundary.ErrorMessage; import com.aeox.business.logger.control.LogInterceptor; import com.aeox.business.login.control.CORSEnabled; import com.aeox.business.login.control.SessionProvider; import com.aeox.business.login.control.SessionSecured; import com.aeox.business.login.entity.Role; import com.aeox.business.login.entity.User; import javax.inject.Inject; import javax.interceptor.Interceptors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * * @author XLOPP2 */ @Path("login") @CORSEnabled(domain = "http://localhost:4200", allowCredentials = true) @Interceptors(LogInterceptor.class) public class LoginResource { @Inject private LoginService loginService; @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response login(@Context HttpServletRequest request, @Context HttpHeaders headers){ HttpSession session = request.getSession(true); User userReceived = SessionProvider.getHttpBasicAuthorization(headers); if (userReceived == null) return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorMessage(400, "Authorization header is not attached")).build(); User userFound = loginService.validateUser(userReceived.getUsername(), userReceived.getPassword()); if(userFound == null) return Response.status(Response.Status.NOT_FOUND).entity(new ErrorMessage(404, "User does not exist")).build(); session.setAttribute("user", userFound); return Response.status(Response.Status.OK).build(); } @DELETE public Response logout(@Context HttpServletRequest request, User user){ HttpSession session = request.getSession(true); session.removeAttribute("user"); session.invalidate(); return Response.status(Response.Status.OK).build(); } @POST @Path("roles") @Consumes(value = MediaType.APPLICATION_JSON) @Produces(value = MediaType.APPLICATION_JSON) @SessionSecured(role = "admin") public Response createRole(Role role){ Role roleCreated = loginService.createRole(role); return Response.status(Response.Status.CREATED).entity(roleCreated).build(); } @POST @Path("roles/{role_id}/users") @Consumes(value = MediaType.APPLICATION_JSON) @Produces(value = MediaType.APPLICATION_JSON) @SessionSecured(role = "admin") public Response createAccount(@PathParam("role_id") Long roleId, User user){ Role role = loginService.getRoleById(roleId); User userCreated = loginService.createUser(role, user); return Response.status(Response.Status.CREATED).entity(userCreated).build(); } @GET @Path("users") @Produces(value = MediaType.APPLICATION_JSON) @SessionSecured(role = "admin") public Response getUsers(){ return Response.status(Response.Status.OK).entity(loginService.getUsers()).build(); } @GET @Path("users/{user_id}") @Produces(value = MediaType.APPLICATION_JSON) @SessionSecured(role = "admin") public Response getUser(@PathParam("user_id") Long userId){ User userFound = loginService.getUserById(userId); return Response.status(Response.Status.OK).entity(userFound).build(); } }
37.472222
143
0.696318
7aa7e2535481f049206ed55bd1c62de67d201c10
3,979
/** * Copyright 2010-2013, Stanford University. This file is licensed under the * BSD license as described in the included LICENSE.txt. */ package net.beaconcontroller.devicemanager.web; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import net.beaconcontroller.devicemanager.Device; import net.beaconcontroller.devicemanager.IDeviceManager; import net.beaconcontroller.packet.IPv4; import net.beaconcontroller.web.IWebManageable; import net.beaconcontroller.web.view.BeaconViewResolver; import net.beaconcontroller.web.view.Tab; import net.beaconcontroller.web.view.layout.Layout; import net.beaconcontroller.web.view.layout.TwoColumnLayout; import net.beaconcontroller.web.view.section.TableSection; import org.openflow.util.HexString; import org.openflow.util.U16; 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; /** * This class sets up the web UI component for the structures in * net.beaconcontroller.devicemanager * * @author David Erickson (daviderickson@cs.stanford.edu) */ @Controller @RequestMapping("/devicemanager") public class DeviceManagerWebManageable implements IWebManageable { protected static Logger log = LoggerFactory.getLogger(DeviceManagerWebManageable.class); protected List<Tab> tabs; protected IDeviceManager deviceManager; public DeviceManagerWebManageable() { tabs = new ArrayList<Tab>(); tabs.add(new Tab("Overview", "/wm/devicemanager/overview.do")); } @Override public String getName() { return "Device Manager"; } @Override public String getDescription() { return "View devices."; } @Override public List<Tab> getTabs() { return tabs; } @RequestMapping("/overview") public String overview(Locale locale, Map<String, Object> model) { Layout layout = new TwoColumnLayout(); model.put("layout", layout); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd HH:mm:ss z", locale); // Listener List Table List<String> columnNames = new ArrayList<String>(); List<List<String>> cells = new ArrayList<List<String>>(); columnNames = new ArrayList<String>(); columnNames.add("MAC"); columnNames.add("IP"); columnNames.add("Last Seen"); columnNames.add("Switch"); columnNames.add("Port"); cells = new ArrayList<List<String>>(); for (Device device : deviceManager.getDevices()) { List<String> row = new ArrayList<String>(); row.add(HexString.toHexString(device.getDataLayerAddress())); StringBuffer sb = new StringBuffer(); for (Integer nw : device.getNetworkAddresses()) { if (sb.length() > 0) sb.append(" "); sb.append(IPv4.fromIPv4Address(nw) + " "); } row.add(sb.toString()); row.add(sdf.format(new Date(device.getLastSeen()))); row.add(HexString.toHexString(device.getSw().getId())); row.add(((Integer)U16.f(device.getSwPort())).toString()); cells.add(row); } Map<String,String> tableOptions = new HashMap<String, String>(); tableOptions.put("\"bFilter\"", "true"); TableSection tableSection = new TableSection("Devices", columnNames, cells, "table-devices", tableOptions); layout.addSection(tableSection, TwoColumnLayout.COLUMN1); return BeaconViewResolver.SIMPLE_VIEW; } /** * @param deviceManager the deviceManager to set */ @Autowired public void setDeviceManager(IDeviceManager deviceManager) { this.deviceManager = deviceManager; } }
35.212389
115
0.685851
10709237eda7f34afe7c4c5d4b2abc1af922ef96
8,053
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.webapp; import com.google.common.base.Joiner; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.UniformInterfaceException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AuthorizationException; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.logaggregation.ContainerLogAggregationType; import org.apache.hadoop.yarn.logaggregation.ContainerLogsRequest; import org.apache.hadoop.yarn.logaggregation.filecontroller.LogAggregationFileControllerFactory; import org.apache.hadoop.yarn.webapp.ForbiddenException; import org.apache.hadoop.yarn.webapp.util.WebAppUtils; import org.apache.hadoop.yarn.webapp.util.YarnWebServiceUtils; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.UndeclaredThrowableException; import java.nio.charset.Charset; import java.util.HashSet; import java.util.Set; /** * Log web service utils class. */ @InterfaceAudience.Private @InterfaceStability.Evolving public final class LogWebServiceUtils { private static final Logger LOG = LoggerFactory.getLogger(LogWebServiceUtils.class); private LogWebServiceUtils() { } private static final Joiner DOT_JOINER = Joiner.on(". "); public static Response sendStreamOutputResponse( LogAggregationFileControllerFactory factory, ApplicationId appId, String appOwner, String nodeId, String containerIdStr, String fileName, String format, long bytes, boolean printEmptyLocalContainerLog) { String contentType = WebAppUtils.getDefaultLogContentType(); if (format != null && !format.isEmpty()) { contentType = WebAppUtils.getSupportedLogContentType(format); if (contentType == null) { String errorMessage = "The valid values for the parameter : format " + "are " + WebAppUtils.listSupportedLogContentType(); return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage) .build(); } } StreamingOutput stream = null; try { stream = getStreamingOutput(factory, appId, appOwner, nodeId, containerIdStr, fileName, bytes, printEmptyLocalContainerLog); } catch (Exception ex) { LOG.debug("Exception", ex); return createBadResponse(Response.Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } Response.ResponseBuilder response = Response.ok(stream); response.header("Content-Type", contentType); // Sending the X-Content-Type-Options response header with the value // nosniff will prevent Internet Explorer from MIME-sniffing a response // away from the declared content-type. response.header("X-Content-Type-Options", "nosniff"); return response.build(); } private static StreamingOutput getStreamingOutput( final LogAggregationFileControllerFactory factory, final ApplicationId appId, final String appOwner, final String nodeId, final String containerIdStr, final String logFile, final long bytes, final boolean printEmptyLocalContainerLog) throws IOException { StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream os) throws IOException, WebApplicationException { ContainerLogsRequest request = new ContainerLogsRequest(); request.setAppId(appId); request.setAppOwner(appOwner); request.setContainerId(containerIdStr); request.setBytes(bytes); request.setNodeId(nodeId); Set<String> logTypes = new HashSet<>(); logTypes.add(logFile); request.setLogTypes(logTypes); boolean findLogs = factory.getFileControllerForRead(appId, appOwner) .readAggregatedLogs(request, os); if (!findLogs) { os.write(("Can not find logs for container:" + containerIdStr) .getBytes(Charset.forName("UTF-8"))); } else { if (printEmptyLocalContainerLog) { StringBuilder sb = new StringBuilder(); sb.append(containerIdStr + "\n"); sb.append("LogAggregationType: " + ContainerLogAggregationType.LOCAL + "\n"); sb.append("LogContents:\n"); sb.append(getNoRedirectWarning() + "\n"); os.write(sb.toString().getBytes(Charset.forName("UTF-8"))); } } } }; return stream; } public static String getNoRedirectWarning() { return "We do not have NodeManager web address, so we can not " + "re-direct the request to related NodeManager " + "for local container logs."; } public static void rewrapAndThrowException(Exception e) { if (e instanceof UndeclaredThrowableException) { rewrapAndThrowThrowable(e.getCause()); } else { rewrapAndThrowThrowable(e); } } public static void rewrapAndThrowThrowable(Throwable t) { if (t instanceof AuthorizationException) { throw new ForbiddenException(t); } else { throw new WebApplicationException(t); } } public static long parseLongParam(String bytes) { if (bytes == null || bytes.isEmpty()) { return Long.MAX_VALUE; } return Long.parseLong(bytes); } public static Response createBadResponse(Response.Status status, String errMessage) { Response response = Response.status(status) .entity(DOT_JOINER.join(status.toString(), errMessage)).build(); return response; } public static boolean isRunningState(YarnApplicationState appState) { return appState == YarnApplicationState.RUNNING; } protected static UserGroupInformation getUser(HttpServletRequest req) { String remoteUser = req.getRemoteUser(); UserGroupInformation callerUGI = null; if (remoteUser != null) { callerUGI = UserGroupInformation.createRemoteUser(remoteUser); } return callerUGI; } public static String getNMWebAddressFromRM(Configuration yarnConf, String nodeId) throws ClientHandlerException, UniformInterfaceException, JSONException { JSONObject nodeInfo = YarnWebServiceUtils.getNodeInfoFromRMWebService(yarnConf, nodeId) .getJSONObject("node"); return nodeInfo.has("nodeHTTPAddress") ? nodeInfo.getString("nodeHTTPAddress") : null; } public static String getAbsoluteNMWebAddress(Configuration yarnConf, String nmWebAddress) { if (nmWebAddress.contains(WebAppUtils.HTTP_PREFIX) || nmWebAddress .contains(WebAppUtils.HTTPS_PREFIX)) { return nmWebAddress; } return WebAppUtils.getHttpSchemePrefix(yarnConf) + nmWebAddress; } }
38.903382
96
0.725816
0141d2e5caca90160024b3b79c0eeae4b1c04f99
2,667
package com.client.impl.test; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.Random; import java.util.zip.CRC32; import java.util.zip.Checksum; //import org.apache.log4j.Logger; import com.client.ClientException; import com.client.DataStoreClient; import com.client.impl.DataStoreClientImpl; public class DataStoreClientTest { byte[] addr = { 127, 0, 0, 1 }; int port = 10024; private byte[] generateData(int size) { byte[] data = new byte[size]; Random random = new Random(); random.nextBytes(data); return data; } public void testWrite() throws UnknownHostException, ClientException { InetAddress inetAddress = InetAddress.getByAddress(addr); DataStoreClient dataStoreClient = new DataStoreClientImpl(inetAddress, port); byte[] data = generateData(100); dataStoreClient.write("testWrite1", data); } public void testRead() throws Exception { InetAddress inetAddress = InetAddress.getByAddress(addr); DataStoreClient dataStoreClient = new DataStoreClientImpl(inetAddress, port); byte[] data1 = generateData(100); dataStoreClient.write("testData", data1); byte[] data2 = dataStoreClient.read("testData"); Checksum checkSum1 = new CRC32(); checkSum1.update(data1, 0, data1.length); long long1 = checkSum1.getValue(); Checksum checkSum2 = new CRC32(); checkSum2.update(data2, 0, data2.length); long long2 = checkSum2.getValue(); if (long1 != long2) throw new Exception("Input data is not equal to output data!"); } public void testReadBroken() throws Exception { InetAddress inetAddress = InetAddress.getByAddress(addr); DataStoreClient dataStoreClient = new DataStoreClientImpl(inetAddress, port); dataStoreClient.read("missingData"); } public void testDelete() throws Exception { InetAddress inetAddress = InetAddress.getByAddress(addr); DataStoreClient dataStoreClient = new DataStoreClientImpl(inetAddress, port); dataStoreClient.delete("testData"); } public void testDeleteBroken() throws Exception { InetAddress inetAddress = InetAddress.getByAddress(addr); DataStoreClient dataStoreClient = new DataStoreClientImpl(inetAddress, port); dataStoreClient.delete("missingData"); } public void testDirectory() throws Exception { InetAddress inetAddress = InetAddress.getByAddress(addr); DataStoreClient dataStoreClient = new DataStoreClientImpl(inetAddress, port); byte[] data = generateData(100); dataStoreClient.write("testData", data); List<String> list = dataStoreClient.directory(); if (list.size() <= 0) throw new Exception("No of files in the folder is not positive."); } }
31.376471
72
0.752906
eb481cffecc3b76f1eb1772122d8a2a97276714a
372
package com.sylvyrfysh.monerowallet; public class TimedObject<T> { private T obj; private long endTime; public TimedObject(T obj,long secondsOfValidity) { this.obj = obj; this.endTime = (secondsOfValidity * 1000) + System.currentTimeMillis(); } public boolean isValid() { return System.currentTimeMillis() < endTime; } public T getObj() { return obj; } }
21.882353
73
0.723118
c2f89237e1ec00f45b2160cfc65777d34c328a19
1,141
/* * generated by Xtext 2.12.0 */ package uniandes.mdd.aplicacion.blockchain.parser.antlr; import com.google.inject.Inject; import org.eclipse.xtext.parser.antlr.AbstractAntlrParser; import org.eclipse.xtext.parser.antlr.XtextTokenStream; import uniandes.mdd.aplicacion.blockchain.parser.antlr.internal.InternalBlockchainParser; import uniandes.mdd.aplicacion.blockchain.services.BlockchainGrammarAccess; public class BlockchainParser extends AbstractAntlrParser { @Inject private BlockchainGrammarAccess grammarAccess; @Override protected void setInitialHiddenTokens(XtextTokenStream tokenStream) { tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT"); } @Override protected InternalBlockchainParser createParser(XtextTokenStream stream) { return new InternalBlockchainParser(stream, getGrammarAccess()); } @Override protected String getDefaultRuleName() { return "Aplicacion"; } public BlockchainGrammarAccess getGrammarAccess() { return this.grammarAccess; } public void setGrammarAccess(BlockchainGrammarAccess grammarAccess) { this.grammarAccess = grammarAccess; } }
27.829268
89
0.816827
fc666f1d6bfe9de463ff791f24cf29a346a9ada6
201
package com.scs.stevetech1.components; import com.scs.stevetech1.server.AbstractGameServer; public interface IProcessByServer { void processByServer(AbstractGameServer server, float tpf_secs); }
20.1
65
0.825871
4327c015ee31493266d930fb6b1bcf1b6496ec77
301
public enum QuestionStatus{ OPEN, CLOSED, ON_HOLD, DELETED } public enum QuestionClosingRemark{ DUPLICATE, OFF_TOPIC, TOO_BROAD, NOT_CONSTRUCTIVE, NOT_A_REAL_QUESTION, PRIMARILY_OPINION_BASED } public enum AccountStatus{ ACTIVE, CLOSED, CANCELED, BLACKLISTED, BLOCKED }
13.086957
34
0.747508
0bf2dc91deb3e1e90468d505a9b10e173ec1e4ef
1,333
package com.example.demo.model; public class Plant { public final static String KEY_ROOT_ARRAY = "plants"; public final static String KEY_ID = "id"; public final static String KEY_GENUS = "genus"; public final static String KEY_SPECIES = "species"; public final static String KEY_CULTIVAR = "cultivar"; public final static String KEY_COMMON = "common"; private int id; private String genus; private String species; private String cultivar; private String common; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getGenus() { return genus; } public void setGenus(String genus) { this.genus = genus; } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } public String getCultivar() { return cultivar; } public void setCultivar(String cultivar) { this.cultivar = cultivar; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } @Override public String toString() { return "Plant{" + "id=" + id + ", genus='" + genus + '\'' + ", species='" + species + '\'' + ", cultivar='" + cultivar + '\'' + ", common='" + common + '\'' + '}'; } }
22.59322
55
0.632408
5f2272c554283f2e7e6dab698a16bb6003808413
397
package com.udacity.jdnd.course3.critter.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(code = HttpStatus.NOT_FOUND) public class EmployeeNotFoundException extends RuntimeException{ public EmployeeNotFoundException(Long id) { super(String.format("Customer not found with id = %d", id)); } }
30.538462
68
0.785894
d861f274ea12e1e73c9825da077af28bbdecc9a2
5,194
/* * MIT License * * Copyright (c) 2018 i4one Interactive, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.i4one.rewards.web.interceptor; import com.i4one.base.model.client.SingleClient; import com.i4one.base.web.controller.Model; import com.i4one.base.web.interceptor.model.BaseModelInterceptor; import com.i4one.base.web.interceptor.model.ModelInterceptor; import com.i4one.base.web.interceptor.model.UserMenuModelInterceptor; import com.i4one.rewards.model.raffle.RaffleManager; import com.i4one.rewards.model.raffle.RaffleSettings; import com.i4one.rewards.model.shopping.ShoppingManager; import com.i4one.rewards.model.shopping.ShoppingSettings; import com.i4one.rewards.model.shopping.category.ShoppingCategory; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author Hamid Badiozamani */ @Service public class RewardsUserMenuModelInterceptor extends BaseModelInterceptor implements ModelInterceptor { private Map<String, Object> rewardsMenu; private ShoppingManager shoppingManager; private RaffleManager raffleManager; private RewardsCategoriesModelInterceptor rewardsCategoriesModelInterceptor; private static final int MAX_CATEGORY_MENU_SIZE = 2; @Override public void init() { super.init(); rewardsMenu = new LinkedHashMap<>(); //rewardsMenu.put("msg.rewards.user.shoppings.index.title", "/rewards/user/shoppings/index.html"); //rewardsMenu.put("msg.rewards.user.raffles.index.title", "/rewards/user/raffles/index.html"); } @Override public Map<String, Object> initResponseModel(Model model) { HttpServletRequest request = model.getRequest(); if ( isUserRequest(request)) { @SuppressWarnings("unchecked") List<Map<String,Object>> menus = (List<Map<String, Object>>) model.get(UserMenuModelInterceptor.MENUS); Map<String,Object> menu = menus.get(0); Map<String, Object> computedMenu = new LinkedHashMap<>(); computedMenu.putAll(rewardsMenu); SingleClient client = model.getSingleClient(); String lang = model.getLanguage(); ShoppingSettings shoppingSettings = getShoppingManager().getSettings(client); if ( shoppingSettings.isEnabled() ) { Set<ShoppingCategory> shoppingCategories = getRewardsCategoriesModelInterceptor().getValidShoppingCategories(model); if (shoppingCategories.isEmpty() || shoppingCategories.size() > MAX_CATEGORY_MENU_SIZE) { computedMenu.put("msg.rewards.user.shoppings.index.title", "/rewards/user/shoppings/index.html"); } else { for (ShoppingCategory shoppingCategory : shoppingCategories) { computedMenu.put(shoppingCategory.getTitle().get(lang), "/rewards/user/shoppings/index.html?categoryid=" + shoppingCategory.getSer()); } } } RaffleSettings raffleSettings = getRaffleManager().getSettings(client); if ( raffleSettings.isEnabled() ) { computedMenu.put("msg.rewards.user.raffles.index.title", "/rewards/user/raffles/index.html"); } if ( !computedMenu.isEmpty() ) { menu.put("msg.rewards.user.menu", computedMenu); } } // We already manipulated the menu from the model and don't need // to add any more items // return Collections.emptyMap(); } public ShoppingManager getShoppingManager() { return shoppingManager; } @Autowired public void setShoppingManager(ShoppingManager shoppingManager) { this.shoppingManager = shoppingManager; } public RaffleManager getRaffleManager() { return raffleManager; } @Autowired public void setRaffleManager(RaffleManager raffleManager) { this.raffleManager = raffleManager; } public RewardsCategoriesModelInterceptor getRewardsCategoriesModelInterceptor() { return rewardsCategoriesModelInterceptor; } @Autowired public void setRewardsCategoriesModelInterceptor(RewardsCategoriesModelInterceptor rewardsCategoriesModelInterceptor) { this.rewardsCategoriesModelInterceptor = rewardsCategoriesModelInterceptor; } }
33.509677
140
0.77166
2bab28d78d2483d728cbfa0b56666c508197b0da
3,901
package org.bbop.apollo.web.dataadapter.gff3; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.bbop.apollo.web.datastore.JEDatabase; import org.gmod.gbol.bioObject.AbstractSingleLocationBioFeature; import org.gmod.gbol.bioObject.conf.BioObjectConfiguration; import org.gmod.gbol.bioObject.io.GFF3Handler; import org.gmod.gbol.bioObject.util.BioObjectUtil; import org.gmod.gbol.simpleObject.Feature; import org.gmod.gbol.simpleObject.FeatureRelationship; import org.gmod.gbol.simpleObject.io.SimpleObjectIOException; public class Gff3JEDatabaseIO extends Gff3IO { private JEDatabase jeDatabase; private BioObjectConfiguration conf; private String source; public Gff3JEDatabaseIO(String databaseDir, String path, String source, BioObjectConfiguration conf, Set<String> metaDataToExport) throws Exception { this(databaseDir, path, source, conf, true, GFF3Handler.Format.GZIP, metaDataToExport); } public Gff3JEDatabaseIO(String databaseDir, String path, String source, BioObjectConfiguration conf, boolean readOnly, Set<String> metaDataToExport) throws Exception { this(databaseDir, path, source, conf, readOnly, GFF3Handler.Format.GZIP, metaDataToExport); } public Gff3JEDatabaseIO(String databaseDir, String path, String source, BioObjectConfiguration conf, boolean readOnly, GFF3Handler.Format format, Set<String> metaDataToExport) throws Exception { super(path, source, format, metaDataToExport); this.conf = conf; setJeDatabase(databaseDir, readOnly); } public void setJeDatabase(String databaseDir, boolean readOnly) { if (jeDatabase != null) { jeDatabase.close(); } jeDatabase = new JEDatabase(databaseDir, readOnly); } public Collection<? extends Feature> writeFeatures(Feature sourceFeature, String source) throws SimpleObjectIOException, IOException { FeatureIterator featureIterator = new FeatureIterator(jeDatabase.getFeatureIterator(), sourceFeature); writeFeatures(featureIterator, source, true); FeatureIterator sequenceAlterationIterator = new FeatureIterator(jeDatabase.getSequenceAlterationIterator(), sourceFeature); writeFeatures(sequenceAlterationIterator, source, false); Collection<Feature> sequenceAlterations = new ArrayList<Feature>(); Iterator<Feature> iter = jeDatabase.getSequenceAlterationIterator(); while (iter.hasNext()) { sequenceAlterations.add(iter.next()); } return sequenceAlterations; } @Override public void close() { super.close(); if (jeDatabase != null) { jeDatabase.close(); } } private void addSourceFeature(AbstractSingleLocationBioFeature feature, Feature sourceFeature) { feature.getFeatureLocation().setSourceFeature(sourceFeature); for (AbstractSingleLocationBioFeature child : feature.getChildren()) { addSourceFeature(child, sourceFeature); } } private void setName(Feature feature) { if (feature.getName() == null) { feature.setName(feature.getUniqueName()); } for (FeatureRelationship fr : feature.getChildFeatureRelationships()) { setName(fr.getSubjectFeature()); } } private class FeatureIterator implements Iterator<AbstractSingleLocationBioFeature> { private Iterator<Feature> iterator; private Feature sourceFeature; public FeatureIterator(Iterator<Feature> iterator, Feature sourceFeature) { this.iterator = iterator; this.sourceFeature = sourceFeature; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public AbstractSingleLocationBioFeature next() { Feature gsolFeature = iterator.next(); setName(gsolFeature); AbstractSingleLocationBioFeature feature = (AbstractSingleLocationBioFeature)BioObjectUtil.createBioObject(gsolFeature, conf); addSourceFeature(feature, sourceFeature); return feature; } @Override public void remove() { } } }
34.219298
195
0.784414
c2c080dd0fcbeb285c373c0540a1b55accae189c
68
package com.benayn.ustyle.base; public enum EnumType { T1,T2,T3 }
11.333333
31
0.735294
9373cd4cb9f825649334339e3704d1d514ec8975
602
package chapter07; import com.google.common.collect.Lists; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import java.util.List; public class TradeBuyAuditor { private List<BuyEvent> buyEvents = Lists.newArrayList(); public TradeBuyAuditor(EventBus eventBus) { eventBus.register(this); } @Subscribe public void auditBuy(BuyEvent buyEvent) { buyEvents.add(buyEvent); System.out.println("Received Trade Buy Event " + buyEvent); } public List<BuyEvent> getBuyEvents() { return buyEvents; } }
22.296296
67
0.702658
9afbb485283de851cdcf5a562ab321a885b86f64
827
package COM; public class Calculation { public static int countWhitePoints(int[][] my2DArray) { int theMax = 0; for (int i = 0; i < my2DArray.length; i++) { for (int j = 0; j < my2DArray[i].length; j++) { if (my2DArray[i][j] == 255) { theMax++; } } } return theMax; } public static int[][] brightPicture(int[][] my2DArray) { for (int i = 0; i < my2DArray.length; i++) { for (int j = 0; j < my2DArray[i].length; j++) { if (my2DArray[i][j] + 30 > 255) { my2DArray[i][j] = 255; } else { my2DArray[i][j] += 30; } } } return my2DArray; } }
27.566667
61
0.392987
f808c1d1181ea344724ab164531742e4757e3926
1,320
package com.callerscreendialer.theme.yourthemenamehere; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.callerscreendialer.themeclickevent.ApplyClickEvent; public class MainActivity extends AppCompatActivity { Button Apply; TextView MAKE_YOUR_THEME; ApplyClickEvent applyClickEvent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Apply = (Button)findViewById(R.id.GoToCSD); MAKE_YOUR_THEME = (TextView)findViewById(R.id.make_theme); applyClickEvent = new ApplyClickEvent(); // Must Use this class for perform Apply button and Make Theme Click Events Apply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { applyClickEvent.ApplyClickEvent_Function(MainActivity.this); } }); MAKE_YOUR_THEME.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { applyClickEvent.MakeYourTheme_Function(MainActivity.this); } }); } }
29.333333
124
0.69697
fc70eb376ccf078cfb733ed45bf80d05d52bd0ae
3,666
package com.publiccms.logic.component.site; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import com.publiccms.common.base.AbstractTaskDirective; import com.publiccms.common.base.AbstractTemplateDirective; import com.publiccms.common.base.BaseMethod; import com.publiccms.common.constants.CommonConstants; /** * * DirectiveComponent 指令处理组件 * */ public class DirectiveComponent { private String directiveRemoveRegex; private String methodRemoveRegex; protected final Log log = LogFactory.getLog(getClass()); private Map<String, AbstractTemplateDirective> templateDirectiveMap = new HashMap<>(); private Map<String, AbstractTaskDirective> taskDirectiveMap = new HashMap<>(); private Map<String, BaseMethod> methodMap = new HashMap<>(); public String getDirectiveName(String className) { return StringUtils.uncapitalize(className.replaceAll(directiveRemoveRegex, CommonConstants.BLANK)); } @Autowired private void init(List<AbstractTemplateDirective> templateDirectiveList, List<AbstractTaskDirective> taskDirectiveList, List<BaseMethod> methodList) { for (AbstractTemplateDirective directive : templateDirectiveList) { if (null == directive.getName()) { directive.setName(getDirectiveName(directive.getClass().getSimpleName())); } templateDirectiveMap.put(directive.getName(), directive); } log.info(new StringBuilder().append(templateDirectiveMap.size()).append(" template directives created:") .append(templateDirectiveMap.keySet()).toString()); for (AbstractTaskDirective directive : taskDirectiveList) { if (null == directive.getName()) { directive.setName(getDirectiveName(directive.getClass().getSimpleName())); } taskDirectiveMap.put(directive.getName(), directive); } log.info(new StringBuilder().append(taskDirectiveMap.size()).append(" task directives created:") .append(taskDirectiveMap.keySet()).toString()); for (BaseMethod method : methodList) { if (null == method.getName()) { method.setName(StringUtils.uncapitalize(method.getClass().getSimpleName().replaceAll(methodRemoveRegex, CommonConstants.BLANK))); } methodMap.put(method.getName(), method); } log.info(new StringBuilder().append(methodMap.size()).append(" methods created:").append(methodMap.keySet()).toString()); } /** * @param directiveRemoveRegex */ public void setDirectiveRemoveRegex(String directiveRemoveRegex) { this.directiveRemoveRegex = directiveRemoveRegex; } /** * @param methodRemoveRegex */ public void setMethodRemoveRegex(String methodRemoveRegex) { this.methodRemoveRegex = methodRemoveRegex; } /** * @return template directive map */ public Map<String, AbstractTemplateDirective> getTemplateDirectiveMap() { return templateDirectiveMap; } /** * @return task directive map */ public Map<String, AbstractTaskDirective> getTaskDirectiveMap() { return taskDirectiveMap; } /** * @return method map */ public Map<String, BaseMethod> getMethodMap() { return methodMap; } }
37.030303
146
0.671304
30d96a547989d63000aa9653c68ff5a9fa2c524c
1,434
package org.astraea.performance; import com.beust.jcommander.ParameterException; import java.util.stream.Stream; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.record.CompressionType; import org.astraea.argument.ArgumentUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class CompressionArgumentTest { @Test void testConversion() { var arg = new Performance.CompressionArgument(); Stream.of(CompressionType.values()) .forEach(type -> Assertions.assertEquals(type, arg.convert(type.name))); Assertions.assertThrows(ParameterException.class, () -> arg.convert("aaa")); } @Test void testParse() { var arg = ArgumentUtil.parseArgument( new Performance.Argument(), new String[] {"--bootstrap.servers", "aa", "--compression", "gzip"}); Assertions.assertEquals(CompressionType.GZIP, arg.compression); Assertions.assertEquals( "gzip", arg.producerProps().get(ProducerConfig.COMPRESSION_TYPE_CONFIG)); Assertions.assertNull(arg.props().get(ProducerConfig.COMPRESSION_TYPE_CONFIG)); } @Test void testJmxServer() { var arg = ArgumentUtil.parseArgument( new Performance.Argument(), new String[] {"--bootstrap.servers", "aa", "--jmx.servers", "aaa"}); Assertions.assertEquals("aaa", arg.producerProps().get("jmx_servers")); } }
34.142857
83
0.706416
3ac32dbc7161ea95f37e5cddfa6a05c1f54fb4b4
3,701
/******************************************************************************* * Copyright 2006 - 2014 Vienna University of Technology, * Department of Software Technology and Interactive Systems, IFS * * 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 eu.scape_project.planning.plato.bean; import java.io.Serializable; import java.util.List; import java.util.Map; import javax.faces.context.FacesContext; import org.ajax4jsf.model.DataVisitor; import org.ajax4jsf.model.ExtendedDataModel; import org.ajax4jsf.model.Range; import org.ajax4jsf.model.SequenceRange; import eu.scape_project.planning.services.IServiceInfo; /** * Data model for service infos. */ public class ServiceInfoDataModel extends ExtendedDataModel<IServiceInfo> implements Serializable { private static final long serialVersionUID = -31472856376172968L; private Integer rowKey; private List<IServiceInfo> serviceInfos; private Map<String, IServiceLoader> serviceLoaders; /** * Creates a new service info data model. * * @param serviceInfos * list of service infos * @param serviceLoaders * map of service identifiers and their loaders */ public ServiceInfoDataModel(List<IServiceInfo> serviceInfos, Map<String, IServiceLoader> serviceLoaders) { this.serviceInfos = serviceInfos; this.serviceLoaders = serviceLoaders; } @Override public void setRowKey(Object key) { rowKey = (Integer) key; } @Override public Object getRowKey() { return rowKey; } @Override public void walk(FacesContext context, DataVisitor visitor, Range range, Object argument) { int firstRow = ((SequenceRange) range).getFirstRow(); for (int i = firstRow; (i < serviceInfos.size()) && (i < (firstRow + ((SequenceRange) range).getRows())); i++) { IServiceLoader serviceLoader = serviceLoaders.get(serviceInfos.get(i).getServiceIdentifier()); if (serviceLoader != null) { serviceLoader.load(serviceInfos.get(i)); } visitor.process(context, i, argument); } } @Override public boolean isRowAvailable() { return rowKey != null; } @Override public int getRowCount() { return serviceInfos.size(); } @Override public IServiceInfo getRowData() { return serviceInfos.get(rowKey); } @Override public int getRowIndex() { // Used for backwards compatibility with JSF 1 throw new UnsupportedOperationException(); } @Override public void setRowIndex(int rowIndex) { // Used for backwards compatibility with JSF 1 throw new UnsupportedOperationException(); } @Override public Object getWrappedData() { // Used for backwards compatibility with JSF 1 throw new UnsupportedOperationException(); } @Override public void setWrappedData(Object data) { // Used for backwards compatibility with JSF 1 throw new UnsupportedOperationException(); } }
30.841667
120
0.654418
6fbe3e5342cb9c4d75b9b6ebe3372549c66c6f2f
2,521
/* * Copyright (c) 2017, Board of Trustees of Leland Stanford Jr. University, * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.lockss.laaws.rs.util; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import com.fasterxml.jackson.databind.util.ISO8601Utils; import java.text.FieldPosition; import java.util.Date; /** * Extends ISO8601DateFormat to support formatting of RFC3339 date format. Same as ISO8601DateFormat but serializing * milliseconds. */ public class RFC3339DateFormat extends ISO8601DateFormat { /** * Formats a {@code Date} to the RFC3339 date format. * * @param date * A {@code Date} to format. * @param toAppendTo * A {@code StringBuffer} to append to. * @param fieldPosition * A {@code FieldPosition}. * @return */ @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { String value = ISO8601Utils.format(date, true); toAppendTo.append(value); return toAppendTo; } }
40.015873
116
0.750496
1289415419647b40ebef253a08131f5e98422513
4,150
package com.osafe.util; import java.util.List; import java.util.Map; import org.apache.ofbiz.base.util.StringUtil; import org.apache.ofbiz.base.util.UtilMisc; import org.apache.ofbiz.base.util.UtilValidate; import org.apache.ofbiz.entity.Delegator; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.util.EntityUtil; import javolution.util.FastList; import javolution.util.FastMap; import jxl.Cell; import jxl.Sheet; public class OsafeProductLoaderHelper { public static final String module = OsafeAdminUtil.class.getName(); public static List getDataList(List dataRows) { List dataList = FastList.newInstance(); for (int i=0 ; i < dataRows.size() ; i++) { Map mRow = (Map)dataRows.get(i); dataList.add(mRow); } return dataList; } public static List buildDataRows(List headerCols,Sheet s) { List dataRows = FastList.newInstance(); try { for (int rowCount = 1 ; rowCount < s.getRows() ; rowCount++) { Cell[] row = s.getRow(rowCount); if (row.length > 0) { Map mRows = FastMap.newInstance(); for (int colCount = 0; colCount < headerCols.size(); colCount++) { String colContent=null; try { colContent=row[colCount].getContents(); } catch (Exception e) { colContent=""; } mRows.put(headerCols.get(colCount),colContent); } dataRows.add(mRows); } } } catch (Exception e) {} return dataRows; } static Map featureTypeIdMap = FastMap.newInstance(); public static Map buildFeatureMap(Map featureTypeMap,String parseFeatureType, Delegator delegator) { if (UtilValidate.isNotEmpty(parseFeatureType)) { int iFeatIdx = parseFeatureType.indexOf(':'); if (iFeatIdx > -1) { String featureType = parseFeatureType.substring(0,iFeatIdx).trim(); String sFeatures = parseFeatureType.substring(iFeatIdx +1); String[] featureTokens = sFeatures.split(","); Map mFeatureMap = FastMap.newInstance(); for (int f=0;f < featureTokens.length;f++) { String featureId = ""; try { String featureTypeKey = StringUtil.removeSpaces(featureType).toUpperCase()+"~"+featureTokens[f].trim(); if(featureTypeIdMap.containsKey(featureTypeKey)) { featureId = (String) featureTypeIdMap.get(featureTypeKey); } else { List productFeatureList = delegator.findByAnd("ProductFeature", UtilMisc.toMap("productFeatureTypeId", StringUtil.removeSpaces(featureType).toUpperCase(), "productFeatureCategoryId", StringUtil.removeSpaces(featureType).toUpperCase(), "description", featureTokens[f].trim())); if(UtilValidate.isNotEmpty(productFeatureList)) { GenericValue productFeature = EntityUtil.getFirst(productFeatureList); featureId = productFeature.getString("productFeatureId"); } else { featureId = delegator.getNextSeqId("ProductFeature"); } } featureTypeIdMap.put(featureTypeKey, featureId); } catch (GenericEntityException e) { e.printStackTrace(); } mFeatureMap.put(""+featureId,""+featureTokens[f].trim()); } featureTypeMap.put(featureType, mFeatureMap); } } return featureTypeMap; } }
33.739837
295
0.543855
9eca545be74e8b2f10fd8806df616c27c1743d6a
4,307
package org.dhis2.fhir.adapter; /* * Copyright (c) 2004-2019, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.dhis2.fhir.adapter.converter.ZonedDateTimeToDateConverter; import org.dhis2.fhir.adapter.dhis.config.DhisEndpointConfig; import org.dhis2.fhir.adapter.dhis.security.DhisWebApiAuthenticationProvider; import org.dhis2.fhir.adapter.dhis.security.SecurityConfig; import org.dhis2.fhir.adapter.rest.RestTemplateCookieStore; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import javax.annotation.Nonnull; import java.time.ZonedDateTime; import java.util.Date; /** * Common application configuration. * * @author volsch */ @Configuration public class AppConfig { @Bean @Nonnull public AbstractUserDetailsAuthenticationProvider dhisWebApiAuthenticationProvider( @Nonnull RestTemplateBuilder restTemplateBuilder, @Nonnull DhisEndpointConfig dhisEndpointConfig, @Nonnull SecurityConfig securityConfig, @Nonnull @Qualifier( "dhisClientHttpRequestFactory" ) ClientHttpRequestFactory clientHttpRequestFactory, @Nonnull @Qualifier( "dhisCookieStore" ) RestTemplateCookieStore cookieStore ) { return new DhisWebApiAuthenticationProvider( restTemplateBuilder, dhisEndpointConfig, securityConfig, clientHttpRequestFactory, cookieStore ); } @Bean @Nonnull public WebMvcConfigurer mvcConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings( @Nonnull CorsRegistry registry ) { registry.addMapping( "/scripts/**" ) .allowedOrigins( "*" ) .allowedMethods( HttpMethod.GET.name() ) .exposedHeaders( HttpHeaders.CACHE_CONTROL, HttpHeaders.CONTENT_LANGUAGE, HttpHeaders.CONTENT_TYPE, HttpHeaders.EXPIRES, HttpHeaders.LAST_MODIFIED, HttpHeaders.PRAGMA, HttpHeaders.CONTENT_LENGTH, HttpHeaders.ETAG ); } @Override public void addFormatters( @Nonnull FormatterRegistry registry ) { registry.addConverter( ZonedDateTime.class, Date.class, new ZonedDateTimeToDateConverter() ); } }; } }
47.32967
235
0.768516
11255c2842104a07157fbc0d200ef27c9bdb3a6a
8,649
package com.volvain.yash; import android.content.Context; import android.util.Log; import com.volvain.yash.DAO.Database; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Map; public class Server { static int first=0; URL url; HttpURLConnection con; static String serverUri; String message=""; Context context; Server(Context context){ this.context=context; serverUri=context.getString(R.string.server); } public String getUserLoc(Long id){ String result=""; try{ url=new URL(serverUri+"GetUserLoc?id="+id); con=(HttpURLConnection)url.openConnection(); BufferedInputStream in=new BufferedInputStream(con.getInputStream()); int i=0; while((i=in.read())!=-1)result+=(char)i; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.i("userData",result); return result; } public int SendUserLoc(Long id,String locDetails){ int b=0; try{ url=new URL(serverUri+"SetUserLoc?id="+id+"&locDetails="+locDetails); Log.i("gauravrmsc","set1"+url.toString()); con=(HttpURLConnection)url.openConnection(); Log.i("gauravrmsc","set2"); BufferedInputStream i=new BufferedInputStream(con.getInputStream()); Log.i("gauravrmsc","set3"); b=Integer.parseInt(""+(char)i.read()); Log.i("gauravrmsc","set4"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return b; } public String Signup(Long phone,String name,String password){ try { url =new URL(serverUri+"/signup?phone="+phone+"&name="+name+"&password="+password); con=(HttpURLConnection) url.openConnection(); BufferedInputStream i=new BufferedInputStream(con.getInputStream()); int b=0; while((b=i.read())!=-1)message+=(char)b; } catch (MalformedURLException e) { return e.toString(); } catch (IOException e) { Log.i("Error",url.toString()); return e.toString(); } return message; } public int firstHelpRequest(Long id,String name,Double longitude,Double latitude,String message){ Log.i("gauravrmsc","Sending first request"); int m=-1; try { url=new URL(serverUri+"/fstReq?id="+id+"&name="+name+"&longitude="+longitude+"&latitude="+latitude+"&message="+message); con=(HttpURLConnection)url.openConnection(); BufferedInputStream i=new BufferedInputStream(con.getInputStream()); Log.i("gauravrmsc","received first request"); /* int b=-; while((b=i.read())!=-1)message+=(char)b;*/ m=Integer.parseInt(""+(char)i.read()); first=1; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return m; //return message; } public ArrayList getProfile(Long id){ Log.i("gkm","2"); ArrayList<String> profileDetails=new ArrayList<>(); try{ Log.i("gkm","3"); url=new URL(serverUri+"GetProfile?id="+id); con=(HttpURLConnection)url.openConnection(); BufferedInputStream i=new BufferedInputStream(con.getInputStream()); String result=""; int c; while((c=i.read())!=-1){ result+=(char)c; } Log.i("gkm","4"); JSONObject profile=(JSONObject) new JSONParser().parse(result); String profession=profile.get("profession").toString(); String professionDesc=profile.get("professionDesc").toString(); profileDetails.add(0,profession); profileDetails.add(1,professionDesc); }catch(MalformedURLException e){} catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return profileDetails; } public int setProfile(Long id,String profession,String professionDesc){ int i=0; try { url=new URL(serverUri+"SetProfile?id="+id+"&Profession="+profession+"&ProfessionDesc="+professionDesc); Log.i("gauravrmsc",""+url); con=(HttpURLConnection)url.openConnection(); BufferedInputStream in=new BufferedInputStream(con.getInputStream()); i=Integer.parseInt(""+(char)in.read()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.i("gkk","6"); return i; } public int subsequentHelpRequest(Long id,Double longitude,Double latitude){ Log.i("gauravrmsc","Sending Subsequent request"); int m=-2; try { if(first>0) { url = new URL(serverUri + "/subsequentReq?id=" + id + "&longitude=" + longitude + "&latitude=" + latitude); con = (HttpURLConnection) url.openConnection(); BufferedInputStream i = new BufferedInputStream(con.getInputStream()); Log.i("gauravrmsc", "received Subsequent request"); /*int b=0; while((b=i.read())!=-1)message+=(char)b;*/ m = Integer.parseInt("" + (char) i.read()); }} catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { Log.i("gauravrmsc",""+e); e.printStackTrace(); } return m; } public void sync(Long myId){ String outputMessage=""; try { url=new URL(serverUri+"/sync?id="+myId); con=(HttpURLConnection)url.openConnection(); BufferedInputStream i=new BufferedInputStream(con.getInputStream()); Log.i("gauravrmsc","response received"); int b=0; /* if((b=i.read())==-1){ Log.i("gauravrmsc","Server sent null"); return; } else{ outputMessage+=(char)b;*/ while((b=i.read())!=-1)outputMessage+=(char)b; Log.i("gauravrmsc","response received="+outputMessage); JSONArray ary=(JSONArray) new JSONParser().parse(outputMessage); for (int n=0;n<ary.size();n++) { Map m=(Map)ary.get(n); /* Long id = Long.parseLong(m.get("id").toString()); Double longitude = Double.parseDouble(m.get("longitude").toString()); Double latitude = Double.parseDouble(obj.get("latitude").toString()); String name = obj.get("name").toString();*/ Long id=(Long)m.get("id"); Double longitude=(Double)m.get("longitude"); Double latitude=(Double)m.get("latitude"); String name=m.get("name").toString(); String message=m.get("message").toString(); Log.i("gauravrmsc","longitude="+longitude); Database db= new Database(context); db.updatHelp(id,name,longitude,latitude,message); } //} } catch (MalformedURLException e) { e.printStackTrace(); Log.i("gauravrmsc",""+e); } catch (IOException e) { e.printStackTrace(); Log.i("gauravrmsc",""+e); } catch (ParseException e) { e.printStackTrace(); Log.i("gauravrmsc","Parse Exception"+e); } } public boolean login(Long id,String password){ try { url=new URL(serverUri+"/login?id="+id+"&password="+password); con=(HttpURLConnection)url.openConnection(); BufferedInputStream i=new BufferedInputStream(con.getInputStream()); int b=0; while((b=i.read())!=-1)message+=(char)b; if(!(message.equals("Invalid Password") || message.equals("Invalid User Name"))){ //TODO put name and id in database and remove if any exist before Database db= new Database(context); db.deleteHelp();//TODO add to logout db.deletLogIn();//TODO add to logout db.insertData(id,message); return true;} } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } }
33.265385
132
0.587814
dc75e09c19b8d0108805ac49dd6d6a42612a09d0
5,014
package com.sequenceiq.redbeams.flow.redbeams.provision; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.sequenceiq.cloudbreak.api.endpoint.v4.common.DatabaseVendor; import com.sequenceiq.cloudbreak.auth.altus.Crn; import com.sequenceiq.cloudbreak.cloud.context.CloudContext; import com.sequenceiq.cloudbreak.cloud.model.CloudResource; import com.sequenceiq.cloudbreak.cloud.transform.CloudResourceHelper; import com.sequenceiq.common.api.type.ResourceType; import com.sequenceiq.redbeams.TestData; import com.sequenceiq.redbeams.domain.DatabaseServerConfig; import com.sequenceiq.redbeams.domain.stack.DBStack; import com.sequenceiq.redbeams.domain.stack.DatabaseServer; import com.sequenceiq.redbeams.flow.redbeams.provision.event.register.UpdateDatabaseServerRegistrationRequest; import com.sequenceiq.redbeams.flow.redbeams.provision.handler.UpdateDatabaseServerRegistrationHandler; import com.sequenceiq.redbeams.service.dbserverconfig.DatabaseServerConfigService; import reactor.bus.Event; import reactor.bus.EventBus; public class UpdateDatabaseServerRegistrationHandlerTest { private static final String ACCOUNT_ID = "accountId"; private static final String DB_STACK_NAME = "dbStackName"; private static final String ENVIRONMENT_CRN = "environmentCrn"; private static final String CONNECTION_DRIVER = "connectionDriver"; private static final String ROOT_USER_NAME = "rootUserName"; private static final String ROOT_PASSWORD = "rootPassword"; private static final int PORT = 8642; private static final String DB_HOST_NAME = "dbHostName"; private static final Crn CRN = TestData.getTestCrn("database", "name"); @Mock private EventBus eventBus; @Mock private DatabaseServerConfigService databaseServerConfigService; @Mock private CloudResourceHelper cloudResourceHelper; @InjectMocks private UpdateDatabaseServerRegistrationHandler underTest; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test public void testAccept() { Event event = mock(Event.class); DBStack dbStack = new DBStack(); dbStack.setName(DB_STACK_NAME); dbStack.setEnvironmentId(ENVIRONMENT_CRN); dbStack.setResourceCrn(CRN); DatabaseServer databaseServer = new DatabaseServer(); dbStack.setDatabaseServer(databaseServer); databaseServer.setAccountId(ACCOUNT_ID); databaseServer.setConnectionDriver(CONNECTION_DRIVER); databaseServer.setRootUserName(ROOT_USER_NAME); databaseServer.setRootPassword(ROOT_PASSWORD); databaseServer.setDatabaseVendor(DatabaseVendor.POSTGRES); databaseServer.setPort(PORT); UpdateDatabaseServerRegistrationRequest request = getRequest(dbStack); when(event.getData()).thenReturn(request); setupCloudresourceMocks(DB_HOST_NAME, ResourceType.RDS_HOSTNAME); setupCloudresourceMocks(Integer.toString(PORT), ResourceType.RDS_PORT); DatabaseServerConfig originalDatabaseServerConfig = new DatabaseServerConfig(); originalDatabaseServerConfig.setHost(null); originalDatabaseServerConfig.setPort(null); when(databaseServerConfigService.getByCrn(CRN)).thenReturn(Optional.of(originalDatabaseServerConfig)); underTest.accept(event); ArgumentCaptor<DatabaseServerConfig> databaseServerConfigCaptor = ArgumentCaptor.forClass(DatabaseServerConfig.class); verify(databaseServerConfigService).update(databaseServerConfigCaptor.capture()); DatabaseServerConfig databaseServerConfig = databaseServerConfigCaptor.getValue(); assertEquals(DB_HOST_NAME, databaseServerConfig.getHost()); assertEquals(PORT, databaseServerConfig.getPort().intValue()); } private void setupCloudresourceMocks(String dbHostName2, ResourceType rdsHostname) { CloudResource dbHostName = mock(CloudResource.class); when(dbHostName.getName()).thenReturn(dbHostName2); when(cloudResourceHelper.getResourceTypeFromList(eq(rdsHostname), any())).thenReturn(Optional.of(dbHostName)); } private UpdateDatabaseServerRegistrationRequest getRequest(DBStack dbStack) { UpdateDatabaseServerRegistrationRequest request = mock(UpdateDatabaseServerRegistrationRequest.class); when(request.getDbResources()).thenReturn(mock(List.class)); when(request.getDBStack()).thenReturn(dbStack); when(request.getCloudContext()).thenReturn(mock(CloudContext.class)); return request; } }
40.764228
126
0.779817
bf8c1abadd9a0bc242969cf6c9711db7fec1a701
3,621
package uk.gov.ons.ctp.response.casesvc.scheduled; import com.godaddy.logging.Logger; import com.godaddy.logging.LoggerFactory; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import uk.gov.ons.ctp.common.distributed.DistributedInstanceManager; import uk.gov.ons.ctp.common.distributed.DistributedLatchManager; import uk.gov.ons.ctp.common.distributed.DistributedLockManager; import uk.gov.ons.ctp.response.casesvc.service.CaseReportService; /** * The scheduler to trigger reports creation based on a cron expression defined in application.yml */ @Component public class ReportScheduler { private static final Logger log = LoggerFactory.getLogger(ReportScheduler.class); private static final String DISTRIBUTED_OBJECT_KEY_REPORT_LATCH = "reportlatch"; private static final String DISTRIBUTED_OBJECT_KEY_INSTANCE_COUNT = "reportscheduler"; private static final String DISTRIBUTED_OBJECT_KEY_REPORT = "report"; @Autowired private CaseReportService caseReportService; @Autowired private DistributedLockManager reportDistributedLockManager; @Autowired private DistributedInstanceManager reportDistributedInstanceManager; @Autowired private DistributedLatchManager reportDistributedLatchManager; /** Initialise report scheduler */ @PostConstruct public void init() { reportDistributedInstanceManager.incrementInstanceCount(DISTRIBUTED_OBJECT_KEY_INSTANCE_COUNT); log.with( "instance_count", reportDistributedInstanceManager.getInstanceCount( DISTRIBUTED_OBJECT_KEY_INSTANCE_COUNT)) .info("Redis instance(s) running"); } /** Clean up report scheduler on bean destruction */ @PreDestroy public void cleanUp() { reportDistributedInstanceManager.decrementInstanceCount(DISTRIBUTED_OBJECT_KEY_INSTANCE_COUNT); reportDistributedLockManager.unlockInstanceLocks(); log.with( "instance_count", reportDistributedInstanceManager.getInstanceCount( DISTRIBUTED_OBJECT_KEY_INSTANCE_COUNT)) .info("Redis instance(s) running"); } /** The method triggering report creation. */ @Scheduled(cron = "#{appConfig.reportSettings.cronExpression}") public void createReport() { log.debug("Entering createReport..."); reportDistributedLatchManager.setCountDownLatch( DISTRIBUTED_OBJECT_KEY_REPORT_LATCH, reportDistributedInstanceManager.getInstanceCount(DISTRIBUTED_OBJECT_KEY_INSTANCE_COUNT)); if (!reportDistributedLockManager.isLocked(DISTRIBUTED_OBJECT_KEY_REPORT)) { if (reportDistributedLockManager.lock(DISTRIBUTED_OBJECT_KEY_REPORT)) { caseReportService.createReport(); } } try { reportDistributedLatchManager.countDown(DISTRIBUTED_OBJECT_KEY_REPORT_LATCH); if (!reportDistributedLatchManager.awaitCountDownLatch(DISTRIBUTED_OBJECT_KEY_REPORT_LATCH)) { log.with( "instance_count", reportDistributedInstanceManager.getInstanceCount( DISTRIBUTED_OBJECT_KEY_INSTANCE_COUNT)) .error("Report run error countdownlatch timed out"); } } catch (InterruptedException e) { log.error("Report run error waiting for countdownlatch", e); } finally { reportDistributedLockManager.unlock(DISTRIBUTED_OBJECT_KEY_REPORT); reportDistributedLatchManager.deleteCountDownLatch(DISTRIBUTED_OBJECT_KEY_REPORT_LATCH); } } }
40.685393
100
0.773819
019f919aba23ab48c5c2789db5d36e83f08755d0
423
//------------------------------------------------------------------ // Copyright 2020 mobile.de GmbH. // Author/Developer: Philipp Bartsch // // This code is licensed under MIT license (see LICENSE for details) //------------------------------------------------------------------ package org.example.move.webhookreceiver.rest.listing; public interface IsListing { String getForeignId(); String getEntityId(); }
28.2
68
0.503546
1d103beafda5c5430e7b723c20ed693b68001a46
1,867
package org.springframework.expression.spel.support; import java.lang.reflect.Method; /** * A {@link org.springframework.expression.PropertyAccessor} variant for data binding * purposes, using reflection to access properties for reading and possibly writing. * * A property can be referenced through a public getter method (when being read) * or a public setter method (when being written), and also as a public field. * * This accessor is explicitly designed for user-declared properties and does not * resolve technical properties on {@code java.lang.Object} or {@code java.lang.Class}. * For unrestricted resolution, choose {@link ReflectivePropertyAccessor} instead. * * @since 4.3.15 * @see #forReadOnlyAccess() * @see #forReadWriteAccess() * @see SimpleEvaluationContext * @see StandardEvaluationContext * @see ReflectivePropertyAccessor */ public final class DataBindingPropertyAccessor extends ReflectivePropertyAccessor { /** * Create a new property accessor for reading and possibly also writing. * @param allowWrite whether to also allow for write operations * @see #canWrite */ private DataBindingPropertyAccessor(boolean allowWrite) { super(allowWrite); } @Override protected boolean isCandidateForProperty(Method method, Class<?> targetClass) { Class<?> clazz = method.getDeclaringClass(); return (clazz != Object.class && clazz != Class.class && !ClassLoader.class.isAssignableFrom(targetClass)); } /** * Create a new data-binding property accessor for read-only operations. */ public static DataBindingPropertyAccessor forReadOnlyAccess() { return new DataBindingPropertyAccessor(false); } /** * Create a new data-binding property accessor for read-write operations. */ public static DataBindingPropertyAccessor forReadWriteAccess() { return new DataBindingPropertyAccessor(true); } }
31.644068
109
0.763792
0835b74306e5f1de813f9beabca0dc5aec48d1fb
5,483
package com.tobe.niuniu.core; import java.util.HashMap; import java.util.Map; import java.util.Stack; /*** * The object of NiuGame represent one real game of dealer or one player. */ public class NiuGame { public final static int ALL_CARD_NUMBER = 52; public final static int ALL_CARD_COMBINATION = 2598960; public final static int CARD_COMBINATION_WITHOUT_PLAYER = 1065021; // 2598960 - 1533939 private Player player = null; private NiuResult playerResult = null; private int playerWinCount = 0; private static Stack<Integer> selectedStack = new Stack<Integer>(); // The count of all the cards from niu 1 to niu niu private Map<Integer, Integer> allNiuCount = new HashMap<Integer, Integer>(); { allNiuCount.put(0, 0); allNiuCount.put(1, 0); allNiuCount.put(2, 0); allNiuCount.put(3, 0); allNiuCount.put(4, 0); allNiuCount.put(5, 0); allNiuCount.put(6, 0); allNiuCount.put(7, 0); allNiuCount.put(8, 0); allNiuCount.put(9, 0); allNiuCount.put(10, 0); } public NiuGame() { } public NiuGame(Player player) { this.player = player; } public void printAllProbability() { combineAlgorithm(0, 0, Player.PLAYER_CARD_NUMBER, ALL_CARD_NUMBER); StringBuilder stringBuilder = new StringBuilder("The probability of NiuNiu: \n"); for (int i = 0; i <= 10; ++i) { double probability = this.allNiuCount.get(i) * 100.0 / ALL_CARD_COMBINATION; if (i == 0) { stringBuilder.append(String.format("No niu: count %d, percentage %f%% \n", this.allNiuCount.get(i), probability)); } else if (i == 10) { int jqkNiuniuCount = 4368; double jqkNiuniuProbability = jqkNiuniuCount * 100.0 / ALL_CARD_COMBINATION; int normalNiuniuCount = this.allNiuCount.get(i) - 4368; double normalNiuniuProbability = normalNiuniuCount * 100.0 / ALL_CARD_COMBINATION; stringBuilder.append(String.format("Niu niu: count %d, percentage %f%% \n", normalNiuniuCount, normalNiuniuProbability)); stringBuilder.append(String.format("Niu niu(JQK): count %d, percentage %f%% \n", jqkNiuniuCount, jqkNiuniuProbability)); } else { stringBuilder.append(String.format("Niu %d: count %d, percentage %f%% \n", i, this.allNiuCount.get(i), probability)); } } System.out.println(stringBuilder.toString()); } public void printWinProbability() { if (this.player == null) { System.out.println("Error, the player should not be null"); System.exit(-1); } this.playerResult = this.player.computeResult(); combineAlgorithmForPlayer(0, 0, Player.PLAYER_CARD_NUMBER, ALL_CARD_NUMBER); System.out.println(this.player); System.out.println(String.format("Win probability: %f%%", this.playerWinCount * 100.0 / ALL_CARD_COMBINATION)); } public static void main(String[] argv) { // NiuGame game = new NiuGame(); // game.printAllProbability(); Player player = new Player(new int[]{12, 21, 31, 43, 23}); NiuGame game = new NiuGame(player); game.printWinProbability(); } private void combineAlgorithm(int currentSelectedNumber, int nextSelectableValue, int numberToSelect, int maxAvaibleValue){ if(currentSelectedNumber == numberToSelect){ // System.out.println(selectedStack); handleCombination(); return; } for(int i = nextSelectableValue; i < maxAvaibleValue; ++i) { selectedStack.push(i); combineAlgorithm(currentSelectedNumber + 1, i + 1, numberToSelect, maxAvaibleValue); selectedStack.pop(); } } private void handleCombination() { int card0 = selectedStack.get(0); int card1 = selectedStack.get(1); int card2 = selectedStack.get(2); int card3 = selectedStack.get(3); int card4 = selectedStack.get(4); Player player = new Player(new int[]{card0, card1, card2, card3, card4}); NiuResult result = player.computeResult(); //System.out.println(result); increaseNiuCount(result.getNiu()); } private void increaseNiuCount(int niu) { this.allNiuCount.put(niu, this.allNiuCount.get(niu) + 1); } private void combineAlgorithmForPlayer(int currentSelectedNumber, int nextSelectableValue, int numberToSelect, int maxAvaibleValue){ if(currentSelectedNumber == numberToSelect){ compareWithPlayer(); return; } for(int i = nextSelectableValue; i < maxAvaibleValue; ++i) { selectedStack.push(i); combineAlgorithmForPlayer(currentSelectedNumber + 1, i + 1, numberToSelect, maxAvaibleValue); selectedStack.pop(); } } private void compareWithPlayer() { int card0 = selectedStack.get(0); int card1 = selectedStack.get(1); int card2 = selectedStack.get(2); int card3 = selectedStack.get(3); int card4 = selectedStack.get(4); Player player = new Player(new int[]{card0, card1, card2, card3, card4}); NiuResult result = player.computeResult(); if (this.playerResult.largerOrEqual(result)) { this.playerWinCount += 1; } } }
33.432927
137
0.622834
9e533f33782639293249677a0c0da5943057e435
3,685
package com.kimbrelk.android.hamlogger.utils; public final class Constants { public final static String PREFS_NAME = "prefs"; public final static class Extras { public final static String BOOK_ID = "com.kimbrelk.android.hamlogger.book_id"; public final static String BOOK_NAME = "com.kimbrelk.android.hamlogger.book_name"; public final static String ENTRY_ID = "com.kimbrelk.android.hamlogger.entry_id"; public final static String IS_NEW = "com.kimbrelk.android.hamlogger.is_new"; } public final static class Prefs { public final static String FIRST_RUN_TIMESTAMP = "first_run_timestamp"; public final static String IS_FIRST_RUN = "is_first_run"; public final static String IS_PRO = "is_pro"; public final static String LAST_VERIFIED_PRO = "last_verified_pro"; public final static String LAST_FREQ = "last_freq"; public final static String LAST_MODE = "last_mode"; public final static String LAST_MODE_SUB = "last_mode_sub"; public final static String LAST_OPERATOR = "last_op"; public final static String LEGACY_DB_LAST_UPDATE = "legacy_db_last_update"; public final static String SORT_MODE = "sort_mode"; } public final static class ScreenIds { public final static String VIEW_BOOKS = "ViewBooks"; public final static String VIEW_ENTRIES = "ViewEntries"; public final static String VIEW_ABOUT = "ViewAbout"; public final static String EDIT_BOOK = "EditBook"; public final static String EDIT_ENTRY = "EditEntry"; } public final static class EventParams { public final static String ERROR = "error"; } public final static class EventIds { public final static String CONTACT_EMAIL = "contact_email"; public final static String CONTACT_TWITTER = "contact_twitter"; public final static String CONTACT_PLAY = "contact_play"; public final static String CREATE_BOOK = "create_book"; public final static String CREATE_ENTRY = "create_entry"; public final static String DELETE_BOOK = "delete_book"; public final static String DELETE_ENTRY = "delete_entry"; public final static String DISCARD_BOOK = "discard_book"; public final static String DISCARD_ENTRY = "discard_entry"; public final static String EDIT_BOOK = "edit_book"; public final static String EDIT_ENTRY = "edit_entry"; public final static String PURCHASE_PRO_START = "purchase_pro_start"; public final static String PURCHASE_PRO_FAILED = "purchase_pro_failed"; public final static String PURCHASE_PRO_SUCCESS = "purchase_pro_success"; public final static String TAP_PRIVACY = "view_privacy_policy"; public final static String TAP_RATE = "rate_app"; } public final static class BillingResult { public final static int OK = 0; public final static int USER_CANCELED = 1; public final static int SERVICE_UNAVAILABLE = 2; public final static int BILLING_UNAVAILABLE = 3; public final static int ITEM_UNAVAILABLE = 4; public final static int DEVELOPER_ERROR = 5; public final static int ERROR = 6; public final static int ITEM_ALREADY_OWNED = 7; public final static int ITEM_NOT_OWNED = 8; } public final static class Request { public final static int PURCHASE_PRO = 1; public final static int IMPORT_ADI = 2; public final static int PERMISSION_STORAGE_EXTERNAL_READ = 3; } public final static class Time { public final static long MILLISECOND = 1; public final static long SECOND = MILLISECOND * 1000; public final static long MINUTE = SECOND * 60; public final static long HOUR = MINUTE * 60; public final static long HALF_DAY = HOUR * 12; public final static long DAY = HOUR * 24; public final static long WEEK = DAY * 7; public final static long MONTH = DAY * 30; } }
39.623656
84
0.76228
5b079867072271ed761060b993c996bd12b4bcc9
937
package com.my.learning.swt.viewer; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; public class NodeLabelProvider extends LabelProvider implements ITableLabelProvider { // @Override // public String getText(Object element) { // if (element instanceof INode) { // INode entry = (INode) element; // if (entry.getFile() == null) { // return null; // } // return entry.getFile().getName(); // } // return null; // } @Override public Image getColumnImage(Object element, int columnIndex) { return null; } @Override public String getColumnText(Object element, int columnIndex) { INode entry = (INode) element; if (entry.getFile() == null) { return null; } if(columnIndex == 0) { return entry.getFile().getName(); } else { return Long.valueOf(entry.getFile().lastModified()).toString(); } } }
24.025641
85
0.690502
3ac01c232d23e7f857a85d150ab919546b1b04d9
2,840
/** */ package ocl.exp; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Iterator Exp</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link ocl.exp.IteratorExp#getKind <em>Kind</em>}</li> * <li>{@link ocl.exp.IteratorExp#getBody <em>Body</em>}</li> * <li>{@link ocl.exp.IteratorExp#getIterator <em>Iterator</em>}</li> * </ul> * * @see ocl.exp.ExpPackage#getIteratorExp() * @model * @generated */ public interface IteratorExp extends CallExp { /** * Returns the value of the '<em><b>Kind</b></em>' attribute. * The literals are from the enumeration {@link ocl.exp.IteratorKind}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Kind</em>' attribute. * @see ocl.exp.IteratorKind * @see #setKind(IteratorKind) * @see ocl.exp.ExpPackage#getIteratorExp_Kind() * @model dataType="ocl.exp.IteratorKind" * @generated */ IteratorKind getKind(); /** * Sets the value of the '{@link ocl.exp.IteratorExp#getKind <em>Kind</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Kind</em>' attribute. * @see ocl.exp.IteratorKind * @see #getKind() * @generated */ void setKind(IteratorKind value); /** * Returns the value of the '<em><b>Body</b></em>' containment reference. * It is bidirectional and its opposite is '{@link ocl.exp.OclExpression#getLoopBodyOwner <em>Loop Body Owner</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Body</em>' containment reference. * @see #setBody(OclExpression) * @see ocl.exp.ExpPackage#getIteratorExp_Body() * @see ocl.exp.OclExpression#getLoopBodyOwner * @model opposite="loopBodyOwner" containment="true" required="true" * @generated */ OclExpression getBody(); /** * Sets the value of the '{@link ocl.exp.IteratorExp#getBody <em>Body</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Body</em>' containment reference. * @see #getBody() * @generated */ void setBody(OclExpression value); /** * Returns the value of the '<em><b>Iterator</b></em>' containment reference list. * The list contents are of type {@link ocl.exp.Variable}. * It is bidirectional and its opposite is '{@link ocl.exp.Variable#getLoopExp <em>Loop Exp</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Iterator</em>' containment reference list. * @see ocl.exp.ExpPackage#getIteratorExp_Iterator() * @see ocl.exp.Variable#getLoopExp * @model opposite="loopExp" containment="true" * @generated */ EList<Variable> getIterator(); } // IteratorExp
31.555556
118
0.647535
0c8cecf898f5d1b607a2fe99a9889fd120350779
2,480
/* * ============LICENSE_START======================================================= * ONAP : APPC * ================================================================================ * Copyright 2018 TechMahindra *================================================================================= * Modification Copyright 2018 IBM. *================================================================================= * 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. * ============LICENSE_END========================================================= */ package org.onap.appc.workflow.objects; import static org.junit.Assert.*; import org.junit.Test; import org.onap.appc.domainmodel.lcm.RequestContext; import org.onap.appc.domainmodel.lcm.ResponseContext; import org.onap.appc.domainmodel.lcm.VNFContext; public class TestWorkflowRequest { private WorkflowRequest workflowRequest=new WorkflowRequest(); @Test public void testToString_ReturnNonEmptyString() { assertNotEquals(workflowRequest.toString(), ""); assertNotEquals(workflowRequest.toString(), null); } @Test public void testToString_ContainsString() { assertTrue(workflowRequest.toString().contains("requestContext")); } @Test public void testGetRequestContext() { RequestContext requestContext= new RequestContext(); workflowRequest.setRequestContext(requestContext); assertEquals(requestContext, workflowRequest.getRequestContext()); } @Test public void testGetResponseContext() { ResponseContext responseContext= new ResponseContext(); workflowRequest.setResponseContext(responseContext); assertEquals(responseContext, workflowRequest.getResponseContext()); } @Test public void testGetVnfContext() { VNFContext vnfContext= new VNFContext(); workflowRequest.setVnfContext(vnfContext); assertEquals(vnfContext, workflowRequest.getVnfContext()); } }
38.75
82
0.623387
1446528b648ff38f09a6378932170a85f447d624
939
package com.hospital.application.views; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.Route; /** * Hospital Application. * <p> * Contact information. * * @author Dmitriy Kalistratov <dmitry@kalistratov.ru> * @version 1.0 */ @Route(value = "", layout = MainView.class) public class ContactsView extends VerticalLayout { /** * Constructor. * <p> * Create developer info. */ public ContactsView() { Label h1 = new Label("Developed by Dmitry Kalistratov"); Label h2 = new Label("m.num +7 (904) 330-28-66"); Label h3 = new Label("email dmitry@kalistratov.ru"); VerticalLayout verticalLayout = new VerticalLayout(h1, h2, h3); verticalLayout.setSizeFull(); verticalLayout.setDefaultHorizontalComponentAlignment(Alignment.CENTER); add(verticalLayout); } }
27.617647
80
0.681576
00dadbf5aef4c9dac3656ddb983702209dfb9893
1,849
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.contracts.sitesettings.general.general; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.joda.time.DateTime; import java.io.IOException; import java.lang.ClassNotFoundException; /** * Set whether you require users to be authenticated to preview content or view the live site. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ViewAuthorizations implements Serializable { // Default Serial Version UID private static final long serialVersionUID = 1L; /** * Specifies whether to enable secure communication across your entire site, using the SSL (Secure Socket Layer) security protocol. Every page on your site will display as an HTTPS page and contain an SSL certificate. */ protected Boolean enforceSitewideSSL; public Boolean getEnforceSitewideSSL() { return this.enforceSitewideSSL; } public void setEnforceSitewideSSL(Boolean enforceSitewideSSL) { this.enforceSitewideSSL = enforceSitewideSSL; } /** * Require log in to view live storefront site. */ protected Boolean requireAuthForLive; public Boolean getRequireAuthForLive() { return this.requireAuthForLive; } public void setRequireAuthForLive(Boolean requireAuthForLive) { this.requireAuthForLive = requireAuthForLive; } /** * Require log in to view pending storefront site. */ protected Boolean requireAuthForPending; public Boolean getRequireAuthForPending() { return this.requireAuthForPending; } public void setRequireAuthForPending(Boolean requireAuthForPending) { this.requireAuthForPending = requireAuthForPending; } }
28.446154
219
0.756625
eec0a97ed8f9535599c129dbe6fe7a36245a0d2a
2,009
package de.htw_berlin.ai.itsec.testwriter; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class TestReader { private FileReader testFile; private BufferedReader bufferedReader; private Map<String, String> valuesToRead; public TestReader(String filePath, Map<String, String> valuesToRead) throws FileNotFoundException { this.testFile = new FileReader(filePath); this.bufferedReader = new BufferedReader(testFile); this.valuesToRead = valuesToRead; } public Map<String, String> readTest() throws IOException { Map<String, String> values = new HashMap<String, String>(); String line, firstChar, value; int i = 0, valueCount = valuesToRead.size(); while (i != valueCount && (line = bufferedReader.readLine()) != null) { if (line.length() < 2) { continue; } firstChar = line.substring(0, 1); if (this.valuesToRead.containsKey(firstChar)) { i++; value = line.substring(2); values.put(valuesToRead.get(firstChar), value); } } if (values.isEmpty()) { return null; } return values; } public Map<String, String> readTestAndAddTestNumber(String titleVariable) throws IOException { Map<String, String> values = readTest(); if (null == values) { return null; } String testNumber = values.get(titleVariable); testNumber = testNumber.substring(testNumber.length() - 2); if (testNumber.charAt(0) == '-') { testNumber = testNumber.charAt(1) + ""; } values.put("number", testNumber); return values; } public void cleanUp() throws IOException { this.bufferedReader.close(); this.testFile.close(); } }
28.7
103
0.608263
c164aefcb08ed91db8908ae59da885d890a51733
899
package org.openjdk.jmh.reconfigure.statistics; import org.apache.commons.math3.distribution.EnumeratedDistribution; import org.apache.commons.math3.util.Pair; import org.openjdk.jmh.reconfigure.helper.HistogramItem; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Sampler { private List<HistogramItem> items; public Sampler(List<HistogramItem> items) { this.items = items; } public List<HistogramItem> getSample(int size) { HistogramItem[] output = new HistogramItem[size]; List<Pair<HistogramItem, Double>> distributionPairs = items.parallelStream().map(it -> new Pair<>(it.single(), (double) it.getCount())).collect(Collectors.toList()); EnumeratedDistribution ed = new EnumeratedDistribution<>(distributionPairs); ed.sample(size, output); return Arrays.asList(output); } }
34.576923
173
0.731924
bf5f9d4f24177a7f77bbcf3efcc62483a4b132bd
969
/* * Copyright (c) [2020] [yang1989] * [yt4j] is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package cn.yt4j.sys.service; import cn.yt4j.sys.entity.SysDict; import cn.yt4j.sys.entity.SysDictItem; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** * 字典(SysDict)表服务接口 * * @author gyv12345@163.com * @since 2020-08-10 08:43:32 */ public interface SysDictService extends IService<SysDict> { /** * 远程字典 * @param code * @return */ List<SysDictItem> listByCode(String code); }
27.685714
207
0.705882
58b2f3de6b3cffa32b31bcc8b02dd2b29a73261d
2,598
package cn.van.mall.web.mapper; import cn.van.mall.system.atom.SystemRoleAtom; import cn.van.mall.system.entity.SysRoleDO; import cn.van.mall.system.model.SysRoleDTO; import cn.van.mall.system.param.SysRoleParam; import cn.van.mall.web.BaseTest; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Copyright (C), 2015-2022, 风尘博客 * 公众号 : 风尘博客 * Author: Van * Date: 2022/1/9 9:05 下午 * Description: 系统角色增删改查测试 * Version: V1.0 */ @Slf4j public class SysRoleMapperTest extends BaseTest { @Resource private SystemRoleAtom roleAtom; @Test public void selectRoleList() { SysRoleParam param = new SysRoleParam(); // param.setRoleId(1L); param.setParams(new HashMap<String,Object>(){ { put("beginTime", null); put("endTime", null); } }); List<SysRoleDTO> list = roleAtom.selectRoleList(param); log.info("selectUserList {}", list); } @Test public void selectRoleByUserId() { List<SysRoleDTO> list = roleAtom.selectRoleByUserId(2L); log.info("selectRoleByUserId {}", list); list = roleAtom.selectRoleByUserName("超级管理员"); log.info("selectRoleByUserName {}", list); } @Test public void selectRoleIdByUserId() { List<Long> list = roleAtom.selectRoleIdByUserId(1L); log.info("selectRoleByUserId {}", list); SysRoleDTO roleDTO = roleAtom.selectById(1L); log.info("roleDTO {}", roleDTO); } @Test public void checkUnique() { int number = roleAtom.checkRoleNameUnique("超级管理员"); log.info("checkRoleNameUnique {}", number); int num = roleAtom.checkRoleKeyUnique("超级管理员"); log.info("checkRoleKeyUnique {}", num); } @Test public void insert() { SysRoleDO roleDO = new SysRoleDO(); // int number = roleAtom.insertRole(roleDO); roleDO.setRoleId(1L); roleDO.setUpdateBy("van"); roleDO.setUpdateTime(LocalDateTime.now()); int num = roleAtom.updateRole(roleDO); log.info("updateRole {}", num); int index = roleAtom.deleteRoleById(1L); log.info("deleteRoleById {}", index); int indexNum = roleAtom.deleteRoleByIds(Stream.of(1L, 2L).collect(Collectors.toList())); log.info("deleteRoleByIds {}", indexNum); } }
30.564706
96
0.646266
9203dca30d035fe16554a7c3f34e91e81950e1e6
1,679
/* * Copyright (C) 2018, Brian He * * 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.github.brianspace.common.observable; import android.support.annotation.Nullable; /** * Base class for a single observable object. */ public class ObjectObservableBase extends WeakObservable<IObserver> { /** * If {@code hasChanged()} returns {@code true}, calls the {@code onUpdate()} * method for every observer in the list of observers using null as the * argument. Afterwards, calls {@code clearChanged()}. * * <p>Equivalent to calling {@code notifyObservers(null)}. */ protected void notifyObservers() { notifyObservers(null); } /** * If {@code hasChanged()} returns {@code true}, calls the {@code onUpdate()} * method for every Observer in the list of observers using the specified * argument. Afterwards calls {@code clearChanged()}. * * @param data the argument passed to {@code onUpdate()}. */ @SuppressWarnings("unchecked") protected void notifyObservers(@Nullable final Object data) { foreachObserver(observer -> observer.onUpdate(this, data)); } }
34.265306
81
0.691483
d06ff2fb68593a3a43de6452474ff42cc2ba3dbc
97
package org.n0nb0at.hive.codec; public interface GeekEncoder { String encode(String raw); }
16.166667
31
0.752577
9644a38e2c9f8a17c1f5c3c3db25c40d7d2a334d
2,812
/* * Copyright 2014 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * 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.dkpro.statistics.agreement; import java.io.Serializable; /** * Basic interface representing the essential data model of any annotation study. The data model * provides access to the raters participating in the annotation study, the set of categories a * rater may use, and the annotation units. Each unit represents a single annotation (i.e., the * decision of a single rater to assign one of the categories to a predefined or rater-defined * unit). The interface acts as the common ground for any inter-rater agreement measure, whereas its * two fundamental extensions - the coding and the unitizing study interfaces - provide further * interface methods necessary for calculating individual measures. * * @see IAgreementMeasure * @see IAnnotationUnit * @author Christian M. Meyer */ public interface IAnnotationStudy extends Serializable { // -- Raters -- /** Returns the number of raters participating in this study. */ int getRaterCount(); int findRater(final String name); // -- Categories -- /** * Returns an iterator over all annotation categories within the study. Note that the categories * are not per se clear; they might need to be gathered by iterating through all associated * items, which yields performance problems in large-scale annotation studies. */ Iterable<Object> getCategories(); /** * Returns the number of annotation categories in the study. Note that the categories are not * per se clear; they might need to be gathered by iterating through all associated items, which * yields performance problems in large-scale annotation studies. */ int getCategoryCount(); /** * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e., * there are exactly two categories). */ boolean isDichotomous(); // -- Units -- // public Iterable<? extends IAnnotationUnit> getUnits(); /** * Returns the number of annotation units defined by the study. That is, the number of * annotations coded by the raters. */ int getUnitCount(); }
36.051282
100
0.720128
b2e1c25abcfc7f8a3d3b087d86191dfcb1b17f3a
1,594
/** * Copyright &copy; 2016-2022 liuhangjun All rights reserved. */ package com.channelsharing.hongqu.supplier.api.entity; import java.math.BigDecimal; import java.util.Date; import com.channelsharing.common.entity.BaseEntity; import lombok.Data; /** * 订单的商品信息Entity * @author liuhangjun * @version 2018-07-01 */ @Data public class OrderGoods extends BaseEntity { private static final long serialVersionUID = 1L; private String orderSn; // 订单编号 private Long goodsId; // 商品id private String goodsName; // 商品名称 private String goodsSn; // 商品序列号 private Long productId; // 产品Id private String goodsNumber; // 商品数量 private String goodsSpecificationNameValue; // 商品规格详情 private String goodsSpecificationIds; // 商品规格Ids private BigDecimal retailPrice; // 单价 private BigDecimal unitPrice; // 市场价 private BigDecimal profit; // 利润 private BigDecimal amountProfit; // 利润总价 private Long userId; // 购买用户 private String userNickname; // 用户昵称 private BigDecimal amountRetail; // 产品总价 private Long supplierId; // 供应商id private Integer payStatus; // 支付状态,0:未支付,1:已支付 private Long shopId; // 店铺id private String picUrl; // 图片链接 private Integer shippingCode; // 快递公司id private String shippingName; // 快递公司名 private BigDecimal shippingFee; // 运费 private Integer shippingStatus; // 运送状态,0:未发货,1:已发货,2:已签收 private String shippingNo; // 运单号 private Date deliveryTime; // 发货时间 private Date beginCreateTime; // 开始 创建时间 private Date endCreateTime; // 结束 创建时间 private String shopName; // 店铺名称 public OrderGoods() { super(); } }
26.131148
61
0.728984
54b34de8ee33024e0e99433aa2850c83525c025a
3,320
package com.chinamobile.bcbsp.examples.copra; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.HashSet; import com.chinamobile.bcbsp.api.AggregateValue; import com.chinamobile.bcbsp.api.AggregationContextInterface; import com.chinamobile.bcbsp.comm.BSPMessage; public class C_AggregateValue extends AggregateValue<String,BSPMessage> { private String community_VertexNum; @Override public void initValue(Iterator<BSPMessage> messages, AggregationContextInterface context) { int maxOverLap = context.getJobConf().getConf().getInt("MaxOverlap", 0); BSPMessage message; String messageValue; String[] messV; long neighbors = 0; Map<String, Double> labelCoefficient = new HashMap<String, Double>(); Map<String, Double> tmp_Labels = new HashMap<String, Double>(); String[] lcs; String[] lc; String label; double coefficient; while (messages.hasNext()) { ++neighbors; message = messages.next(); messageValue = new String(message.getData()); messV = messageValue.split("@"); lcs = messV[1].split("\\|"); for (int i = 0; i != lcs.length; ++i) { lc = lcs[i].split("-"); label = lc[0]; coefficient = Double.parseDouble(lc[1]); if (labelCoefficient.containsKey(label)) { labelCoefficient.put(label, labelCoefficient.get(label) + coefficient); } else { labelCoefficient.put(label, coefficient); } } } Set<String> randomLabels = new HashSet<String>(); double maxCoefficient = 0; boolean findLabel = false; double tmp_coeffi; Iterator<String> it = labelCoefficient.keySet().iterator(); while (it.hasNext()) { label = it.next(); tmp_coeffi = labelCoefficient.get(label).doubleValue() / neighbors; if (tmp_coeffi > maxCoefficient) { maxCoefficient = tmp_coeffi; randomLabels.clear(); randomLabels.add(label); } else if (tmp_coeffi == maxCoefficient) { randomLabels.add(label); } if (tmp_coeffi >= (1.0 / maxOverLap)) { tmp_Labels.put(label, tmp_coeffi); findLabel = true; } } if (!findLabel) { community_VertexNum = getMinLabel(randomLabels) + "-1|"; } else { it = tmp_Labels.keySet().iterator(); StringBuffer sb = new StringBuffer(); while(it.hasNext()) { sb.append(it.next() + "-1|"); } community_VertexNum = sb.toString(); } } public String getMinLabel(Set<String> labels) { long minLabel = Integer.MAX_VALUE; String label; Iterator<String> it = labels.iterator(); while(it.hasNext()) { label = it.next(); if(minLabel > Long.parseLong(label)) { minLabel = Long.parseLong(label); } } return String.valueOf(minLabel); } @Override public void initValue(String s) { community_VertexNum = s; } @Override public void setValue(String s) { community_VertexNum = s; } @Override public String getValue() { return community_VertexNum; } @Override public String toString() { return community_VertexNum; } @Override public void readFields(DataInput in) throws IOException { community_VertexNum = in.readUTF(); } @Override public void write(DataOutput out) throws IOException { out.writeUTF(community_VertexNum); } }
22.585034
92
0.688855
0662cc3ca18cc856d91730dc8a5c7b42768952c3
1,861
/* * generated by Xtext */ package com.robotoworks.mechanoid.db; import org.eclipse.xtext.generator.IOutputConfigurationProvider; import org.eclipse.xtext.naming.IQualifiedNameProvider; import org.eclipse.xtext.parsetree.reconstr.ICommentAssociater; import org.eclipse.xtext.parsetree.reconstr.ITransientValueService; import org.eclipse.xtext.scoping.IScopeProvider; import org.eclipse.xtext.serializer.sequencer.ISemanticSequencer; import com.google.inject.Binder; import com.robotoworks.mechanoid.db.naming.SqliteQualifiedNameProvider; import com.robotoworks.mechanoid.db.scoping.XSqliteModelScopeProvider; import com.robotoworks.mechanoid.db.serializer.SqliteModelSemanticSequencer; import com.robotoworks.mechanoid.db.serializer.SqliteSerializer; import com.robotoworks.mechanoid.generator.MechanoidOutputConfigurationProvider; /** * Use this class to register components to be used at runtime / without the * Equinox extension registry. */ public class SqliteModelRuntimeModule extends com.robotoworks.mechanoid.db.AbstractSqliteModelRuntimeModule { @Override public void configure(Binder binder) { super.configure(binder); binder.bind(IOutputConfigurationProvider.class).to(MechanoidOutputConfigurationProvider.class); } @Override public Class<? extends IScopeProvider> bindIScopeProvider() { return XSqliteModelScopeProvider.class; } @Override public Class<? extends IQualifiedNameProvider> bindIQualifiedNameProvider() { return SqliteQualifiedNameProvider.class; } @Override public Class<? extends org.eclipse.xtext.serializer.ISerializer> bindISerializer() { return SqliteSerializer.class; } @Override public Class<? extends ISemanticSequencer> bindISemanticSequencer() { return ExtendedSqliteModelSemanticSequencer.class; } }
35.788462
109
0.792585
6efbe7d6cca2769eedc366ea5641e243e0ec478e
15,863
/** * Copyright 2015 IBM Corp. 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.ibm.watson.developer_cloud.alchemy.v1; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.ibm.watson.developer_cloud.alchemy.v1.model.AlchemyGenericModel; import com.ibm.watson.developer_cloud.alchemy.v1.model.CombinedResults; import com.ibm.watson.developer_cloud.alchemy.v1.model.Concepts; import com.ibm.watson.developer_cloud.alchemy.v1.model.Dates; import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentAuthors; import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentEmotion; import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentPublicationDate; import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentSentiment; import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentText; import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentTitle; import com.ibm.watson.developer_cloud.alchemy.v1.model.Entities; import com.ibm.watson.developer_cloud.alchemy.v1.model.Feeds; import com.ibm.watson.developer_cloud.alchemy.v1.model.Keywords; import com.ibm.watson.developer_cloud.alchemy.v1.model.Language; import com.ibm.watson.developer_cloud.alchemy.v1.model.LanguageSelection; import com.ibm.watson.developer_cloud.alchemy.v1.model.Microformats; import com.ibm.watson.developer_cloud.alchemy.v1.model.SAORelations; import com.ibm.watson.developer_cloud.alchemy.v1.model.Taxonomies; import com.ibm.watson.developer_cloud.alchemy.v1.model.TypedRelations; import com.ibm.watson.developer_cloud.alchemy.v1.util.AlchemyEndPoints; import com.ibm.watson.developer_cloud.alchemy.v1.util.AlchemyEndPoints.AlchemyAPI; import com.ibm.watson.developer_cloud.http.RequestBuilder; import com.ibm.watson.developer_cloud.http.ServiceCall; import com.ibm.watson.developer_cloud.service.AlchemyService; import com.ibm.watson.developer_cloud.util.ResponseConverterUtils; /** * The Alchemy Language service uses offers 12 text analysis services, each of which uses * sophisticated natural language processing techniques to analyze your content and add high-level * semantic information. * * @version v1 * @see <a href="http://www.alchemyapi.com/products/alchemylanguage"> Alchemy Language</a> */ public class AlchemyLanguage extends AlchemyService { /** The Constant BASE_URL. */ public static final String BASE_URL = "baseUrl"; /** The Constant COREFERENCE. */ public static final String COREFERENCE = "coreference"; /** The Constant CQUERY. */ public static final String CQUERY = "cquery"; /** The Constant DISAMBIGUATE. */ public static final String DISAMBIGUATE = "disambiguate"; /** The Constant ENTITIES. */ public static final String ENTITIES = "entities"; /** The Constant EXTRACT. */ public static final String EXTRACT = "extract"; /** The Constant EXTRACT_LINK. */ public static final String EXTRACT_LINK = "extractLinks"; /** The Constant FORCED_GLOSSARY. */ public static final String FORCED_GLOSSARY = "forced_glossary"; /** The Constant HTML. */ public static final String HTML = "html"; /** The Constant KEYWORD_EXTRACT_MODE. */ public static final String KEYWORD_EXTRACT_MODE = "keywordExtractMode"; /** The Constant KEYWORDS. */ public static final String KEYWORDS = "keywords"; /** The Constant KNOWLEDGE_GRAPH. */ public static final String KNOWLEDGE_GRAPH = "knowledgeGraph"; /** The Constant LINKED_DATA. */ public static final String LINKED_DATA = "linkedData"; /** The Constant MAX_RETRIEVE. */ public static final String MAX_RETRIEVE = "maxRetrieve"; /** The Constant QUOTATIONS. */ public static final String QUOTATIONS = "quotations"; /** The Constant RAW. */ public static final String RAW = "raw"; /** The Constant REQUIRED_ENTITIES. */ public static final String REQUIRED_ENTITIES = "requireEntities"; /** The Constant SENTIMENT. */ public static final String SENTIMENT = "sentiment"; /** The Constant SENTIMENT_EXCLUDE_ENTITIES. */ public static final String SENTIMENT_EXCLUDE_ENTITIES = "sentimentExcludeEntities"; /** The Constant SHOW_SOURCE_TEXT. */ public static final String SHOW_SOURCE_TEXT = "showSourceText"; /** The Constant SOURCE_TEXT. */ public static final String SOURCE_TEXT = "sourceText"; /** The Constant STRUCTURED_ENTITIES. */ public static final String STRUCTURED_ENTITIES = "structuredEntities"; /** The Constant TARGET. */ public static final String TARGET = "target"; /** The Constant TEXT. */ public static final String TEXT = "text"; /** The Constant URL. */ public static final String URL = "url"; /** The Constant USE_METADATA. */ public static final String USE_METADATA = "useMetadata"; /** The Constant XPATH. */ public static final String XPATH = "xpath"; /** The Constant TARGETS. */ public static final String TARGETS = "targets"; /** The Constant ANCHOR_DATE. */ public static final String ANCHOR_DATE = "anchorDate"; /** The Constant MODEL_ID. */ public static final String MODEL_ID = "model_id"; private LanguageSelection language = LanguageSelection.DETECT; private static final SimpleDateFormat anchorDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static final String LANGUAGE = "language"; /** * Instantiates a new alchemy data news service. */ public AlchemyLanguage() { super(); } /** * Instantiates a new alchemy language service by apiKey. * @param apiKey the api key */ public AlchemyLanguage(String apiKey) { super(apiKey); } /** * Execute the request and return the POJO that represent the response. * * @param <T> The POJO that represents the response object * @param params the request parameters * @param operation the alchemy operation * @param returnType the POJO class to be parsed from the response * @param acceptedFormats the accepted input formats e.g. "html", "text"... * @return the POJO object that represent the response */ private <T extends AlchemyGenericModel> ServiceCall<T> createServiceCall(final Map<String, Object> params, AlchemyAPI operation, Class<T> returnType, String... acceptedFormats) { // clone params, to prevent errors if the user continues to use the provided Map, or it is immutable final Map<String, Object> paramsCopy = new HashMap<String, Object>(params); // Get the input format and check for missing parameters final String format = getInputFormat(paramsCopy, acceptedFormats); // Get the path that represent this operation based on the operation and format final String path = AlchemyEndPoints.getPath(operation, format); // Return json paramsCopy.put(OUTPUT_MODE, "json"); if (!paramsCopy.containsKey(LANGUAGE) && language != LanguageSelection.DETECT) { paramsCopy.put(LANGUAGE, language.toString().toLowerCase()); } // Prevent jsonp to be returned paramsCopy.remove(JSONP); final RequestBuilder requestBuilder = RequestBuilder.post(path); for (final String param : paramsCopy.keySet()) { requestBuilder.form(param, paramsCopy.get(param)); } if (operation == AlchemyAPI.TYPED && params.containsKey(MODEL_ID)) { requestBuilder.query(MODEL_ID, params.get(MODEL_ID)); } return createServiceCall(requestBuilder.build(),ResponseConverterUtils.getObject(returnType)); } /** * Allows users to set language of input text. * * @param language The language to use */ public void setLanguage(LanguageSelection language) { this.language = language; } /** * Extracts the authors from a URL or HTML. * * @param params The parameters to be used in the service call, html or url should be specified. * @return {@link DocumentAuthors} */ public ServiceCall<DocumentAuthors> getAuthors(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.AUTHORS, DocumentAuthors.class, HTML, URL); } /** * Extracts concepts tags for text, HTML, or a URLL. * * @param params The parameters to be used in the service call, text, html or url should be * specified. * @return {@link Concepts} */ public ServiceCall<Concepts> getConcepts(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.CONCEPTS, Concepts.class, TEXT, HTML, URL); } /** * Extracts publication date information when it is specified in web pages. * * @param params The parameters to be used in the service call, html or url should be specified. * @return {@link DocumentPublicationDate} */ public ServiceCall<DocumentPublicationDate> getPublicationDate(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.PUBLICATION_DATE, DocumentPublicationDate.class, HTML, URL); } /** * Categorized through the taxonomy call for text, HTML, or a URL. * * @param params The parameters to be used in the service call, text, html or url should be * specified. * @return {@link Taxonomies} */ public ServiceCall<Taxonomies> getTaxonomy(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.TAXONOMY, Taxonomies.class, TEXT, HTML, URL); } /** * Automatically perform analysis using multiple features on any web page or posted (uploaded) * HTML/text file. * * @param params The parameters to be used in the service call, text, html or url should be * specified. * @return {@link Microformats} */ public ServiceCall<CombinedResults> getCombinedResults(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.COMBINED, CombinedResults.class, TEXT, HTML, URL); } /** * Extracts a grouped, ranked list of named entities (people, companies, organizations, etc.) from * text, a URL or HTML. * * @param params The parameters to be used in the service call, text, html or url should be * specified. * @return {@link Entities} */ public ServiceCall<Entities> getEntities(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.ENTITIES, Entities.class, TEXT, HTML, URL); } /** * Detects the RSS/ATOM feeds for a URL or HTML. * * @param params The parameters to be used in the service call, html or url should be specified. * @return {@link Feeds} */ public ServiceCall<Feeds> getFeeds(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.FEEDS, Feeds.class, HTML, URL); } /** * Extracts the keywords from text, a URL or HTML. * * @param params The parameters to be used in the service call, text, html or url should be * specified. * @return {@link Keywords} */ public ServiceCall<Keywords> getKeywords(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.KEYWORDS, Keywords.class, TEXT, HTML, URL); } /** * Detects the language for text, a URL or HTML. * * @param params The parameters to be used in the service call, text, html or url should be * specified. * @return {@link Language} */ public ServiceCall<Language> getLanguage(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.LANGUAGE, Language.class, TEXT, HTML, URL); } /** * Parses the {@link Microformats} for a URL or HTML. * * @param params The parameters to be used in the service call, html or url should be specified * @return {@link Microformats} */ public ServiceCall<Microformats> getMicroformats(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.MICROFORMATS, Microformats.class, HTML, URL); } /** * Extracts Subject-Action-Object(SAO) relations from text, a URL or HTML. * * @param params The parameters to be used in the service call, text, html or url should be * specified. * @return {@link SAORelations} */ public ServiceCall<SAORelations> getRelations(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.RELATIONS, SAORelations.class, TEXT, HTML, URL); } /** * Calculates the sentiment for text, a URL or HTML. * * @param params The parameters to be used in the service call, text, html or url should be * specified. * @return {@link DocumentSentiment} */ public ServiceCall<DocumentSentiment> getSentiment(Map<String, Object> params) { AlchemyAPI operation = AlchemyAPI.SENTIMENT; if (params.get(TARGET) != null || params.get(TARGETS) != null) operation = AlchemyAPI.SENTIMENT_TARGETED; return createServiceCall(params, operation, DocumentSentiment.class, TEXT, HTML, URL); } /** * Extracts the cleaned text (removes ads, navigation, etc.) for a URL or HTML. if raw is true, * extracts the cleaned text (removes ads, navigation, etc.). * * @param params The parameters to be used in the service call, html or url should be specified. * @return {@link DocumentText} */ public ServiceCall<DocumentText> getText(Map<String, Object> params) { AlchemyAPI operation = AlchemyAPI.TEXT; if (params.get(RAW) != null) operation = AlchemyAPI.TEXT_RAW; return createServiceCall(params, operation, DocumentText.class, HTML, URL); } /** * Extracts the title for a URL or HTML. * * @param params The parameters to be used in the service call, html or url should be specified. * @return {@link DocumentTitle} */ public ServiceCall<DocumentTitle> getTitle(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.TITLE, DocumentTitle.class, HTML, URL); } /** * Detects emotions in a text, URL or HTML. * * @param params The parameters to be used in the service call, text, html or url should be * specified * @return {@link DocumentEmotion} */ public ServiceCall<DocumentEmotion> getEmotion(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.EMOTION, DocumentEmotion.class, TEXT, HTML, URL); } /** * Finds entities and their relationships from a text, URL or HTML. * * @param params The parameters to be used in the service call, text, html or url should be * specified * @return {@link DocumentEmotion} */ public ServiceCall<TypedRelations> getTypedRelations(Map<String, Object> params) { return createServiceCall(params, AlchemyAPI.TYPED, TypedRelations.class, TEXT, HTML, URL); } /** * Extracts dates for text, a URL or HTML. * * @param params The parameters to be used in the service call, text, html or url should be * specified. * @return {@link Dates} */ public ServiceCall<Dates> getDates(final Map<String, Object> params) { // clone params, to prevent errors if the user continues to use the provided Map, or it is immutable Map<String, Object> paramsCopy = new HashMap<String, Object>(params); if (params.containsKey(ANCHOR_DATE) && params.get(ANCHOR_DATE) instanceof Date) { String anchorDate = anchorDateFormat.format(params.get(ANCHOR_DATE)); paramsCopy.put(ANCHOR_DATE, anchorDate); } return createServiceCall(paramsCopy, AlchemyAPI.DATES, Dates.class, TEXT, HTML, URL); } }
37.149883
108
0.718086
5f1208c40999e28b1f4cce5197ede62969de6539
695
package ca.uhn.fhir.jpa.starter.custom; import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; @RestController public class UserController { @GetMapping("/user") public Principal user(Principal user) { return user; } @GetMapping(value = {"/auth-info"}, produces = MediaType.APPLICATION_JSON_VALUE) public Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } }
28.958333
81
0.811511
77e39779f34b6c71057ad4b5df523edf375a62f7
1,191
package common.webapp.controller; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.BDDMockito.*; import javax.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; public class ReloadControllerTest extends BaseControllerTestCase { @Autowired private ReloadController c; @Test public void testHandleRequest() throws Exception { MockHttpServletRequest request = newGet("/admin/reload"); String rtn = c.handleRequest(request); assertEquals("redirect:/top", rtn); } @Test public void testHandleRequestWithReferer() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getSession()).thenReturn(newGet("/admin/reload").getSession()); when(request.getHeader("Referer")).thenReturn("http://foo.bar/common/test"); when(request.getContextPath()).thenReturn("/common"); String rtn = c.handleRequest(request); assertEquals("redirect:/test", rtn); } }
33.083333
85
0.70529
697c0bfde06d3dacfe2132015b03875fc4ca2729
4,099
package io.quarkus.webjars.locator.deployment; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import io.quarkus.bootstrap.classloading.ClassPathElement; import io.quarkus.bootstrap.classloading.QuarkusClassLoader; import io.quarkus.bootstrap.util.ZipUtils; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.ExecutionTime; import io.quarkus.deployment.annotations.Record; import io.quarkus.deployment.builditem.FeatureBuildItem; import io.quarkus.vertx.http.deployment.RouteBuildItem; import io.quarkus.vertx.http.runtime.HttpBuildTimeConfig; import io.quarkus.webjars.locator.runtime.WebJarsLocatorRecorder; public class WebJarsLocatorProcessor { @BuildStep @Record(ExecutionTime.RUNTIME_INIT) public void findWebjarsAndCreateHandler( HttpBuildTimeConfig httpConfig, BuildProducer<FeatureBuildItem> feature, BuildProducer<RouteBuildItem> routes, WebJarsLocatorRecorder recorder) throws Exception { // The context path + the resources path String rootPath = httpConfig.rootPath; String webjarRootPath = (rootPath.endsWith("/")) ? rootPath + "webjars/" : rootPath + "/webjars/"; feature.produce(new FeatureBuildItem(FeatureBuildItem.WEBJARS_LOCATOR)); final String webjarsFileSystemPath = "META-INF/resources/webjars/"; QuarkusClassLoader cl = (QuarkusClassLoader) Thread.currentThread().getContextClassLoader(); Map<String, String> versionMap = new HashMap<>(); List<ClassPathElement> resources = cl.getElementsWithResource(webjarsFileSystemPath); for (ClassPathElement webJarsElement : resources) { Path root = webJarsElement.getRoot(); if (root == null) { continue; } //we only care about jars if (!Files.isDirectory(root)) { try (FileSystem jar = ZipUtils.newFileSystem(root)) { Path web = jar.getPath(webjarsFileSystemPath); try (Stream<Path> implementations = Files.list(web)) { implementations.forEach(new Consumer<Path>() { @Override public void accept(Path implPath) { try (Stream<Path> version = Files.list(implPath)) { List<Path> versionList = version.collect(Collectors.toList()); if (versionList.isEmpty()) { return; } if (versionList.size() > 1) { throw new RuntimeException("Found multiple versions of webjar " + implPath.getFileName() + " versions " + versionList); } versionMap.put(stripSeperator(implPath.getFileName().toString()), stripSeperator(versionList.get(0).getFileName().toString())); } catch (IOException e) { throw new RuntimeException(e); } } }); } } } } routes.produce( new RouteBuildItem(webjarRootPath + "*", recorder.getHandler(webjarRootPath, versionMap), false)); } private String stripSeperator(String val) { //some JDK versions will include the trailing path seperator in the name return val.replaceAll("/", "").replaceAll("\\\\", ""); } }
45.544444
128
0.585265
1c66ae0e256eb09b7b3d391f08eacb96f10c739d
1,194
package com.tct.jms.consumer; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import org.springframework.stereotype.Service; import com.tct.codec.MessageCodec; import com.tct.codec.MessageCodecSelector; import com.tct.service.ServiceSelector; import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class ConsumerMessageListener implements MessageListener { @Override public void onMessage(Message message) { if(message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; log.info("RECE MESSAGE"); if(null !=textMessage) { //编解码器选择器 MessageCodecSelector messageCodecSelector = new MessageCodecSelector(); MessageCodec messageCodec = null; try { log.info(textMessage.getText()); messageCodec = messageCodecSelector.getMessageDecode(textMessage.getText()); } catch (Exception e2) { log.debug(e2+"消息解码器不存在"); } //业务处理选择器 ServiceSelector serviceSelector = new ServiceSelector(); boolean flag = serviceSelector.handlerService(messageCodec, textMessage); } }else { log.info("收到非TextMessage消息类型"); } } }
25.956522
81
0.740369
60bfae597b007ec3202c11700bf19723104df174
314
package io.github.ludovicianul.prettylogger.config.level; import io.github.ludovicianul.prettylogger.config.MarkerType; import org.slf4j.event.Level; public class Fav extends PrettyMarker { private Fav() { super(MarkerType.FAV, Level.INFO); } static Fav defaultConfig() { return new Fav(); } }
19.625
61
0.738854
2ea8f381a55eed99246735eb88af2e3129a478d0
463
package miniprojekti.data_access; import java.util.List; import miniprojekti.domain.ReadingTip; import miniprojekti.domain.Tip; /** * * @author Tatu */ public interface Dao { List<ReadingTip> findAll(); void save(String author, String title, String url); int deleteTip(Tip tip); int deleteByID(int id); int deleteByTitle(String title); int updateTip(Tip tip); String[] findUser(String username); }
16.535714
55
0.663067
9294282ba9312a289cfd6214fccafe92cd1de769
139
package io.neow3j.compiler.sourcelookup; public class TestSmartContract { // The content of this file does not matter to the test. }
19.857143
60
0.755396
ac05c7221f83048beeb95ac1534494a2b114ade8
96
package io.github.laskowski.os; public enum OperatingSystem { WINDOWS, MAC, UNIX }
12
31
0.677083
2fa4450f0386459e45fe7fc7f3ab92aae678c1e4
2,551
package com.bazl.dna.lims.service.impl; import com.bazl.dna.lims.dao.FugitivesMiddleTableMapper; import com.bazl.dna.lims.model.po.FugitivesMiddleTable; import com.bazl.dna.lims.service.FugitivesMiddleTableService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author wanghaiyang * @date 2020/7/9 18:29 */ public class FugitivesMiddleTableServiceImpl extends BaseService implements FugitivesMiddleTableService { @Autowired FugitivesMiddleTableMapper fugitivesMiddleTableMapper; @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public int deleteByPrimaryKey(String id) { try { return fugitivesMiddleTableMapper.deleteByPrimaryKey(id); }catch(Exception e){ e.getStackTrace(); logger.error(id + "删除失败!"); return 0; } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public int insert(FugitivesMiddleTable record) { try { return fugitivesMiddleTableMapper.insert(record); }catch (Exception e) { e.getStackTrace(); logger.error("插入失败!"); return 0; } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public FugitivesMiddleTable selectByPrimaryKey(String id) { try { return fugitivesMiddleTableMapper.selectByPrimaryKey(id); }catch (Exception e) { e.getStackTrace(); logger.error(id + "查询失败!"); return null; } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public List<FugitivesMiddleTable> selectAll() { try { return fugitivesMiddleTableMapper.selectAll(); }catch (Exception e) { e.getStackTrace(); logger.error("查询失败!"); return null; } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public int updateByPrimaryKey(FugitivesMiddleTable record) { try { return fugitivesMiddleTableMapper.updateByPrimaryKey(record); }catch (Exception e) { e.getStackTrace(); logger.error("更新失败!"); return 0; } } }
31.109756
105
0.659741
c7dabeecca525f427638b0b834d5a7776bf828d7
7,321
/* * Copyright 2016 LinkedIn Corp. * * 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.linkedin.drelephant.mapreduce.heuristics; import com.linkedin.drelephant.configurations.heuristic.HeuristicConfigurationData; import com.linkedin.drelephant.util.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.linkedin.drelephant.analysis.Heuristic; import com.linkedin.drelephant.analysis.HeuristicResult; import com.linkedin.drelephant.analysis.Severity; import com.linkedin.drelephant.mapreduce.data.MapReduceCounterData; import com.linkedin.drelephant.mapreduce.data.MapReduceApplicationData; import com.linkedin.drelephant.mapreduce.data.MapReduceTaskData; import com.linkedin.drelephant.math.Statistics; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; /** * This heuristic deals with the efficiency of container size */ public abstract class GenericMemoryHeuristic implements Heuristic<MapReduceApplicationData> { private static final Logger logger = Logger.getLogger(GenericMemoryHeuristic.class); private static final long CONTAINER_MEMORY_DEFAULT_BYTES = 2048L * FileUtils.ONE_MB; // Severity Parameters private static final String MEM_RATIO_SEVERITY = "memory_ratio_severity"; private static final String CONTAINER_MEM_SEVERITY = "container_memory_severity"; // Default value of parameters private double[] memRatioLimits = {0.6d, 0.5d, 0.4d, 0.3d}; // Avg Physical Mem of Tasks / Container Mem private double[] memoryLimits = {1.1d, 1.5d, 2.0d, 2.5d}; // Container Memory Severity Limits private String _containerMemConf; private HeuristicConfigurationData _heuristicConfData; private void loadParameters() { Map<String, String> paramMap = _heuristicConfData.getParamMap(); String heuristicName = _heuristicConfData.getHeuristicName(); double[] confMemRatioLimits = Utils.getParam(paramMap.get(MEM_RATIO_SEVERITY), memRatioLimits.length); if (confMemRatioLimits != null) { memRatioLimits = confMemRatioLimits; } logger.info(heuristicName + " will use " + MEM_RATIO_SEVERITY + " with the following threshold settings: " + Arrays.toString(memRatioLimits)); double[] confMemoryLimits = Utils.getParam(paramMap.get(CONTAINER_MEM_SEVERITY), memoryLimits.length); if (confMemoryLimits != null) { memoryLimits = confMemoryLimits; } logger.info(heuristicName + " will use " + CONTAINER_MEM_SEVERITY + " with the following threshold settings: " + Arrays.toString(memoryLimits)); for (int i = 0; i < memoryLimits.length; i++) { memoryLimits[i] = memoryLimits[i] * CONTAINER_MEMORY_DEFAULT_BYTES; } } protected GenericMemoryHeuristic(String containerMemConf, HeuristicConfigurationData heuristicConfData) { this._containerMemConf = containerMemConf; this._heuristicConfData = heuristicConfData; loadParameters(); } protected abstract MapReduceTaskData[] getTasks(MapReduceApplicationData data); @Override public HeuristicConfigurationData getHeuristicConfData() { return _heuristicConfData; } @Override public HeuristicResult apply(MapReduceApplicationData data) { if(!data.getSucceeded()) { return null; } String containerSizeStr = data.getConf().getProperty(_containerMemConf); if (containerSizeStr == null) { return null; } long containerMem; try { containerMem = Long.parseLong(containerSizeStr); } catch (NumberFormatException e) { // Some job has a string var like "${VAR}" for this config. if(containerSizeStr.startsWith("$")) { String realContainerConf = containerSizeStr.substring(containerSizeStr.indexOf("{")+1, containerSizeStr.indexOf("}")); containerMem = Long.parseLong(data.getConf().getProperty(realContainerConf)); } else { throw e; } } containerMem *= FileUtils.ONE_MB; MapReduceTaskData[] tasks = getTasks(data); List<Long> taskPMems = new ArrayList<Long>(); List<Long> taskVMems = new ArrayList<Long>(); List<Long> runtimesMs = new ArrayList<Long>(); long taskPMin = Long.MAX_VALUE; long taskPMax = 0; for (MapReduceTaskData task : tasks) { if (task.isSampled()) { runtimesMs.add(task.getTotalRunTimeMs()); long taskPMem = task.getCounters().get(MapReduceCounterData.CounterName.PHYSICAL_MEMORY_BYTES); long taskVMem = task.getCounters().get(MapReduceCounterData.CounterName.VIRTUAL_MEMORY_BYTES); taskPMems.add(taskPMem); taskPMin = Math.min(taskPMin, taskPMem); taskPMax = Math.max(taskPMax, taskPMem); taskVMems.add(taskVMem); } } if(taskPMin == Long.MAX_VALUE) { taskPMin = 0; } long taskPMemAvg = Statistics.average(taskPMems); long taskVMemAvg = Statistics.average(taskVMems); long averageTimeMs = Statistics.average(runtimesMs); Severity severity; if (tasks.length == 0) { severity = Severity.NONE; } else { severity = getTaskMemoryUtilSeverity(taskPMemAvg, containerMem); } HeuristicResult result = new HeuristicResult(_heuristicConfData.getClassName(), _heuristicConfData.getHeuristicName(), severity, Utils.getHeuristicScore(severity, tasks.length)); result.addResultDetail("Number of tasks", Integer.toString(tasks.length)); result.addResultDetail("Avg task runtime", Statistics.readableTimespan(averageTimeMs)); result.addResultDetail("Avg Physical Memory (MB)", Long.toString(taskPMemAvg / FileUtils.ONE_MB)); result.addResultDetail("Max Physical Memory (MB)", Long.toString(taskPMax / FileUtils.ONE_MB)); result.addResultDetail("Min Physical Memory (MB)", Long.toString(taskPMin / FileUtils.ONE_MB)); result.addResultDetail("Avg Virtual Memory (MB)", Long.toString(taskVMemAvg / FileUtils.ONE_MB)); result.addResultDetail("Requested Container Memory", FileUtils.byteCountToDisplaySize(containerMem)); return result; } private Severity getTaskMemoryUtilSeverity(long taskMemAvg, long taskMemMax) { double ratio = ((double)taskMemAvg) / taskMemMax; Severity sevRatio = getMemoryRatioSeverity(ratio); // Severity is reduced if the requested container memory is close to default Severity sevMax = getContainerMemorySeverity(taskMemMax); return Severity.min(sevRatio, sevMax); } private Severity getContainerMemorySeverity(long taskMemMax) { return Severity.getSeverityAscending( taskMemMax, memoryLimits[0], memoryLimits[1], memoryLimits[2], memoryLimits[3]); } private Severity getMemoryRatioSeverity(double ratio) { return Severity.getSeverityDescending( ratio, memRatioLimits[0], memRatioLimits[1], memRatioLimits[2], memRatioLimits[3]); } }
39.572973
114
0.740199
e50f17796781be63d6d70c9ab5ff39098c6fa975
12,084
package uk.gov.hmcts.reform.civil.bpmn; import org.camunda.bpm.engine.externaltask.ExternalTask; import org.camunda.bpm.engine.variable.VariableMap; import org.camunda.bpm.engine.variable.Variables; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; class NotifyClaimTest extends BpmnBaseTest { public static final String MESSAGE_NAME = "NOTIFY_DEFENDANT_OF_CLAIM"; public static final String PROCESS_ID = "NOTIFY_CLAIM"; //CCD EVENTS public static final String NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE = "NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIM_ISSUE"; private static final String NOTIFY_RESPONDENT_SOLICITOR_1_FOR_CLAIM_ISSUE_CC = "NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIM_ISSUE_CC"; private static final String NOTIFY_RESPONDENT_SOLICITOR_2_FOR_CLAIM_ISSUE = "NOTIFY_RESPONDENT_SOLICITOR2_FOR_CLAIM_ISSUE"; private static final String NOTIFY_RPA_ON_CONTINUOUS_FEED = "NOTIFY_RPA_ON_CONTINUOUS_FEED"; private static final String PROCEEDS_IN_HERITAGE_SYSTEM = "PROCEEDS_IN_HERITAGE_SYSTEM"; private static final String NOTIFY_APPLICANT_SOLICITOR_1_HAND_OFFLINE = "NOTIFY_APPLICANT_SOLICITOR1_FOR_CASE_PROCEEDS_IN_CASEMAN"; private static final String NOTIFY_RPA_ON_CASE_HANDED_OFFLINE = "NOTIFY_RPA_ON_CASE_HANDED_OFFLINE"; //ACTIVITY IDs private static final String NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE_ACTIVITY_ID = "NotifyDefendantSolicitor1"; private static final String NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE_CC_ACTIVITY_ID = "NotifyApplicantSolicitorCC"; private static final String NOTIFY_RESPONDENT_SOLICITOR_2_CLAIM_ISSUE_ACTIVITY_ID = "NotifyDefendantSolicitor2"; private static final String NOTIFY_RPA_ON_CONTINUOUS_FEED_ACTIVITY_ID = "NotifyRoboticsOnContinuousFeed"; private static final String PROCEEDS_IN_HERITAGE_SYSTEM_ACTIVITY_ID = "ProceedOffline"; private static final String NOTIFY_APPLICANT_SOLICITOR_1_HAND_OFFLINE_ACTIVITY_ID = "NotifyClaimProceedsOfflineNotifyApplicantSolicitor1"; private static final String NOTIFY_RPA_ON_CASE_HANDED_OFFLINE_ACTIVITY_ID = "NotifyRoboticsOnCaseHandedOffline"; enum FlowState { CLAIM_NOTIFIED, TAKEN_OFFLINE_AFTER_CLAIM_NOTIFIED; public String fullName() { return "MAIN" + "." + name(); } } public NotifyClaimTest() { super("notify_claim.bpmn", "NOTIFY_CLAIM"); } @ParameterizedTest @ValueSource(strings = {"true", "false"}) void shouldSuccessfullyCompleteNotifyClaim_andRpaContinuousFeed_whenCalled(Boolean rpaContinuousFeed) { //assert process has started assertFalse(processInstance.isEnded()); //assert message start event assertThat(getProcessDefinitionByMessage(MESSAGE_NAME).getKey()).isEqualTo(PROCESS_ID); VariableMap variables = Variables.createVariables(); variables.putValue(FLOW_STATE, FlowState.CLAIM_NOTIFIED.fullName()); variables.putValue(FLOW_FLAGS, Map.of(RPA_CONTINUOUS_FEED, rpaContinuousFeed)); //complete the start business process ExternalTask startBusiness = assertNextExternalTask(START_BUSINESS_TOPIC); assertCompleteExternalTask( startBusiness, START_BUSINESS_TOPIC, START_BUSINESS_EVENT, START_BUSINESS_ACTIVITY, variables ); //complete the notification ExternalTask notificationTask = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(notificationTask, PROCESS_CASE_EVENT, NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE, NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE_ACTIVITY_ID, variables ); //complete the CC notification notificationTask = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(notificationTask, PROCESS_CASE_EVENT, NOTIFY_RESPONDENT_SOLICITOR_1_FOR_CLAIM_ISSUE_CC, NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE_CC_ACTIVITY_ID, variables ); if (rpaContinuousFeed) { //complete the Robotics notification ExternalTask forRobotics = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask( forRobotics, PROCESS_CASE_EVENT, NOTIFY_RPA_ON_CONTINUOUS_FEED, NOTIFY_RPA_ON_CONTINUOUS_FEED_ACTIVITY_ID, variables ); } //end business process ExternalTask endBusinessProcess = assertNextExternalTask(END_BUSINESS_PROCESS); completeBusinessProcess(endBusinessProcess); assertNoExternalTasksLeft(); } @ParameterizedTest @ValueSource(strings = {"true", "false"}) void shouldSuccessfullyCompleteNotifyClaim_AndNotifyAppropriateSolicitors_whenCalled( Boolean twoRespondentRepresentatives) { //assert process has started assertFalse(processInstance.isEnded()); //assert message start event assertThat(getProcessDefinitionByMessage(MESSAGE_NAME).getKey()).isEqualTo(PROCESS_ID); VariableMap variables = Variables.createVariables(); variables.putValue(FLOW_STATE, FlowState.CLAIM_NOTIFIED.fullName()); variables.putValue(FLOW_FLAGS, Map.of(TWO_RESPONDENT_REPRESENTATIVES, twoRespondentRepresentatives, RPA_CONTINUOUS_FEED, true)); //complete the start business process ExternalTask startBusiness = assertNextExternalTask(START_BUSINESS_TOPIC); assertCompleteExternalTask( startBusiness, START_BUSINESS_TOPIC, START_BUSINESS_EVENT, START_BUSINESS_ACTIVITY, variables ); //complete the notification ExternalTask notificationTask = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(notificationTask, PROCESS_CASE_EVENT, NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE, NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE_ACTIVITY_ID, variables ); //complete the CC notification ExternalTask notificationCcTask = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(notificationCcTask, PROCESS_CASE_EVENT, NOTIFY_RESPONDENT_SOLICITOR_1_FOR_CLAIM_ISSUE_CC, NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE_CC_ACTIVITY_ID, variables ); if (twoRespondentRepresentatives) { //complete the additional defendant solicitor notification ExternalTask secondSolicitorNotificationTask = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(secondSolicitorNotificationTask, PROCESS_CASE_EVENT, NOTIFY_RESPONDENT_SOLICITOR_2_FOR_CLAIM_ISSUE, NOTIFY_RESPONDENT_SOLICITOR_2_CLAIM_ISSUE_ACTIVITY_ID, variables ); } //complete the Robotics notification ExternalTask forRobotics = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask( forRobotics, PROCESS_CASE_EVENT, NOTIFY_RPA_ON_CONTINUOUS_FEED, NOTIFY_RPA_ON_CONTINUOUS_FEED_ACTIVITY_ID, variables ); //end business process ExternalTask endBusinessProcess = assertNextExternalTask(END_BUSINESS_PROCESS); completeBusinessProcess(endBusinessProcess); assertNoExternalTasksLeft(); } @Test void shouldSuccessfullyCompleteNotifyClaim_TakenOffline() { //assert process has started assertFalse(processInstance.isEnded()); //assert message start event assertThat(getProcessDefinitionByMessage(MESSAGE_NAME).getKey()).isEqualTo(PROCESS_ID); VariableMap variables = Variables.createVariables(); variables.putValue(FLOW_STATE, FlowState.TAKEN_OFFLINE_AFTER_CLAIM_NOTIFIED.fullName()); //complete the start business process ExternalTask startBusiness = assertNextExternalTask(START_BUSINESS_TOPIC); assertCompleteExternalTask( startBusiness, START_BUSINESS_TOPIC, START_BUSINESS_EVENT, START_BUSINESS_ACTIVITY, variables ); //complete the notification ExternalTask notificationTask = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(notificationTask, PROCESS_CASE_EVENT, NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE, NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE_ACTIVITY_ID, variables ); //complete the CC notification notificationTask = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(notificationTask, PROCESS_CASE_EVENT, NOTIFY_RESPONDENT_SOLICITOR_1_FOR_CLAIM_ISSUE_CC, NOTIFY_RESPONDENT_SOLICITOR_1_CLAIM_ISSUE_CC_ACTIVITY_ID, variables ); //Proceed Offline ExternalTask proceedOfflineTask = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(proceedOfflineTask, PROCESS_CASE_EVENT, PROCEEDS_IN_HERITAGE_SYSTEM, PROCEEDS_IN_HERITAGE_SYSTEM_ACTIVITY_ID ); //Notify Claimant Solicitor - Handed Offline ExternalTask notifyApplicantSolicitorHandedOffline = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(notifyApplicantSolicitorHandedOffline, PROCESS_CASE_EVENT, NOTIFY_APPLICANT_SOLICITOR_1_HAND_OFFLINE, NOTIFY_APPLICANT_SOLICITOR_1_HAND_OFFLINE_ACTIVITY_ID ); //Notify RPA - Handed Offline ExternalTask notifyRpaHandedOffline = assertNextExternalTask(PROCESS_CASE_EVENT); assertCompleteExternalTask(notifyRpaHandedOffline, PROCESS_CASE_EVENT, NOTIFY_RPA_ON_CASE_HANDED_OFFLINE, NOTIFY_RPA_ON_CASE_HANDED_OFFLINE_ACTIVITY_ID ); //end business process ExternalTask endBusinessProcess = assertNextExternalTask(END_BUSINESS_PROCESS); completeBusinessProcess(endBusinessProcess); assertNoExternalTasksLeft(); } @Test void shouldAbort_whenStartBusinessProcessThrowsAnError() { //assert process has started assertFalse(processInstance.isEnded()); //assert message start event assertThat(getProcessDefinitionByMessage(MESSAGE_NAME).getKey()).isEqualTo(PROCESS_ID); //fail the start business process ExternalTask startBusiness = assertNextExternalTask(START_BUSINESS_TOPIC); assertFailExternalTask(startBusiness, START_BUSINESS_TOPIC, START_BUSINESS_EVENT, START_BUSINESS_ACTIVITY); assertNoExternalTasksLeft(); } }
43.941818
116
0.67097
55aac5a91448e24565af52bfdc6063255c652745
856
package net.dblsaiko.bruhmoment.util.list; import net.dblsaiko.bruhmoment.util.IdentifierFilter; public record EntityEntry(IdentifierFilter entityId, IdentifierFilter itemId) { public static EntityEntry fromArgs(String[] args) { if (args.length < 1) { return null; } IdentifierFilter entityId = IdentifierFilter.from(args[0]); IdentifierFilter itemId = IdentifierFilter.any(); if (args.length > 1) { itemId = IdentifierFilter.from(args[1]); } return new EntityEntry(entityId, itemId); } public String[] toArgs() { return new String[] { this.entityId.asString(), this.itemId.asString() }; } @Override public String toString() { return String.format("EntityEntry { entityId: %s, itemId: %s }", this.entityId, this.itemId); } }
28.533333
101
0.642523
1921f7ca589b07e85e796993e0aeec85d7e77741
2,339
package cn.brainco.limiting_direction_csx; import androidx.appcompat.app.AppCompatActivity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements SensorEventListener { private SensorManager mSensorManager; private Sensor mAccelerometer; public static final float mGravity = 9.8f; //屏幕旋转字符串 private String orientationStr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent sensorEvent) { float xValue = sensorEvent.values[0];// Acceleration minus Gx on the x-axis float yValue = sensorEvent.values[1];//Acceleration minus Gy on the y-axis float zValue = sensorEvent.values[2]; orientationStr = "0";//Acceleration minus Gz on the z-axis if (yValue > mGravity) { //重力指向设备下边 orientationStr = "1"; } else if (yValue < -mGravity) { //重力指向设备上边 orientationStr = "2"; } else if (xValue > mGravity) { //重力指向设备左边 orientationStr = "3"; } else if (xValue < -mGravity) { //重力指向设备右边 orientationStr = "4"; } else if (zValue > mGravity) { //屏幕朝上 orientationStr = "5"; } else if (zValue < -mGravity) { //屏幕朝下 orientationStr = "6"; } // channel.invokeMethod("orientationCallback", orientationStr); } }
33.898551
98
0.638307
b6c96e3636ac76104927edb4d4121dfef56b587f
74,876
package org.jesperancinha.java11.mastery4dot2; import org.jesperancinha.console.consolerizer.console.Consolerizer; import org.jesperancinha.java11.mastery4dot2.band.EffectiveBandManager; import org.jesperancinha.java11.mastery4dot2.band.GeneralBandManager; import org.jesperancinha.java11.mastery4dot2.band.QuintetBandManager; import org.jesperancinha.java11.mastery4dot2.concert.Band; import org.jesperancinha.java11.mastery4dot2.concert.GenericBand; import org.jesperancinha.java11.mastery4dot2.concert.QuintetBand; import org.jesperancinha.java11.mastery4dot2.concert.Ticket; import org.jesperancinha.java11.mastery4dot2.instrument.DrumException; import org.jesperancinha.java11.mastery4dot2.instrument.Drums; import org.jesperancinha.java11.mastery4dot2.instrument.DrumsIOException; import org.jesperancinha.java11.mastery4dot2.record.Company; import org.jesperancinha.java11.mastery4dot2.show.CristalBall; import org.jesperancinha.java11.mastery4dot2.show.SuperCristalBall; import org.jesperancinha.java11.mastery4dot2.songs.Compilation; import org.jesperancinha.java11.mastery4dot2.styles.Indie; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Permission; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.temporal.Temporal; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Objects; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.BLUE; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.BRIGHT_CYAN; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.BRIGHT_MAGENTA; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.GREEN; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.MAGENTA; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.ORANGE; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.RED; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.YELLOW; import static org.jesperancinha.console.consolerizer.console.Consolerizer.printRainbowLn; import static org.jesperancinha.console.consolerizer.console.ConsolerizerGraphs.printUnicornsLn; import static org.jesperancinha.java11.mastery4dot2.concert.Ticket.getTicketsLongNumbers; import static org.jesperancinha.java11.mastery4dot2.concert.Ticket.getTicketsStringNumbers; public class Mastery4Dot2Runner { private static boolean skipQuestions; public static void main(String[] args) { if (args.length > 0) { skipQuestions = "-skip".equals(args[0]); } Consolerizer.typingWaitGlobal = 0; Consolerizer.maxLineCharsGlobal = 200; BLUE.printGenericLn("==================== Master Module mastery-4-2 ===================="); BLUE.printGenericLn("----> Run with VM command -ea or -enableassertions for a more accurate run"); BLUE.printGenericLn("----> Run with -skip to skip questions"); BLUE.printGenericLn("----> Note that this mastery need the prepare.sh script to be run first."); exercise1(); exercise2(); exercise3(); exercise4(); exercise5(); exercise6(); exercise7(); exercise8(); exercise9(); exercise10(); exercise11(); exercise12(); exercise13(); exercise14(); exercise15(); exercise16(); exercise17(); exercise18(); exercise19(); moduleEnd(); } private static void exercise19() { BRIGHT_CYAN.printGenericLn("--- 19. `try-with-resources` `open` and `close` methods."); printRainbowLn("=="); GREEN.printGenericLn("Case: We are at the end of our mastery module"); GREEN.printGenericLn("If you noticed, drums are a part of almost all spanish music"); GREEN.printGenericLn("We'll play one as a closeable instrument. Enjoy!"); var drum = new Drums(); try (drum) { drum.playDrum(); drum.playWrongDrum(); } catch (DrumException | DrumsIOException e) { RED.printGenericLn("It's all good! We failed to play, closing failed and this is expected -> %s", e); } GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. We can use try-with-resources even after we've created our autocloseable instance"); GREEN.printGenericLn("2. A suppressed exception occurs when closing fails"); GREEN.printGenericLn("3. The suppressed exception is the closing exception when one is thrown in the try block"); GREEN.printGenericLn("4. The main exception is the one thrown during the try scope"); GREEN.printGenericLn("5. If no exception is thrown during the try block, no suppressed exception is thrown"); } private static void exercise18() { BRIGHT_CYAN.printGenericLn("--- 18. `Arrays` `binarySearch`"); printRainbowLn("=="); GREEN.printGenericLn("Case: We have compiled a list of of all Lori Meyers albums we know"); GREEN.printGenericLn("Lori Meyers started in 1998. You are now in possession of a lot of their records."); GREEN.printGenericLn("Now you want to organize them!."); final String[] albums = {"Viaje de estudios", "Hostal Pimodán", "Hostal Pimodán (reedición)", "Cronolánea", "Viaje de estudios (reedición)", "Cuando el destino nos alcance", "Impronta"}; int foundIndex = Arrays.binarySearch(albums, "D"); MAGENTA.printGenericLn("Our record collection is:\n%s", Arrays.stream(albums).collect(Collectors.toList())); MAGENTA.printGenericLn("Our insertion point results in %d. This result makes no sense, purely because our array isn't sorted", foundIndex); Arrays.sort(albums); MAGENTA.printGenericLn("After sorting, our record collection is:\n%s", Arrays.stream(albums).collect(Collectors.toList())); foundIndex = Arrays.binarySearch(albums, "D"); MAGENTA.printGenericLn("Once sorted, we finally have insertion point %d. This is correct", foundIndex); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. In order to make binarySearch for Arrays, we have to sort them first"); GREEN.printGenericLn("2. Sorting arrays and therefore being able to perform a faster and more accurate binary search isn't specific to Java"); GREEN.printGenericLn("3. The insertion point is an index. It is describe as a negative number"); } private static void exercise17() { BRIGHT_CYAN.printGenericLn("--- 17. `writeUTF` and where it is possible with `BufferedWriter` and `FileOutputWriter`"); printRainbowLn("=="); GREEN.printGenericLn("Case: In the year 2000, spanish singer, Monica Naranjo, came into the music scene with her hit \"Sobreviviré\""); GREEN.printGenericLn("Given the raw energy of the lyrics of the songs and its meaning, \"Sobreviviré\" became an anthem of those who fight to be understood and accepted"); GREEN.printGenericLn("In the video, Monica Naranjo depics just that."); GREEN.printGenericLn("We want to copy these lyrics from the source to new files."); GREEN.printGenericLn("We will do this in two ways. One with a BufferedWriter and the other with a FileOutputStream."); String source = null; try (var fis = new FileInputStream("/tmp/monica_naranjo_lyrics.txt")) { source = new String(fis.readAllBytes(), Charset.defaultCharset()); } catch (FileNotFoundException e) { RED.printThrowableAndExit(e); } catch (IOException e) { RED.printThrowableAndExit(e); } MAGENTA.printGenericLn("We just read the lyrics"); BRIGHT_MAGENTA.printGenericLn(source); MAGENTA.printGenericLn("We will now write this to file in UTF(Unicode Transformation Format) %s", "/tmp/mn1.txt"); try (var fos = new FileOutputStream("/tmp/mn1.txt")) { final ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeUTF(source); oos.flush(); } catch (FileNotFoundException e) { RED.printThrowableAndExit(e); } catch (IOException e) { RED.printThrowableAndExit(e); } readFile("/tmp/mn1.txt"); try (var bw = new BufferedWriter(new FileWriter("/tmp/mn2.txt", Charset.defaultCharset()))) { bw.write('U'); bw.write('T'); bw.write('F'); bw.write('-'); bw.write(source); } catch (IOException e) { RED.printThrowableAndExit(e); } readFile("/tmp/mn2.txt"); try (var fos = new FileOutputStream("/tmp/mn3.txt")) { final OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.defaultCharset().name()); osw.write(source); osw.flush(); } catch (FileNotFoundException e) { RED.printThrowableAndExit(e); } catch (IOException e) { RED.printThrowableAndExit(e); } GREEN.printGenericLn("Take-away"); readFile("/tmp/mn3.txt"); GREEN.printGenericLn("1. We can specify UTF with FileWriter, OutputStreamWriter and with ObjectOutputStream"); GREEN.printGenericLn("2. It is not mandatory to specify UTF with Writers. CharSet is optional"); GREEN.printGenericLn("3. In the OutputStream we have methods that can write in UTF directly (writeUTF)"); } private static void readFile(String resultFilename) { try (var fis = new FileInputStream(resultFilename)) { MAGENTA.printGenericLn("We just read this from file %s", resultFilename); final String s = new String(fis.readAllBytes(), Charset.defaultCharset()); BRIGHT_MAGENTA.printGenericLn(s); } catch (FileNotFoundException e) { RED.printThrowableAndExit(e); } catch (IOException e) { RED.printThrowableAndExit(e); } } private static void exercise16() { BRIGHT_CYAN.printGenericLn("--- 16. NavigableMap and `pollLastEntry` and `pollFirstEntry`"); printRainbowLn("=="); GREEN.printGenericLn("Case: \"Supersubmarina\" is a band from Spain."); GREEN.printGenericLn("In 2008 and 2009, they've edited their first two EP(Extended Play)s"); GREEN.printGenericLn("You'll show these vinyls to your friends"); GREEN.printGenericLn("And then you will lend them"); final String[] cientoCero = {"Cientocero", "Elástica galáctica", "No es así", "Cientocero (english)", "Cientocero (maqueta)"}; final String[] supersubmarina = {"Supersubmarina", "Ana", "Supersubmarina", "OCB"}; final NavigableMap<String, List<String>> albums = new TreeMap<>() {{ put("Cientocero", Arrays.stream(cientoCero).collect(Collectors.toList())); put("Supersubmarina", Arrays.stream(supersubmarina).collect(Collectors.toList())); }}; MAGENTA.printGenericLn("Ciento cero is %s", String.join(",", cientoCero)); MAGENTA.printGenericLn("Supersubmarina is %s", String.join(",", supersubmarina)); BLUE.printGenericLn("Let's tail this from %s:", "Cientocero"); MAGENTA.printGenericLn("%s", albums.tailMap("Cientocero")); BLUE.printGenericLn("And now from %s:", "Supersubmarina"); MAGENTA.printGenericLn("%s", albums.tailMap("Supersubmarina")); BLUE.printGenericLn("Let's head this from %s:", "Cientocero"); MAGENTA.printGenericLn("%s", albums.headMap("Cientocero")); BLUE.printGenericLn("And now from %s:", "Supersubmarina"); MAGENTA.printGenericLn("%s", albums.headMap("Supersubmarina")); final Map.Entry<String, List<String>> firstLending = albums.pollFirstEntry(); MAGENTA.printGenericLn("We just took out the first album: %s", firstLending); MAGENTA.printGenericLn("So the our album collection looks like this: %s", albums); final Map.Entry<String, List<String>> lastLending = albums.pollLastEntry(); MAGENTA.printGenericLn("We just took out the last album: %s", lastLending); MAGENTA.printGenericLn("So the our album collection should be empty now: %s", albums); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. Navigable maps are very simple"); GREEN.printGenericLn("2. Important methods are pollFirstEntry, pollLastEntry, tailMap and headMaps"); GREEN.printGenericLn("3. Head is exclusive, whiile tail is inclusive"); } private static void exercise15() { BRIGHT_CYAN.printGenericLn("--- 15. Iterating through a `CopyOnWriteArrayList` and the `UnsupportedOperationException`"); printRainbowLn("=="); GREEN.printGenericLn("Case: Someone is compiling songs of the band Dorian for you."); GREEN.printGenericLn("Your other half is waiting impatiently for the mix result."); GREEN.printGenericLn("You keep getting a list, always updated, but you have to read it at the same time its being filled."); GREEN.printGenericLn("It's hard to keep up, and so you decide to make multiple reads."); final String[] songs = { "Buenas Intenciones", "Duele", "La Tormenta de Arena", "Los Amigos que Perdí", "El Futuro no es de Nadie", "Vicios y Defectos", "Tristeza", "A Cualquier Otra parte", "Te Echamos de Menos (Undo Remix)", "Horas Bajas (Undo Remix)", "El Temblor (Lovo Remix)", "Verte Amanecer"}; MAGENTA.printGenericLn("This is our possible list:"); ORANGE.printGenericLn("%s", String.join(",", songs)); final Compilation compilation = new Compilation(); final var songSet = Arrays.stream(songs).collect(Collectors.toCollection(ConcurrentSkipListSet::new)); final ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.submit(() -> { try { while (songSet.size() > 0) { final String s = songSet.pollFirst(); compilation.addSong(s); Thread.sleep(100); } } catch (InterruptedException e) { RED.printThrowableAndExit(e); } }); executorService.submit(() -> { try { while (songSet.size() > 0) { final Iterator<String> iterator = compilation.iterator(); while (iterator.hasNext()) { MAGENTA.printGenericLn("Got song %s", iterator.next()); Thread.sleep(500); } BRIGHT_MAGENTA.printGenericLn("One Iteration done!"); } final Iterator<String> iterator = compilation.iterator(); while (iterator.hasNext()) { MAGENTA.printGenericLn("Got song %s", iterator.next()); Thread.sleep(500); } BRIGHT_MAGENTA.printGenericLn("Last iteration done!"); } catch (InterruptedException e) { RED.printThrowableAndExit(e); } }); executorService.shutdown(); try { executorService.awaitTermination(15, TimeUnit.SECONDS); } catch (InterruptedException e) { RED.printThrowableAndExit(e); } final Iterator<String> iterator = compilation.iterator(); MAGENTA.printGenericLn("No exception has occurred and everything went well."); BLUE.printGenericLn("Can we change the list with this iterator though?"); try { iterator.remove(); } catch (UnsupportedOperationException e) { RED.printGenericLn("We cannot! And this is because this iterator is working with an array that is allowed to be copied and discarded -> %s", e); } GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. CopyOnWriteArrayList make a copy on every write operation"); GREEN.printGenericLn("2. This way, there will be no concurrent type of exception thrown"); GREEN.printGenericLn("3. The iterator of this type of List's does not support modifications"); } private static void exercise14() { BRIGHT_CYAN.printGenericLn("--- 14. Static and instance initialization of final `members`"); printRainbowLn("=="); GREEN.printGenericLn("Case: We know that the band Dorian is mostly classified as being an Indie pop group."); GREEN.printGenericLn("We'll create its registry and see the many different ways we can initialize final values."); GREEN.printGenericLn("Have a look in the code. All these fields are mandatory and cannot change because they are final"); var dorian = new Indie("Dorian"); MAGENTA.printGenericLn("This is our band %s", dorian); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. All final fields have to be initialized"); GREEN.printGenericLn("2. There is no difference in this mandatory action between static and instance members"); GREEN.printGenericLn("3. Members can be initialized using accolades"); GREEN.printGenericLn("4. There isn't a lot of reasons to use accolades this way. Just know that they work"); } private static void exercise13() { BRIGHT_CYAN.printGenericLn("--- 13. `Float.POSITIVE_INFINITY` vs `Float.NEGATIVE_INFINITY`"); printRainbowLn("=="); GREEN.printGenericLn("Case: Vetusta Morla publish in 2020 its fith studio album entitled \"Mismo Sitio Distinto Lugar - Canciones dentro de canciones\"."); GREEN.printGenericLn("They came up with this original concept of songs within songs."); GREEN.printGenericLn("When you find a song within a song you are really up to infinity."); GREEN.printGenericLn("We can represent the infinity of songs Vetusta Morla can make by using Float and Double."); var songs = Float.POSITIVE_INFINITY; var nosongs = Float.NEGATIVE_INFINITY; ORANGE.printGenericLn(songs); ORANGE.printGenericLn(nosongs); BLUE.printGenericLn("But how can we generate infinite songs?"); var infiniteSongs = 1 / 0.0f; var noSongsToInfinity = -1 / 0.0f; ORANGE.printGenericLn(infiniteSongs); ORANGE.printGenericLn(noSongsToInfinity); BLUE.printGenericLn("Can we use double for this?"); var songsDouble = Double.POSITIVE_INFINITY; var nosongsDouble = Double.NEGATIVE_INFINITY; ORANGE.printGenericLn(songsDouble); ORANGE.printGenericLn(nosongsDouble); BLUE.printGenericLn("But how can we generate double infinite songs?"); var infiniteSongsDouble = 1 / 0.0; var noSongsToInfinityDouble = -1 / 0.0; ORANGE.printGenericLn(infiniteSongsDouble); ORANGE.printGenericLn(noSongsToInfinityDouble); BLUE.printGenericLn("Sounds good, but how about that overflow Exception?"); try { var notWithLongs = 1 / 0L; } catch (ArithmeticException e) { RED.printGenericLn("Nope, no Longs allowed! -> %s", e); } BLUE.printGenericLn("Ok... and ints?"); try { var notWithIntegers = 1 / 0; } catch (ArithmeticException e) { RED.printGenericLn("Nope, no ints either! -> %s", e); } BLUE.printGenericLn("Shorts?"); try { var notWithShorts = 1 / (short) 0; } catch (ArithmeticException e) { RED.printGenericLn("Shorts also won't do! -> %s", e); } BLUE.printGenericLn("Then I guess Byte won't also work?"); try { var notWithBytes = 1 / (byte) 0; } catch (ArithmeticException e) { RED.printGenericLn("Bingo! -> %s", e); } GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. There infinity representations for Float and Double calculations"); GREEN.printGenericLn("2. Numbers without decimals cannot make a division by zero"); GREEN.printGenericLn("3. Division by zero with Float and Double are akin to ∞ (infinity) in math."); } private static void exercise12() { BRIGHT_CYAN.printGenericLn("--- 12. Immutability with Guidelines 7 and 6"); printRainbowLn("=="); GREEN.printGenericLn("Case: We just made a much safer Cristal Ball for Alaska to use."); GREEN.printGenericLn("Let's give it a try!."); SuperCristalBall superBolaDeCristal = null; try { superBolaDeCristal = SuperCristalBall.createCristalBall( "Alaska", new Date(86, Calendar.OCTOBER, 6), new Band( List.of( "Alaska", "Nacho Canut", "Ana Curra", "Eduardo Benavente", "Carlos Berlanga" ), "Alaska y los Pegamoides")); } catch (NoSuchProviderException e) { RED.printThrowableAndExit(e); } catch (NoSuchAlgorithmException e) { RED.printThrowableAndExit(e); } MAGENTA.printGenericLn("This is our new and improved cristal ball:\n%s", superBolaDeCristal); BLUE.printGenericLn("Note that we've made this Cristal Ball so safe that it now obeys guidelines 6 and 7!"); BLUE.printGenericLn("Therefore, for this module, there isn't much to test."); BLUE.printGenericLn("Please follow the code for a better understandinf of what's happening and namely have a look at the comments."); BLUE.printGenericLn("Of course read the guidelines here -> https://www.oracle.com/java/technologies/javase/seccodeguide.html"); // Guideline 7-2 / OBJECT-2: Prevent the unauthorized construction of sensitive classes SecurityManager setSecurityManager = new SecurityManager() { @Override public void checkExit(int status) { throw new RuntimeException("Ahha! Not today you are not!"); } @Override public void checkPermission(Permission perm) { } }; System.setSecurityManager(setSecurityManager); try { assert superBolaDeCristal != null; // Guideline 7-2 / OBJECT-2: Prevent the unauthorized construction of sensitive classes superBolaDeCristal.leaveEarth(); } catch (RuntimeException e) { RED.printGenericLn("The reason why this exception is thrown is that our SecurityManager doesn't let us exit with an error:\n%s\nIt's magic!", e); } System.setSecurityManager(null); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. We've made a few tests here, but this module will not be able to cover all of guidelines 6 and 7"); GREEN.printGenericLn("2. Guideline 6 is about protecting Mutability"); GREEN.printGenericLn("3. Guideline 7 is about protecting Object construction"); GREEN.printGenericLn("4. Some guidelines may fuse with each other"); GREEN.printGenericLn("5. Some are much more important than others"); GREEN.printGenericLn("6. Guideline 7-1 / OBJECT-1: Avoid exposing constructors of sensitive classes"); GREEN.printGenericLn("7. Guideline 7-2 / OBJECT-2: Prevent the unauthorized construction of sensitive classes"); GREEN.printGenericLn("8. Guideline 7-4 / OBJECT-4: Prevent constructors from calling methods that can be overridden"); GREEN.printGenericLn("9. Guideline 7-5 / OBJECT-5: Defend against cloning of non-final classes"); } private static void exercise11() { BRIGHT_CYAN.printGenericLn("--- 11. Method overloading and overriding with `extends`"); printRainbowLn("=="); GREEN.printGenericLn("Case: Some of us like music \"Rosario Flores\" style, others prefer something more edgy like \"Dorian\"."); GREEN.printGenericLn("We now have to manage the upcoming dates and for that we have created just one BandManager abstraction"); GREEN.printGenericLn("Further we have implemented 3 different ways to override and other two to overload the BandManager method."); GREEN.printGenericLn("We'll put these methods to the test for different times of music history."); var band = new Band(List.of( "Santi Balmes", "Julián Saldarriaga", "Jordi Roig", "Joan Ramón Planell", "Oriol Bonet"), "Love of Lesbian"); var quintetBand = new QuintetBand( List.of( "Alaska", "Nacho Canut", "Ana Curra", "Eduardo Benavente", "Carlos Berlanga" ), "Alaska y los Pegamoides"); var genericBand = new GenericBand( 6, List.of( "Pucho", "David \"el Indio\"", "Álvaro B. Baglietto", "Jorge González", "Guillermo Galván", "Juanma Latorre" ), "Vetusta Morla"); var paulinaRubio = new GenericBand(1, List.of("Paulina Rubio"), "Paulina Rubio"); var rosarioFlores = new GenericBand(1, List.of("Rosario Flores"), "Rosario Flores"); MAGENTA.printGenericLn("These are our bands:\n%s\n%s\n%s\n%s\n%s", band, quintetBand, genericBand, paulinaRubio, rosarioFlores); var effectiveBandManager = new EffectiveBandManager(); var generalBandManager = new GeneralBandManager(); var quintetBandManager = new QuintetBandManager(); final Map<Band, Temporal> upcomingDates = effectiveBandManager.getUpcomingDates(band, LocalDateTime.now()); final Map<GenericBand, LocalDateTime> upcomingDates1 = generalBandManager.getUpcomingDates(genericBand, LocalDateTime.now()); final Map<QuintetBand, LocalDate> upcomingDates2 = quintetBandManager.getUpcomingDates(quintetBand, LocalDate.now()); MAGENTA.printGenericLn("The first maps are now ready:\n%s\n%s\n%s", upcomingDates, upcomingDates1, upcomingDates2); upcomingDates1.put(paulinaRubio, LocalDateTime.now()); upcomingDates1.put(rosarioFlores, LocalDateTime.now()); MAGENTA.printGenericLn("Adding two more artists to this new concert we get:\n%s", upcomingDates1); final Map<GenericBand, LocalDateTime> upcomingDates3 = generalBandManager.getUpcomingDates((Band) genericBand, LocalDateTime.now()); final Map<QuintetBand, LocalDate> upcomingDates4 = quintetBandManager.getUpcomingDates((Band) quintetBand, LocalDate.now()); BRIGHT_MAGENTA.printGenericLn("Had we used the overriden methods we would have gotten:\n%s\nand\n%s", upcomingDates3, upcomingDates4); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. Overloading and overriding with extends obeys some specific rules"); GREEN.printGenericLn("2. The base type is the parameter you have to use in order to override"); GREEN.printGenericLn("3. Subclass types of the declared base parameter always results in overloading"); GREEN.printGenericLn("4. The return parameters may be subclass types"); GREEN.printGenericLn("5. Since they have to be subclasses or the same, the type cannot be erased when overriding"); } private static void exercise10() { BRIGHT_CYAN.printGenericLn("--- 10. Evaluation order of conditional operators"); printRainbowLn("=="); GREEN.printGenericLn("Case: Pepe is a manager that loves going to concerts."); GREEN.printGenericLn("In your team, you know that he is crazy about \"Vetusta Morla\"."); GREEN.printGenericLn("However, sometimes, Pepe forgets to say to the team that is off."); GREEN.printGenericLn("Not only that, but at the same time that \"Vetusta Morla\" is playing, \"Sidonie\" is also playing in the same week."); GREEN.printGenericLn("If any of this is true, then we know that Pepe will be off the whole November of 2011."); GREEN.printGenericLn("We'll check this:"); var month = 11; var year = 2011; if (pepeIsOffOn(year, month, 24) || pepeIsOffOn(year, month, 25)) { MAGENTA.printGenericLn("Pepe won't be coming to work this november!"); } GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. Logic operators such as || and && can short circuit in Java"); GREEN.printGenericLn("2. Short circuiting does not imply the evaluation of all operands"); GREEN.printGenericLn("3. Since they are evaluated left to right and considering mathematical precedence, the runtime knows when further evaluation is not needed"); GREEN.printGenericLn("4. When not all operands are evaluated, we call this a short-circuit"); } private static boolean pepeIsOffOn(int year, int month, int day) { var concertVetustaDate = LocalDateTime.of(2011, 11, 25, 0, 0); var concertSidonieDate = LocalDateTime.of(2011, 11, 24, 0, 0); if (concertVetustaDate.getYear() == year && concertVetustaDate.getMonthValue() == month && concertVetustaDate.getDayOfMonth() == day) { MAGENTA.printGenericLn("Pepe is going to see Vetusta Morla on the %s", concertVetustaDate); return true; } if (concertVetustaDate.getYear() == year && concertSidonieDate.getMonthValue() == month && concertSidonieDate.getDayOfMonth() == day) { MAGENTA.printGenericLn("Pepe is going to see Sidonie on the %s", concertSidonieDate); return true; } return false; } private static void exercise9() { BRIGHT_CYAN.printGenericLn("--- 9. Why use `putIfAbsent`?"); printRainbowLn("=="); GREEN.printGenericLn("Case: Someone in your group of friends suggested to go to the next concert of Paulina Rubio."); GREEN.printGenericLn("Unfortunatelly you cannot go."); GREEN.printGenericLn("However your friends, Paco, Lori, Nere, Cristina, Viktor, Carlos and Andrea, are really excited to go!"); GREEN.printGenericLn("We need to distribute the tickets as fast as possible and store them in a map."); GREEN.printGenericLn("The best ticket is the front row one, so in spite of being best friends, they will struggle to get the best one first!"); ORANGE.printGenericLn("Ticket office is open!"); var ticketFrontRow = new Ticket("Paulina Rubio", "Valdemoro - Madrid - España", "ES1028562319", LocalDateTime.of(2010, 5, 8, 0, 0)); var ticketRowTwo = new Ticket("Paulina Rubio", "Valdemoro - Madrid - España", "ES0384518495", LocalDateTime.of(2010, 5, 8, 0, 0)); var ticketRowThree = new Ticket("Paulina Rubio", "Valdemoro - Madrid - España", "ES0174538594", LocalDateTime.of(2010, 5, 8, 0, 0)); var ticketRowFour = new Ticket("Paulina Rubio", "Valdemoro - Madrid - España", "ES3287451065", LocalDateTime.of(2010, 5, 8, 0, 0)); var ticketRowFive = new Ticket("Paulina Rubio", "Valdemoro - Madrid - España", "ES0102956473", LocalDateTime.of(2010, 5, 8, 0, 0)); var ticketRowSix = new Ticket("Paulina Rubio", "Valdemoro - Madrid - España", "ES6674993217", LocalDateTime.of(2010, 5, 8, 0, 0)); var ticketRowSeven = new Ticket("Paulina Rubio", "Valdemoro - Madrid - España", "ES9928465748", LocalDateTime.of(2010, 5, 8, 0, 0)); var precedenceTickets = List.of(ticketFrontRow, ticketRowTwo, ticketRowThree, ticketRowFour, ticketRowFive, ticketRowSix, ticketRowSeven); ExecutorService executorService = Executors.newFixedThreadPool(7); final var ticketMap = new ConcurrentHashMap<Ticket, String>(); executorService.submit(tryAssignTo(precedenceTickets, ticketMap, "Paco")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap, "Lori")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap, "Nere")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap, "Cristina")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap, "Viktor")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap, "Carlos")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap, "Andrea")); executorService.shutdown(); try { executorService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { RED.printThrowableAndExit(e); } MAGENTA.printGenericLn("The result is \n%s", ticketMap.entrySet().stream().map(Object::toString).collect(Collectors.joining("\n"))); GREEN.printGenericLn("We would get the same result if we had used putIfAbsent:"); final var ticketMap2 = new ConcurrentHashMap<Ticket, String>(); executorService = Executors.newFixedThreadPool(7); executorService.submit(tryAssignToNoLog(precedenceTickets, ticketMap2, "Paco")); executorService.submit(tryAssignToNoLog(precedenceTickets, ticketMap2, "Lori")); executorService.submit(tryAssignToNoLog(precedenceTickets, ticketMap2, "Nere")); executorService.submit(tryAssignToNoLog(precedenceTickets, ticketMap2, "Cristina")); executorService.submit(tryAssignToNoLog(precedenceTickets, ticketMap2, "Viktor")); executorService.submit(tryAssignToNoLog(precedenceTickets, ticketMap2, "Carlos")); executorService.submit(tryAssignToNoLog(precedenceTickets, ticketMap2, "Andrea")); executorService.shutdown(); try { executorService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { RED.printThrowableAndExit(e); } MAGENTA.printGenericLn("The new result is \n%s", ticketMap.entrySet().stream().map(Object::toString).collect(Collectors.joining("\n"))); GREEN.printGenericLn("These operations will not fail for non-thread safe maps:"); final var ticketMap3 = new HashMap<Ticket, String>(); executorService = Executors.newFixedThreadPool(7); executorService.submit(tryAssignTo(precedenceTickets, ticketMap3, "Paco")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap3, "Lori")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap3, "Nere")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap3, "Cristina")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap3, "Viktor")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap3, "Carlos")); executorService.submit(tryAssignTo(precedenceTickets, ticketMap3, "Andrea")); executorService.shutdown(); try { executorService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { RED.printThrowableAndExit(e); } MAGENTA.printGenericLn("The new result is also what we are looking for:\n%s", ticketMap.entrySet().stream().map(Object::toString).collect(Collectors.joining("\n"))); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. In order to add to a hashmap in a concurrent way, we should use an atomic operation."); GREEN.printGenericLn("2. putIfAbsent performs a check if exists and add then if not, it puts an element into the map in an atomic way."); GREEN.printGenericLn("3. This, also works in a non-thread safe map."); GREEN.printGenericLn("4. For that we do not have to combine our operation with a ConcurrentHashMap which is thread safe."); } private static Runnable tryAssignToNoLog(List<Ticket> precedenceTickets, Map<Ticket, String> ticketMap, String winner) { return () -> { for (var nextTicket : precedenceTickets) { final String computeIfAbsent = ticketMap.putIfAbsent(nextTicket, winner); if (Objects.equals(computeIfAbsent, winner)) { break; } } }; } private static Runnable tryAssignTo(List<Ticket> precedenceTickets, Map<Ticket, String> ticketMap, String winner) { return () -> { for (var nextTicket : precedenceTickets) { final String computeIfAbsent = ticketMap.computeIfAbsent(nextTicket, ticket -> { ORANGE.printGenericLn("Assigning ticket %s to %s", ticket, winner); return winner; }); if (Objects.equals(computeIfAbsent, winner)) { break; } } }; } private static void exercise8() { BRIGHT_CYAN.printGenericLn("--- 8. Overwriting with `FileOutputStream`"); printRainbowLn("=="); GREEN.printGenericLn("Case: \"Sueño su boca\" was the first big hit of Raúl Cuenca in Spain."); GREEN.printGenericLn("In the year 2000, this hit was being played all across spanish speaking countries and the rest of the latin world."); GREEN.printGenericLn("You want to save the lyrics and made it through to copying them to one friend"); GREEN.printGenericLn("Now you you are making the second copy you make a mistake and only copy a bit of it to the same destination file."); GREEN.printGenericLn("Will there be a change?."); try ( var fis = new FileInputStream("/tmp/raul_lyrics.txt"); var fos = new FileOutputStream("/tmp/raul_lyrics2.txt"); ) { byte[] buffer = new byte[2048]; int bytes; while ((bytes = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes); YELLOW.printGenericLn(new String(buffer).trim()); } } catch (FileNotFoundException e) { RED.printThrowableAndExit(e); } catch (IOException e) { RED.printThrowableAndExit(e); } catch (Exception e) { RED.printThrowableAndExit(e); } BLUE.printGenericLn("Check your file contents in the file system: /tmp/raul_lyrics2.txt."); BLUE.printGenericLn("Press ENTER twice to continue..."); if (!skipQuestions) { try { System.in.read(); } catch (IOException e) { RED.printThrowableAndExit(e); } } try ( var fis = new FileInputStream("/tmp/raul_lyrics.txt"); var fos = new FileOutputStream("/tmp/raul_lyrics2.txt"); ) { byte[] buffer = new byte[100]; int bytes; bytes = fis.read(buffer); fos.write(buffer, 0, bytes); YELLOW.printGenericLn(new String(buffer).trim()); } catch (FileNotFoundException e) { RED.printThrowableAndExit(e); } catch (IOException e) { RED.printThrowableAndExit(e); } catch (Exception e) { RED.printThrowableAndExit(e); } GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. By default, FileOutputStream is configured to have the appendMode to false."); GREEN.printGenericLn("2. If appendMode is disable, the file gets overwritten."); GREEN.printGenericLn("3. Overwriting a file means that the file is written all over again."); GREEN.printGenericLn("4. When we start again, we remove all original data."); } private static void exercise7() { BRIGHT_CYAN.printGenericLn("--- 7. Immutability standards and using `LocalDate` and `LocalDateTime`"); printRainbowLn("=="); GREEN.printGenericLn("Case: Alaska started a show in 1984 based on the writings of Dolores Rico Oliver called \"La bola de cristal\"."); GREEN.printGenericLn("\"La bola de cristal\", if yo haven't guessed already means \"The cristal ball\""); GREEN.printGenericLn("Cristal balls are always portrayed the same way"); GREEN.printGenericLn("They are magic and they give information about the past, the present and the future."); GREEN.printGenericLn("Each cristal ball is also unique, but how do cristal balls make sure they are not tampered with?"); GREEN.printGenericLn("In other words, what makes cristal balls immutable?"); GREEN.printGenericLn("For our case we are just interested on the first 5 requirements for security guidelines 6 on Mutable classes: https://www.oracle.com/java/technologies/javase/seccodeguide.html"); CristalBall bolaDeCristal = null; try { bolaDeCristal = CristalBall.createCristalBall( "Alaska", new Date(86, Calendar.OCTOBER, 6), new Band( List.of( "Alaska", "Nacho Canut", "Ana Curra", "Eduardo Benavente", "Carlos Berlanga" ), "Alaska y los Pegamoides")); } catch (NoSuchProviderException e) { RED.printThrowableAndExit(e); } catch (NoSuchAlgorithmException e) { RED.printThrowableAndExit(e); } MAGENTA.printGenericLn("This is the Cristal Ball of Episode I\n%s", bolaDeCristal); MAGENTA.printGenericLn("We can get the from the available ones\n%s", CristalBall.getHost(bolaDeCristal)); MAGENTA.printGenericLn("We can get it from the available ones\n%s", CristalBall.getCristalBall(bolaDeCristal.getPriv())); BRIGHT_CYAN.printGenericLn("We can also comment it out:"); bolaDeCristal.setComment("Me encanta este show! Super guay!!"); MAGENTA.printGenericLn("And then we get a comment on our Cristal Ball\n%s", bolaDeCristal); BRIGHT_CYAN.printGenericLn("And if we check if this is immutable:"); Date date = bolaDeCristal.getDate(); Date dateSafeCopy = bolaDeCristal.getDateSafeCopy(); LocalDate localDate = bolaDeCristal.getLocalDate(); LocalDateTime localDateTime = bolaDeCristal.getLocalDateTime(); Band band = bolaDeCristal.getBand(); String host = bolaDeCristal.getHost(); MAGENTA.printGenericLn("We get that\n%s had a band:\n%s\nand the pilot show aired on spanish television on the:%s\n%s\n%s\n%s ", host, band, date, dateSafeCopy, localDate, localDateTime); BRIGHT_CYAN.printGenericLn("Let's tamper that and see if we can change it!"); date.setYear(200); dateSafeCopy.setTime(200); band.capacity = 1000; BRIGHT_CYAN.printGenericLn("Note that LocalDate and LocalDateTime are already immutable"); BRIGHT_CYAN.printGenericLn("We did change the date objects and the capacity."); BRIGHT_CYAN.printGenericLn("From the outside we get the impression that we changed our original cristal ball:"); MAGENTA.printGenericLn("We get that\n%s had a band:\n%s\nand the pilot show aired on spanish television on the:%s\n%s\n%s\n%s ", host, band, date, dateSafeCopy, localDate, localDateTime); BRIGHT_CYAN.printGenericLn("But from the inside we see that nothing has changed:"); date = bolaDeCristal.getDate(); dateSafeCopy = bolaDeCristal.getDateSafeCopy(); localDate = bolaDeCristal.getLocalDate(); localDateTime = bolaDeCristal.getLocalDateTime(); band = bolaDeCristal.getBand(); host = bolaDeCristal.getHost(); MAGENTA.printGenericLn("We get that\n%s had a band:\n%s\nand the pilot show aired on spanish television on the:%s\n%s\n%s\n%s ", host, band, date, dateSafeCopy, localDate, localDateTime); BRIGHT_CYAN.printGenericLn("If we make a copy of it, we can use our method. Remember that we made a copy method to make a copy easy and follow the secuirty guidelines:"); try { MAGENTA.printGenericLn("This is our copy:\n%s", bolaDeCristal.copy()); } catch (NoSuchProviderException e) { RED.printThrowableAndExit(e); } catch (NoSuchAlgorithmException e) { RED.printThrowableAndExit(e); } GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. We followed the Java Security Guidelines for Mutability from point 1 to 5, which are the most common"); GREEN.printGenericLn("1.1 Guideline 6-1 / MUTABLE-1: Prefer immutability for value types"); GREEN.printGenericLn("1.2 Guideline 6-2 / MUTABLE-2: Create copies of mutable output values"); GREEN.printGenericLn("1.3 Guideline 6-3 / MUTABLE-3: Create safe copies of mutable and subclassable input values"); GREEN.printGenericLn("1.4 Guideline 6-4 / MUTABLE-4: Support copy functionality for a mutable class"); GREEN.printGenericLn("1.5 Guideline 6-5 / MUTABLE-5: Do not trust identity equality when overridable on input reference objects"); } private static void exercise6() { BRIGHT_CYAN.printGenericLn("--- 6. Bypassing overloading methods with different return types"); printRainbowLn("=="); GREEN.printGenericLn("Case: We want to go one of the \"La casa azul\" concerts."); GREEN.printGenericLn("Time is running out to book them, we don't know to which one we can go to."); GREEN.printGenericLn("So we decide to buy a bunch of them."); var ticket1 = new Ticket("La casa azul", "El Ejido, " + "ES", "ES23424ES23432", LocalDateTime.of(2019, 4, 27, 0, 0, 0)); var ticket2 = new Ticket("La casa azul", "El Ejido, " + "ES", 123232341342312L, LocalDateTime.of(2019, 4, 27, 0, 0, 0)); var ticket3 = new Ticket("La casa azul", "Seville, " + "ES", 193874567394857L, LocalDateTime.of(2019, 6, 29, 0, 0, 0)); MAGENTA.printGenericLn("Our first ticket is -> %s", ticket1); MAGENTA.printGenericLn("Our second ticket is -> %s", ticket2); MAGENTA.printGenericLn("Our third ticket is -> %s", ticket3); MAGENTA.printGenericLn("We have all the tickets for \"La casa azul\":\n%s", getTicketsStringNumbers("La casa azul")); MAGENTA.printGenericLn("Some of them are just numbers:\n%s", getTicketsLongNumbers("La casa azul")); BRIGHT_CYAN.printGenericLn("We realize that we can only go to the latest one!"); BRIGHT_CYAN.printGenericLn("Let's unregister te last two tickets"); var ticket1U = Ticket.unregisterTicket("ES23424ES23432"); var ticket2U = Ticket.unregisterTicket(123232341342312L); assert ticket1.equals(ticket1U); assert ticket2.equals(ticket2U); MAGENTA.printGenericLn("We've unregistered tickets\n%s\nand\n%s", ticket1U, ticket2U); final var allTicketsLaCasaAzul = getTicketsStringNumbers("La casa azul"); MAGENTA.printGenericLn("We finally should only have one ticket in our reservation:\n%s", allTicketsLaCasaAzul); final var ticketNumber = allTicketsLaCasaAzul.get(0); final var finalTicket = Ticket.getTicket(ticketNumber); MAGENTA.printGenericLn("Hurrah! We are going to %s to watch %s with ticket %s on the %s", finalTicket.getVenue(), finalTicket.getBandName(), finalTicket.getTicketNumber(), finalTicket.getLocalDateTime()); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. Methods can be overloaded if their parameters are different both in number and in types"); GREEN.printGenericLn("2. The compiler cannot tell two methods apart if they differ only in their return type"); GREEN.printGenericLn("3. This makes sense because if you call a method and do not assign its return value, you also would not be able to tell which method should be called would you?"); GREEN.printGenericLn("4. By the previous point we can also infer that parameter naming will not play a role in overloading since we don't call methods via their parameters name in Java... Not yet at least 😊"); } private static void exercise5() { BRIGHT_CYAN.printGenericLn("--- 5. Hiding and shadowing instance members"); printRainbowLn("=="); GREEN.printGenericLn("Case: \"Love of Lesbian\" was founded in 1997."); GREEN.printGenericLn("Alaska actually started in a band called \"Alaska y los Pegamoides\" in 1979."); GREEN.printGenericLn("\"Vetusta Morla\" is another band which started in 1998."); GREEN.printGenericLn("We are going to register them and understand the concept of shadouwing of instance members."); var band = new Band(List.of( "Santi Balmes", "Julián Saldarriaga", "Jordi Roig", "Joan Ramón Planell", "Oriol Bonet"), "Love of Lesbian"); var quintetBand = new QuintetBand( List.of( "Alaska", "Nacho Canut", "Ana Curra", "Eduardo Benavente", "Carlos Berlanga" ), "Alaska y los Pegamoides"); var genericBand = new GenericBand( 6, List.of( "Pucho", "David \"el Indio\"", "Álvaro B. Baglietto", "Jorge González", "Guillermo Galván", "Juanma Latorre" ), "Vetusta Morla"); MAGENTA.printGenericLn("This is band #1 -> %s", band); MAGENTA.printGenericLn("This is band #2 -> %s", quintetBand); MAGENTA.printGenericLn("This is band #3 -> %s", genericBand); GREEN.printGenericLn("We notice a few things that may sound odd."); GREEN.printGenericLn("1. Capacity is different for the subclasses of Band."); GREEN.printGenericLn("2. Capacity didn't limit the number of allowed members."); MAGENTA.printGenericLn("Band #1 has %d members", band.capacity); MAGENTA.printGenericLn("Band #2 has %d members", ((Band) quintetBand).capacity); MAGENTA.printGenericLn("Band #3 has %d members", ((Band) genericBand).capacity); GREEN.printGenericLn("Well, we know that for the last two bands this is not true. This is why we have our common getters."); MAGENTA.printGenericLn("Band #1 has %d members", band.getCapacity()); MAGENTA.printGenericLn("Band #2 has %d members", quintetBand.getCapacity()); MAGENTA.printGenericLn("Band #3 has %d members", genericBand.getCapacity()); GREEN.printGenericLn("This is true, but do methods get overriden?"); MAGENTA.printGenericLn("Band #1 has %d members", band.getCapacity()); MAGENTA.printGenericLn("Band #2 has %d members", ((Band) quintetBand).getCapacity()); MAGENTA.printGenericLn("Band #3 has %d members", ((Band) genericBand).getCapacity()); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. Shadowing involves covering another variable. There is no limitation on how this can be done"); GREEN.printGenericLn("2. The overshadowing member will also overshadow the scope"); GREEN.printGenericLn("3. Methods do get overridden regardless of @Override"); GREEN.printGenericLn("4. Capacity in an ArrayList only means that the initial capacity of the Array is fixed."); GREEN.printGenericLn("5. An ArrayList will change size automatically. Capacity is just used in performance and memory usage fine tuning."); } private static void exercise4() { BRIGHT_CYAN.printGenericLn("--- 4. The `java.desktop` module"); printRainbowLn("=="); GREEN.printGenericLn("Case: We want an app that lets us surf the web for short stories about Spanish music"); GREEN.printGenericLn("We'll make our first prototype using the \"Bandido\". A famous spanish album from \"Miguel Bosé\" containing famous anthem \"Amante bandido\""); GREEN.printGenericLn("We'll use this as the name of our module: amante.bandido"); GREEN.printGenericLn("Please find this module in the sources for mastery-4-3-swing and run it."); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. Java SWING libraries, although part of the JDK, they are not part of the java.base module."); GREEN.printGenericLn("2. Because they are not part of the java.base module, they have to be required."); GREEN.printGenericLn("3. To require them, you need to require the java.desktop module. Example:"); GREEN.printGenericLn("module amante.bandido {\n" + " requires java.desktop;\n" + " requires consolerizer;\n" + "}"); } private static void exercise3() { BRIGHT_CYAN.printGenericLn("--- 3. The body of `switch`"); printRainbowLn("=="); GREEN.printGenericLn("Case: \"¿A quién le importa?\" is a single from 1984 sung by Alaska and Dinamara, and edited by Nacho Canut and Carlos Berlanga."); GREEN.printGenericLn("There have been a lot of switches in styles up until present for this song. Several covers."); GREEN.printGenericLn("The reason why this song is so popular is because later in the 80's, it found great recognition in marginalized groups."); GREEN.printGenericLn("Most importantly the LGBT community from spanish speaking countries."); GREEN.printGenericLn("The song gained such momentum in that community, that it is now celebrated in the same way as \"I will survive\" from Gloria Gaynor is."); GREEN.printGenericLn("It mainly has to do with the rebelious theme of the song in which it is said:"); GREEN.printGenericLn("\"Who cares as to what to I do? Who cares as to what do I say? I am like this, I will always be like this and I will never change.\""); var i = 1984; MAGENTA.printGenericLn("In year %d version %s was released.", i, getYearMusic(i)); i = 2002; MAGENTA.printGenericLn("In year %d version %s was released.", i, getYearMusic(i)); i = 2011; MAGENTA.printGenericLn("In year %d version %s was released.", i, getYearMusic(i)); i = 2017; var m = 6; MAGENTA.printGenericLn("In year %d and month %d version %s was released.", i, m, getYearMonthMusic(i, m)); m = 12; MAGENTA.printGenericLn("In year %d and month %d version %s was released.", i, m, getYearMonthMusic(i, m)); i = 2020; m = 6; MAGENTA.printGenericLn("In year %d and month %d version %s was released.", i, m, getYearMonthMusic(i, m)); m = 7; MAGENTA.printGenericLn("In year %d and month %d version %s was released.", i, m, getYearMonthMusic(i, m)); GREEN.printGenericLn("Curiosities about switch and other accolades:"); BLUE.printGenericLn(" int k =0;\n" + " for (; k < 100; k++) ;\n" + " while(k < 100);\n" + " do {} while (k<100);\n" + " // Do while without a body is illegal\n" + " // do while (k<100);\n" + " // Switches without a body are illegal\n" + " // switch(i);"); int k = 0; for (; k < 100; k++) ; while (k < 100) ; do { } while (k < 100); // Do while without a body is illegal // do while (k<100); // Switches without a body are illegal // switch(i);k GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. Switches must have a body!"); GREEN.printGenericLn("2. Switches only accept int, short, long, byte, char, their boxed counterparts, Short, Long, Byte, Character, and String and enums as parameters."); GREEN.printGenericLn("3. do while is akin to a switch in the sense that it also cannot be done without a body."); GREEN.printGenericLn("4. for and while can be done without a body."); } /** * - [RUBÍ 2020, entrada completa a quien le importa](https://www.youtube.com/watch?v=aNMdaRbX_-k) * - [Rosa López · A quién le importa - 2020](https://www.youtube.com/watch?v=NxlfzjWX2Z4) * - [A QUIÉN LE IMPORTA - Grupal | Gala 7 | OT 2017](https://www.youtube.com/watch?v=hoH6OXQpmQY) * - [Himno World Pride Madrid 2017 - A quien le importa 2017](https://www.lasexta.com/especiales/world-pride-madrid/orgullo-lgtbi/a-quien-le-importa-asi-suena-el-himno-oficial-del-world-pride-madrid-2017_201706285953f2d20cf2a25c00ab7737.html) * - [Fangoria - A quien le importa 2011](https://www.youtube.com/watch?v=XX_hWpPnd3I) * - [Thalia - A Quien Le Importa - Video Oficial 2002](https://www.youtube.com/watch?v=s0MG5mdwweU) * - [Alaska y Dinarama A Quién Le Importa (1984)](https://www.youtube.com/watch?v=N2L7cRsUA0E) * * @param y Year of the song inception * @param m Month of the song inception * @return */ private static String getYearMonthMusic(int y, int m) { switch (y) { case 2002: return "Thalia - A Quien Le Importa - Video Oficial 2002 - https://www.youtube.com/watch?v=s0MG5mdwweU"; // Unreachable statement // break; case 2011: return "Fangoria - A quien le importa 2011 - https://www.youtube.com/watch?v=XX_hWpPnd3I"; case 2017: switch (m) { case 12: return "A QUIÉN LE IMPORTA - Grupal | Gala 7 | OT 2017 - https://www.youtube.com/watch?v=hoH6OXQpmQY"; case 6: default: return "Himno World Pride Madrid 2017 - A quien le importa 2017\nhttps://www.lasexta.com/especiales/world-pride-madrid/orgullo-lgtbi/a-quien-le-importa-asi-suena-el-himno-oficial-del-world-pride-madrid-2017_201706285953f2d20cf2a25c00ab7737.html"; } case 2020: switch (m) { case 6: return "Rosa López · A quién le importa - 2020 - https://www.youtube.com/watch?v=NxlfzjWX2Z4"; case 7: default: return "Camila Sodi - RUBÍ 2020, entrada completa a quien le importa - https://www.youtube.com/watch?v=aNMdaRbX_-k"; } case 1984: // Unreachable statement // break; default: return "Alaska y Dinarama A Quién Le Importa (1984) - https://www.youtube.com/watch?v=N2L7cRsUA0E"; } } private static String getYearMusic(int y) { return getYearMonthMusic(y, 0); } private static void exercise2() { BRIGHT_CYAN.printGenericLn("--- 2. Different ways to use `this`"); printRainbowLn("=="); GREEN.printGenericLn("Case: In 1981, Hispavox edited and published single \"Juntos\" by Paloma San Basilio"); GREEN.printGenericLn("Since then, this song has been sung and remixed by different artists."); GREEN.printGenericLn("We will register this event and see how can we use `this`."); var company = new Company("Hispavox"); var music = company.new Music("Juntos", "Paloma San Basilio", LocalDateTime.of(1981, 1, 1, 0, 0, 0)); // 'org.jesperancinha.java11.mastery4dot2.record.Company' is not an enclosing class // Company.this BLUE.printGenericLn("The only reason why %s works is because %s is an enclosing class of %s.", "Company.this.company", "Company", "Music"); MAGENTA.printGenericLn(music.getTheMusic()); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. `this` is more commonly used within a class to refer to the instance members"); GREEN.printGenericLn("2. It cannot be used for static members"); GREEN.printGenericLn("3. Although less common, we can use this to refer to the instance members of an enclosing class"); GREEN.printGenericLn("4. Even though it looks like a static accessor, it is an instance member accessor"); } private static void exercise1() { BRIGHT_CYAN.printGenericLn("--- 1. Primitives Revised"); printRainbowLn("=="); GREEN.printGenericLn("Case: Music group Fangoria was created in 1989."); GREEN.printGenericLn("The name of the group was inspired by the love the group members, Alaska and Nacho Canut have for the magazine of the same name"); GREEN.printGenericLn("We'll have a look at numbers related to that magazine and explore java primitive types with it"); printRainbowLn("###"); final byte issnLeft = 0164; BRIGHT_CYAN.printGenericLn("Byte - one byte - 2^8"); BRIGHT_CYAN.printGenericLn("Range from %s to %s", Byte.MIN_VALUE, Byte.MAX_VALUE); MAGENTA.printGenericLn("If we look at the left side of the issn, we a small number."); MAGENTA.printGenericLn("164, is however, too big for the maximum allowed value for a byte."); MAGENTA.printGenericLn("In this case, we can use its octed representation, which in turn is a smaller number than a 164."); MAGENTA.printGenericLn("Octet radix numbers are represented with a 0 as a prefix."); MAGENTA.printGenericLn("This is our number as we would read it in decimal: %s", Integer.toString(issnLeft, 10)); MAGENTA.printGenericLn("And this is what we want: %s", Integer.toString(issnLeft, 8)); BRIGHT_MAGENTA.printGenericLn("Note that we are able to pass a byte in the toString of Integer, just because the range of Integer covers the byte range"); BRIGHT_MAGENTA.printGenericLn("Also, bear in mind that primitive numbers without decimals are interpreted as integers. except for byte and short"); printRainbowLn("###"); short lossesPerIssue = 20000; BRIGHT_CYAN.printGenericLn("Short two bytes - 2^16"); BRIGHT_CYAN.printGenericLn("Range from %s to %s", Short.MIN_VALUE, Short.MAX_VALUE); MAGENTA.printGenericLn("In early beginnings, Fangoria magazine wasn't selling that much."); MAGENTA.printGenericLn("The losses amounted to USD$20000 per issue"); MAGENTA.printGenericLn("We cannot put this number in a byte. It just falls out of range"); MAGENTA.printGenericLn("If we use a short though, we can safely accomodate it"); MAGENTA.printGenericLn("This is our number as we would read it in decimal: %s", Integer.toString(lossesPerIssue, 10)); MAGENTA.printGenericLn("Just for fun, we can look at its octal representation: %s", Integer.toString(lossesPerIssue, 8)); MAGENTA.printGenericLn("Which if we use that in the code we get: %s", 047040); BRIGHT_MAGENTA.printGenericLn("Note that shor, just as byte, is often overlooked because it's just not common enough"); BRIGHT_MAGENTA.printGenericLn("However, the benefits of using primitives like these two for small numbers can represent an advantage"); printRainbowLn("###"); int oclc = 4618144; BRIGHT_CYAN.printGenericLn("Integer four bytes - 2^32"); BRIGHT_CYAN.printGenericLn("Range from %s to %s", Integer.MIN_VALUE, Integer.MAX_VALUE); MAGENTA.printGenericLn("As reported by wikipedia, the OCLC is the Ohio College Library Center number."); MAGENTA.printGenericLn("We want to register this reference number for the publishing of issue 7 of Fangoria Magazine."); MAGENTA.printGenericLn("For this, we cannot use Short anymore. It falls out of the range needed."); MAGENTA.printGenericLn("We'll try with Integer."); MAGENTA.printGenericLn("This is our number as we would read it in decimal: %s", Integer.toString(oclc, 10)); MAGENTA.printGenericLn("Just for fun, we can look at its octal representation: %s", Integer.toString(oclc, 8)); MAGENTA.printGenericLn("Which if we use that in the code we get: %s", 021473640); BRIGHT_MAGENTA.printGenericLn("Important to note is again, how integer is always the type pointed out by the compiler"); BRIGHT_MAGENTA.printGenericLn("Especially if you look the octals, they are interpreted as int."); BRIGHT_MAGENTA.printGenericLn("They only get converted when they match the range."); printRainbowLn("###"); long firstPublicationMs = 283_996_800_000L; BRIGHT_CYAN.printGenericLn("Long eight bytes - 2^64"); BRIGHT_CYAN.printGenericLn("Range from %s to %s", Long.MIN_VALUE, Long.MAX_VALUE); MAGENTA.printGenericLn("The first publication of Fangoria happened on a specific date."); MAGENTA.printGenericLn("We found the number in milliseconds."); MAGENTA.printGenericLn("If we convert that to some epoch representation, we then convert from %d to %s", firstPublicationMs, LocalDateTime.ofInstant(Instant.ofEpochMilli(firstPublicationMs), ZoneId.systemDefault())); MAGENTA.printGenericLn("This is our number as we would read it in decimal: %s", Long.toString(firstPublicationMs, 10)); MAGENTA.printGenericLn("Just for fun, we can look at its octal representation: %s", Long.toString(firstPublicationMs, 8)); MAGENTA.printGenericLn("Which if we use that in the code we get: %s", 04103741642000L); BRIGHT_MAGENTA.printGenericLn("You probably noticed that we are using L to specify that it is a long."); BRIGHT_MAGENTA.printGenericLn("The compiler needs to know what do we actually mean if the number falls out of the integer range."); BRIGHT_MAGENTA.printGenericLn("If it falls out of the range of Integer and we want it to be long, we specify that with an appended L or l."); printRainbowLn("###"); float firstPublicationMs2 = 283_996_800_000L; BRIGHT_CYAN.printGenericLn("Float 4 bytes - 2^32"); BRIGHT_CYAN.printGenericLn("Range from %s to %s with a min normal %s", Float.MIN_VALUE, Float.MAX_VALUE, Float.MIN_NORMAL); BRIGHT_CYAN.printGenericLn("It stores up 6 to 7 significant numbers"); MAGENTA.printGenericLn("Before continuing in this section you probably noticed a strange conversion."); MAGENTA.printGenericLn("A long to a float? Well that can happen simply because a long fits in a float range."); MAGENTA.printGenericLn("And although float occupies less amount of bytes (4) than long (8), its implementation allows this to happen."); MAGENTA.printGenericLn("This means that even with a float, the rule that it fits, is accepted is still valid."); MAGENTA.printGenericLn("The only difference is that we need to specify L if its bigger than an int."); MAGENTA.printGenericLn("If we convert that to some epoch representation from a float, we then convert from %f to %s", firstPublicationMs2, LocalDateTime.ofInstant(Instant.ofEpochMilli((long) firstPublicationMs2), ZoneId.systemDefault())); BRIGHT_MAGENTA.printGenericLn("Notice that we had to upcast it to long. This is because the compiler does not understand that we are converting to a type with a lower range. Although the number fits, type float does not fit in the long range."); float parallelUniversePublications1 = (3_000_000f * 12 * 30 * 10); MAGENTA.printGenericLn("Let's imagine that 10 universes are working together."); MAGENTA.printGenericLn("The same thing happens in all of those 10 universes to our magazine."); MAGENTA.printGenericLn("The website gets 3 million visits per month"); MAGENTA.printGenericLn("And we are calculating what would have happened if during the course of 30 years of existence, the numbers would have kept stable"); MAGENTA.printGenericLn("In the end we get all of these hits: %s", parallelUniversePublications1); BRIGHT_MAGENTA.printGenericLn("Did you notice the f? f, means float. Without the f, the calculation would result in a numeric overflow warning from the compiler"); BRIGHT_MAGENTA.printGenericLn("Since one of the elements is now a float, the compiler will check if the result fits within the float range."); BRIGHT_MAGENTA.printGenericLn("During runtime, well get a float as a result."); printRainbowLn("###"); double parallelUniversePublications2 = (3_000_000d * 12 * 30 * 1e+200); double parallelUniversePublications3 = (3_000_000d * 12 * 30 * 1e+300); BRIGHT_CYAN.printGenericLn("Float 4 bytes - 2^32"); BRIGHT_CYAN.printGenericLn("Range from %s to %s with a min normal %s", Double.MIN_VALUE, Double.MAX_VALUE, Double.MIN_NORMAL); MAGENTA.printGenericLn("In the same way with Float, we can make a calculation if we have %s universes", 1e+200); BRIGHT_MAGENTA.printGenericLn("Notice the d. Now we specify that the number is a double."); MAGENTA.printGenericLn("If the number is too big, we'll get a different lind of mathematical notation."); MAGENTA.printGenericLn("If we try with %s universes", parallelUniversePublications3); MAGENTA.printGenericLn("A very high number is also considered a number, but Double specifies it as %s", parallelUniversePublications3); BRIGHT_CYAN.printGenericLn("Reminder: double values are 64 bit floating point numbers with a precision of 15 to 16 significant number digits."); BRIGHT_CYAN.printGenericLn("Doubles range from\n%s to %s in normal values", Double.MIN_NORMAL, Double.MAX_VALUE); BRIGHT_CYAN.printGenericLn("Doubles can also be: %s and be %f or %f", Double.MIN_VALUE, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY); BRIGHT_CYAN.printGenericLn(parallelUniversePublications1); BRIGHT_CYAN.printGenericLn(parallelUniversePublications2); BRIGHT_CYAN.printGenericLn(parallelUniversePublications3); printRainbowLn("###"); GREEN.printGenericLn("Curiosities about primitive types:"); double maxTest = 3.40282353482789473289473289477899659000892042934820984928423804e+38; float maxTest2 = 3.40282353482789473289473289477899659000892042934820984928423804e+38f; float maxTest3 = 3.4028235e+38f; double maxTest4 = 3.4028235e+38; double maxTest5 = 3.4028235111112222233333444444555555666666777788889999111122222e+38; double maxTest6 = 1.79769313486231572234324324324e+308; MAGENTA.printGenericLn("double maxTest = 3.40282353482789473289473289477899659000892042934820984928423804e+38:"); BRIGHT_MAGENTA.printGenericLn("%f", maxTest); MAGENTA.printGenericLn("float maxTest2 = 3.40282353482789473289473289477899659000892042934820984928423804e+38f:"); BRIGHT_MAGENTA.printGenericLn("%f", maxTest2); MAGENTA.printGenericLn("float maxTest3 = 3.40282353482789473289473289477899659000892042934820984928423804e+38f:"); BRIGHT_MAGENTA.printGenericLn("%f", maxTest3); MAGENTA.printGenericLn("double maxTest4 = 3.4028235e+38:"); BRIGHT_MAGENTA.printGenericLn("%f", maxTest4); MAGENTA.printGenericLn("double maxTest5 = 3.4028235111112222233333444444555555666666777788889999111122222e+38:"); BRIGHT_MAGENTA.printGenericLn("%f", maxTest5); MAGENTA.printGenericLn("double maxTest5 = 3.4028235111112222233333444444555555666666777788889999111122222e+38"); BRIGHT_MAGENTA.printGenericLn("%s", Double.toString(maxTest5)); MAGENTA.printGenericLn("Float.MAX_VALUE:"); BRIGHT_MAGENTA.printGenericLn("%f", Float.MAX_VALUE); MAGENTA.printGenericLn("Double.MAX_VALUE:"); BRIGHT_MAGENTA.printGenericLn("%f", Double.MAX_VALUE); MAGENTA.printGenericLn("double maxTest6 = 1.79769313486231572234324324324e+308;"); BRIGHT_MAGENTA.printGenericLn("%f", maxTest6); MAGENTA.printGenericLn("Double.toString(Double.MAX_VALUE):"); BRIGHT_MAGENTA.printGenericLn("%s", Double.toString(Double.MAX_VALUE)); GREEN.printGenericLn("Take-away"); GREEN.printGenericLn("1. Primitive type conversion rules and ranges are not simple"); GREEN.printGenericLn("2. A number without decimal is considered an integer and automatically converted to a lower range if it fits it, but only on instantiation assignment."); GREEN.printGenericLn("3. A value with a coma is considered a double. An f will specify that it is a float"); GREEN.printGenericLn("4. d is needed when making calculations that result in very large numbers"); GREEN.printGenericLn("5. d is also needed if our number without decimals results to be higher than long"); GREEN.printGenericLn("6. f is also needed if our number without decimals results to be higher than long"); GREEN.printGenericLn("7. f can take in any integer or long"); GREEN.printGenericLn("8. d can take in any integer or long or float"); GREEN.printGenericLn("9. Octals may not have digits higher than 8 otherwise the 0 before the number rule won't work!"); double a; long b = 123; a = b; float c; c = b; long d = 123412341234L; c = 1.2f; a = c; a = 4.5; // Overflows a = 1233112213L * 12312232223L * 2; // Correct a = 1233112213d * 12312232223L * 2; } private static void moduleEnd() { printUnicornsLn(100); GREEN.printGenericLn("Hope you enjoyed this mastery into Java 11 with some Spanish Indie/Pop flavor to it."); GREEN.printGenericLn("Please keep coming back as I'll be creating more mastery modules."); GREEN.printGenericLn("Thank you!"); printUnicornsLn(100); } }
63.400508
270
0.662295
b6eac9313459b10583ec1c7dbd36ec454982a184
683
package net.okair.springcloud.sysadmin.organization.entity.form; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import net.okair.springcloud.commom.web.entity.form.BaseForm; import net.okair.springcloud.sysadmin.organization.entity.po.Role; import java.util.Set; @ApiModel @Data public class RoleUpdateForm extends BaseForm<Role> { @ApiModelProperty(value = "角色编码") private String code; @ApiModelProperty(value = "角色名称") private String name; @ApiModelProperty(value = "角色描述") private String description; @ApiModelProperty(value = "角色拥有的资源id列表") private Set<String> resourceIds; }
22.766667
66
0.764275
08e88c2fcccbaca9adee151a5b96e80ed2013d2c
19,472
package org.hisp.dhis.reports.ouwiseprogress.action; import static org.hisp.dhis.system.util.ConversionUtils.getIdentifiers; import static org.hisp.dhis.system.util.TextUtils.getCommaDelimitedString; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import jxl.Workbook; import jxl.format.Alignment; import jxl.format.Border; import jxl.format.BorderLineStyle; import jxl.format.Colour; import jxl.format.VerticalAlignment; import jxl.write.Formula; import jxl.write.Label; import jxl.write.Number; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import org.hisp.dhis.common.comparator.IdentifiableObjectNameComparator; import org.hisp.dhis.config.Configuration_IN; import org.hisp.dhis.i18n.I18nFormat; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitService; import org.hisp.dhis.period.Period; import org.hisp.dhis.period.PeriodService; import org.hisp.dhis.period.PeriodType; import org.hisp.dhis.reports.ReportService; import org.hisp.dhis.reports.Report_in; import org.hisp.dhis.reports.Report_inDesign; import org.hisp.dhis.system.util.MathUtils; import com.opensymphony.xwork2.Action; /** * @author Mithilesh Kumar Thakur */ public class GenerateFacilityBasedOuWiseProgressReportResultAction implements Action { private final String GENERATEAGGDATA = "generateaggdata"; private final String USEEXISTINGAGGDATA = "useexistingaggdata"; private final String USECAPTUREDDATA = "usecaptureddata"; // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- private ReportService reportService; public void setReportService( ReportService reportService ) { this.reportService = reportService; } private PeriodService periodService; public void setPeriodService( PeriodService periodService ) { this.periodService = periodService; } private OrganisationUnitService organisationUnitService; public void setOrganisationUnitService( OrganisationUnitService organisationUnitService ) { this.organisationUnitService = organisationUnitService; } private I18nFormat format; public void setFormat( I18nFormat format ) { this.format = format; } // ------------------------------------------------------------------------- // Properties // ------------------------------------------------------------------------- private InputStream inputStream; public InputStream getInputStream() { return inputStream; } private String fileName; public String getFileName() { return fileName; } private String reportList; public void setReportList( String reportList ) { this.reportList = reportList; } private int ouIDTB; public void setOuIDTB( int ouIDTB ) { this.ouIDTB = ouIDTB; } private int availablePeriods; public void setAvailablePeriods( int availablePeriods ) { this.availablePeriods = availablePeriods; } private int availablePeriodsto; public void setAvailablePeriodsto( int availablePeriodsto ) { this.availablePeriodsto = availablePeriodsto; } private String aggData; public void setAggData( String aggData ) { this.aggData = aggData; } private Period selectedPeriod; private Period selectedEndPeriod; private SimpleDateFormat simpleDateFormat; private Date sDate; private Date eDate; private String raFolderName; private List<Period> periodList = new ArrayList<Period>(); private SimpleDateFormat yearFormat; private SimpleDateFormat dateTimeFormat; private OrganisationUnit selectedOrgUnit; private List<OrganisationUnit> orgUnitList; private String reportFileNameTB; private String reportModelTB; private PeriodType selPeriodType; // ------------------------------------------------------------------------- // Action implementation // ------------------------------------------------------------------------- public String execute() throws Exception { // Initialization raFolderName = reportService.getRAFolderName(); simpleDateFormat = new SimpleDateFormat( "MMM-yy" ); yearFormat = new SimpleDateFormat( "yyyy" ); SimpleDateFormat dayFormat = new SimpleDateFormat( "yyyy-MM-dd" ); dateTimeFormat = new SimpleDateFormat( "EEEE, dd MMMM yyyy HH:mm:ss zzzz" ); // Getting Report Details String deCodesXMLFileName = ""; Report_in selReportObj = reportService.getReport( Integer.parseInt( reportList ) ); deCodesXMLFileName = selReportObj.getXmlTemplateName(); reportModelTB = selReportObj.getModel(); reportFileNameTB = selReportObj.getExcelTemplateName(); // OrgUnit Related Info selectedOrgUnit = new OrganisationUnit(); selectedOrgUnit = organisationUnitService.getOrganisationUnit( ouIDTB ); //int selectedOrgUnitLevel = organisationUnitService.getLevelOfOrganisationUnit( ouIDTB ); System.out.println( selectedOrgUnit.getName()+ " : " + selReportObj.getName()+" : Report Generation Start Time is : " + new Date() ); // OrgUnit Related Information if ( reportModelTB.equalsIgnoreCase( "PROGRESSIVE-ORGUNIT" ) ) { orgUnitList = new ArrayList<OrganisationUnit>( selectedOrgUnit.getChildren() ); Collections.sort( orgUnitList, new IdentifiableObjectNameComparator() ); //Hardcoded to level 2 to make report fast for state level /* if( selectedOrgUnitLevel != 2 ) { orgUnitList.add( selectedOrgUnit ); } */ } // Period Info selectedPeriod = periodService.getPeriod( availablePeriods ); selectedEndPeriod = periodService.getPeriod( availablePeriodsto ); sDate = format.parseDate( String.valueOf( selectedPeriod.getStartDate() ) ); eDate = format.parseDate( String.valueOf( selectedEndPeriod.getEndDate() ) ); selPeriodType = selReportObj.getPeriodType(); periodList = new ArrayList<Period>( periodService.getPeriodsBetweenDates( selPeriodType, sDate, eDate ) ); //List<Period> periodList = new ArrayList<Period>( periodService.getIntersectingPeriods( sDate, eDate ) ); Collection<Integer> periodIds = new ArrayList<Integer>( getIdentifiers(Period.class, periodList ) ); String periodIdsByComma = getCommaDelimitedString( periodIds ); // Getting DataValues List<Report_inDesign> reportDesignList = reportService.getReportDesign( deCodesXMLFileName ); String dataElmentIdsByComma = reportService.getDataelementIds( reportDesignList ); String inputTemplatePath = System.getenv( "DHIS2_HOME" ) + File.separator + raFolderName + File.separator + "template" + File.separator + reportFileNameTB; String outputReportPath = System.getenv( "DHIS2_HOME" ) + File.separator + Configuration_IN.DEFAULT_TEMPFOLDER; File newdir = new File( outputReportPath ); if( !newdir.exists() ) { newdir.mkdirs(); } outputReportPath += File.separator + UUID.randomUUID().toString() + ".xls"; Workbook templateWorkbook = Workbook.getWorkbook( new File( inputTemplatePath ) ); WritableWorkbook outputReportWorkbook = Workbook.createWorkbook( new File( outputReportPath ), templateWorkbook ); WritableCellFormat wCellformat = new WritableCellFormat(); wCellformat.setBorder( Border.ALL, BorderLineStyle.THIN ); wCellformat.setAlignment( Alignment.CENTRE ); wCellformat.setVerticalAlignment( VerticalAlignment.CENTRE ); wCellformat.setWrap( true ); int slno = 1; int orgUnitCount = 0; Iterator<OrganisationUnit> organisationUnitIterator = orgUnitList.iterator(); while ( organisationUnitIterator.hasNext() ) { OrganisationUnit currentOrgUnit = (OrganisationUnit) organisationUnitIterator.next(); List<OrganisationUnit> childOrgUnitTree = new ArrayList<OrganisationUnit>( organisationUnitService.getOrganisationUnitWithChildren( currentOrgUnit.getId() ) ); List<Integer> childOrgUnitTreeIds = new ArrayList<Integer>( getIdentifiers( OrganisationUnit.class, childOrgUnitTree ) ); String childOrgUnitsByComma = getCommaDelimitedString( childOrgUnitTreeIds ); Map<String, String> aggDeMap = new HashMap<String, String>(); if( aggData.equalsIgnoreCase( USEEXISTINGAGGDATA ) ) { aggDeMap.putAll( reportService.getResultDataValueFromAggregateTable( currentOrgUnit.getId(), dataElmentIdsByComma, periodIdsByComma ) ); } else if( aggData.equalsIgnoreCase( GENERATEAGGDATA ) ) { aggDeMap.putAll( reportService.getAggDataFromDataValueTable( childOrgUnitsByComma, dataElmentIdsByComma, periodIdsByComma ) ); } else if( aggData.equalsIgnoreCase( USECAPTUREDDATA ) ) { aggDeMap.putAll( reportService.getAggDataFromDataValueTable( ""+currentOrgUnit.getId(), dataElmentIdsByComma, periodIdsByComma ) ); } //int count1 = 0; Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator(); while ( reportDesignIterator.hasNext() ) { Report_inDesign report_inDesign = (Report_inDesign) reportDesignIterator.next(); String sType = report_inDesign.getStype(); String deCodeString = report_inDesign.getExpression(); String tempStr = ""; if ( deCodeString.equalsIgnoreCase( "FACILITY" ) ) { tempStr = selectedOrgUnit.getName(); } else if( deCodeString.equalsIgnoreCase( "PROGRESSIVE-ORGUNIT" ) ) { tempStr = currentOrgUnit.getName(); } else if( deCodeString.equalsIgnoreCase( "FACILITYP" ) ) { tempStr = selectedOrgUnit.getParent().getName(); } else if( deCodeString.equalsIgnoreCase( "FACILITYPP" ) ) { tempStr = selectedOrgUnit.getParent().getParent().getName(); } else if ( deCodeString.equalsIgnoreCase( "DATE-FROM" ) ) { tempStr = dayFormat.format( sDate ); } else if ( deCodeString.equalsIgnoreCase( "DATE-TO" ) ) { tempStr = dayFormat.format( eDate ); } else if ( deCodeString.equalsIgnoreCase( "MONTH-FROM" ) ) { tempStr = simpleDateFormat.format( sDate ); } else if ( deCodeString.equalsIgnoreCase( "MONTH-TO" ) ) { tempStr = simpleDateFormat.format( eDate ); } else if ( deCodeString.equalsIgnoreCase( "CURRENTDATETIME" ) ) { tempStr = dateTimeFormat.format( new Date() ); } else if ( deCodeString.equalsIgnoreCase( "MONTH-YEAR" ) ) { tempStr = yearFormat.format( sDate ); } else if( deCodeString.equalsIgnoreCase( "SLNo" ) ) { tempStr = "" + slno; } else if ( deCodeString.equalsIgnoreCase( "NA" ) ) { tempStr = " "; } else { if ( sType.equalsIgnoreCase( "dataelement" ) ) { if( aggData.equalsIgnoreCase( USECAPTUREDDATA ) ) { tempStr = getAggVal( deCodeString, aggDeMap ); } else if( aggData.equalsIgnoreCase( GENERATEAGGDATA ) ) { tempStr = getAggVal( deCodeString, aggDeMap ); } else if( aggData.equalsIgnoreCase( USEEXISTINGAGGDATA ) ) { tempStr = getAggVal( deCodeString, aggDeMap ); } //System.out.println( " deCodeString " + deCodeString + " -tempSt " + tempStr + "-" + currentOrgUnit.getName() ); } else if ( sType.equalsIgnoreCase( "formula" ) ) { tempStr = deCodeString; } } int tempRowNo = report_inDesign.getRowno(); int tempColNo = report_inDesign.getColno(); int sheetNo = report_inDesign.getSheetno(); WritableSheet sheet0 = outputReportWorkbook.getSheet( sheetNo ); if ( reportModelTB.equalsIgnoreCase( "PROGRESSIVE-ORGUNIT" ) ) { if( deCodeString.equalsIgnoreCase( "FACILITY" ) || deCodeString.equalsIgnoreCase( "FACILITYP" ) || deCodeString.equalsIgnoreCase( "FACILITYPP" ) || deCodeString.equalsIgnoreCase( "DATE-FROM" ) || deCodeString.equalsIgnoreCase( "DATE-TO" ) || deCodeString.equalsIgnoreCase( "MONTH-FROM" ) || deCodeString.equalsIgnoreCase( "MONTH-TO" ) || deCodeString.equalsIgnoreCase( "CURRENTDATETIME" ) || deCodeString.equalsIgnoreCase( "MONTH-YEAR" ) ) { } else { tempRowNo += orgUnitCount; } try { if( sType.equalsIgnoreCase( "formula" ) ) { tempStr = tempStr.replace( "?", "" + ( tempRowNo + 1 ) ); sheet0.addCell( new Formula( tempColNo, tempRowNo, tempStr, wCellformat ) ); } else { sheet0.addCell( new Number( tempColNo, tempRowNo, Double.parseDouble( tempStr ), wCellformat ) ); } } catch( Exception e ) { sheet0.addCell( new Label( tempColNo, tempRowNo, tempStr, getCellFormat2() ) ); } //System.out.println( "SType : " + sType + " OU Name : " + currentOrgUnit.getName() + " DECode : " + deCodeString + " TempStr : " + tempStr + " -- Row No " + tempRowNo + " -- Col No " + tempColNo ); } //count1++; }// reportDesignIterator while loop end slno++; orgUnitCount++; }// organisationUnitIterator while loop end outputReportWorkbook.write(); outputReportWorkbook.close(); fileName = reportFileNameTB.replace( ".xls", "" ); fileName += "_" + selectedOrgUnit.getShortName() + "_"; fileName += "_" + simpleDateFormat.format( sDate ) + ".xls"; File outputReportFile = new File( outputReportPath ); inputStream = new BufferedInputStream( new FileInputStream( outputReportFile ) ); System.out.println( selectedOrgUnit.getName()+ " : " + selReportObj.getName() +" Report Generation End Time is : " + new Date() ); outputReportFile.deleteOnExit(); return SUCCESS; } private String getAggVal( String expression, Map<String, String> aggDeMap ) { try { Pattern pattern = Pattern.compile( "(\\[\\d+\\.\\d+\\])" ); Matcher matcher = pattern.matcher( expression ); StringBuffer buffer = new StringBuffer(); String resultValue = ""; while ( matcher.find() ) { String replaceString = matcher.group(); replaceString = replaceString.replaceAll( "[\\[\\]]", "" ); replaceString = aggDeMap.get( replaceString ); if( replaceString == null ) { replaceString = "0"; } matcher.appendReplacement( buffer, replaceString ); resultValue = replaceString; } matcher.appendTail( buffer ); double d = 0.0; try { d = MathUtils.calculateExpression( buffer.toString() ); } catch ( Exception e ) { d = 0.0; resultValue = ""; } resultValue = "" + (double) d; return resultValue; } catch ( NumberFormatException ex ) { throw new RuntimeException( "Illegal DataElement id", ex ); } } // for format the cell public WritableCellFormat getCellFormat1() throws Exception { WritableFont arialBold = new WritableFont( WritableFont.ARIAL, 10, WritableFont.BOLD ); WritableCellFormat wCellformat = new WritableCellFormat( arialBold ); wCellformat.setBorder( Border.ALL, BorderLineStyle.THIN ); wCellformat.setAlignment( Alignment.CENTRE ); wCellformat.setBackground( Colour.GRAY_25 ); wCellformat.setVerticalAlignment( VerticalAlignment.CENTRE ); wCellformat.setWrap( true ); return wCellformat; } // for format the cell public WritableCellFormat getCellFormat2() throws Exception { WritableCellFormat wCellformat = new WritableCellFormat(); wCellformat.setBorder( Border.ALL, BorderLineStyle.THIN ); wCellformat.setAlignment( Alignment.LEFT ); wCellformat.setVerticalAlignment( VerticalAlignment.CENTRE ); wCellformat.setWrap( true ); return wCellformat; } }
37.089524
223
0.566917