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
dd227ceac2abc627f9eb10b22564b445ac7fcd9d
1,460
package cn.cookie.framework.context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ContextUtils implements ApplicationContextAware{ private static ApplicationContext applicationContext; private static final Logger logger = LoggerFactory.getLogger(ContextUtils.class); public static ApplicationContext getApplicationContext() { synchronized (ContextUtils.class) { while (applicationContext == null) { try { ContextUtils.class.wait(60000); if (applicationContext == null) { logger.warn("Have been waiting for ApplicationContext to be set for 1 minute", new Exception()); } } catch (InterruptedException ex) { logger.debug("getApplicationContext, wait interrupted"); } } return applicationContext; } } public static Object getBean(Class<?> beanType) { return getApplicationContext().getBean(beanType); } public static Object getBean(String name) { return getApplicationContext().getBean(name); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{ synchronized (ContextUtils.class) { ContextUtils.applicationContext = applicationContext; ContextUtils.class.notifyAll(); } } }
29.2
102
0.776712
bfdd9ea773020cc54390d8eaba505b0056c4c22b
683
package app.retake.domain.dto; import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.List; @XmlRootElement(name = "procedures") @XmlAccessorType(XmlAccessType.FIELD) public class ProcedureWrapperXMLExportDTO { @XmlElementWrapper(name = "procedures") @XmlElement(name = "procedure") private List<ProcedureXMLExportDTO> procedures; public ProcedureWrapperXMLExportDTO() { this.procedures = new ArrayList<>(); } public List<ProcedureXMLExportDTO> getProcedures() { return this.procedures; } public void setProcedures(List<ProcedureXMLExportDTO> procedures) { this.procedures = procedures; } }
25.296296
71
0.726208
3f4badd361fff790ffac9a94365b8a3ec1704406
3,150
/** * Copyright 2014 Lockheed Martin Corporation * * 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 streamflow.model.storm; import java.io.Serializable; public class GlobalStreamId implements Serializable { private String componentId; private String streamId; public GlobalStreamId() { } public GlobalStreamId(String componentId, String streamId) { this.componentId = componentId; this.streamId = streamId; } public String getComponentId() { return componentId; } public void setComponentId(String componentId) { this.componentId = componentId; } public String getStreamId() { return streamId; } public void setStreamId(String streamId) { this.streamId = streamId; } @Override public int hashCode() { int hash = 7; hash = 73 * hash + (this.componentId != null ? this.componentId.hashCode() : 0); hash = 73 * hash + (this.streamId != null ? this.streamId.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final GlobalStreamId other = (GlobalStreamId) obj; if ((this.componentId == null) ? (other.componentId != null) : !this.componentId.equals(other.componentId)) { return false; } if ((this.streamId == null) ? (other.streamId != null) : !this.streamId.equals(other.streamId)) { return false; } return true; } public int compareTo(GlobalStreamId other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int comparison = Boolean.valueOf(this.componentId != null).compareTo(other.componentId != null); if (comparison != 0) { return comparison; } if (this.componentId != null) { comparison = this.componentId.compareTo(other.componentId); if (comparison != 0) { return comparison; } } comparison = Boolean.valueOf(this.streamId != null).compareTo(other.streamId != null); if (comparison != 0) { return comparison; } if (this.streamId != null) { comparison = this.streamId.compareTo(other.streamId); if (comparison != 0) { return comparison; } } return 0; } }
29.166667
104
0.595873
83a7cd211692ca2e7ddb3ee2ffc159adba74fd64
12,994
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.tracing.opentelemetry; import com.azure.core.tracing.opentelemetry.implementation.AmqpPropagationFormatUtil; import com.azure.core.tracing.opentelemetry.implementation.AmqpTraceUtil; import com.azure.core.tracing.opentelemetry.implementation.HttpTraceUtil; import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.tracing.ProcessKind; import io.opentelemetry.OpenTelemetry; import io.opentelemetry.trace.AttributeValue; import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span.Builder; import io.opentelemetry.trace.SpanContext; import io.opentelemetry.trace.Tracer; import java.util.Objects; import java.util.Optional; /** * Basic tracing implementation class for use with REST and AMQP Service Clients to create {@link Span} and in-process * context propagation. Singleton OpenTelemetry tracer capable of starting and exporting spans. * * <p> * This helper class supports W3C distributed tracing protocol and injects SpanContext into the outgoing HTTP and AMQP * requests. */ public class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private static final Tracer TRACER = OpenTelemetry.getTracerFactory().get("Azure-OpenTelemetry"); // standard attributes with AMQP request static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String COMPONENT = "component"; static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Builder spanBuilder = getSpanBuilder(spanName, context); Span span = spanBuilder.startSpan(); if (span.isRecording()) { // TODO (savaity): replace with the AZ_TRACING_NAMESPACE_KEY String tracingNamespace = getOrDefault(context, "az.tracing.namespace", null, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, AttributeValue.stringAttributeValue(tracingNamespace)); } } return context.addData(PARENT_SPAN_KEY, span); } /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); Span span; Builder spanBuilder; switch (processKind) { case SEND: // use previously created span builder from the LINK process. spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, Builder.class); if (spanBuilder == null) { return Context.NONE; } span = spanBuilder.setSpanKind(Span.Kind.CLIENT).startSpan(); if (span.isRecording()) { // If span is sampled in, add additional request attributes addSpanRequestAttributes(span, context, spanName); } return context.addData(PARENT_SPAN_KEY, span); case MESSAGE: spanBuilder = getSpanBuilder(spanName, context); span = spanBuilder.setSpanKind(Span.Kind.PRODUCER).startSpan(); // Add diagnostic Id and trace-headers to Context context = setContextData(span); return context.addData(PARENT_SPAN_KEY, span); case PROCESS: return startScopedSpan(spanName, context); default: return Context.NONE; } } /** * {@inheritDoc} */ @Override public void end(int responseCode, Throwable throwable, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); final Span span = getOrDefault(context, PARENT_SPAN_KEY, null, Span.class); if (span == null) { return; } if (span.isRecording()) { span.setStatus(HttpTraceUtil.parseResponseStatus(responseCode, throwable)); } span.end(); } /** * {@inheritDoc} */ @Override public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { logger.warning("Failed to set span attribute since value is null or empty."); return; } final Span span = getOrDefault(context, PARENT_SPAN_KEY, null, Span.class); if (span != null) { span.setAttribute(key, AttributeValue.stringAttributeValue(value)); } else { logger.warning("Failed to find span to add attribute."); } } /** * {@inheritDoc} */ @Override public Context setSpanName(String spanName, Context context) { return context.addData(USER_SPAN_NAME_KEY, spanName); } /** * {@inheritDoc} */ @Override public void end(String statusMessage, Throwable throwable, Context context) { final Span span = getOrDefault(context, PARENT_SPAN_KEY, null, Span.class); if (span == null) { logger.warning("Failed to find span to end it."); return; } if (span.isRecording()) { span.setStatus(AmqpTraceUtil.parseStatusMessage(statusMessage, throwable)); } span.end(); } @Override public void addLink(Context context) { final Builder spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, Builder.class); if (spanBuilder == null) { logger.warning("Failed to find spanBuilder to link it."); return; } final SpanContext spanContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); if (spanContext == null) { logger.warning("Failed to find span context to link it."); return; } spanBuilder.addLink(spanContext); } /** * {@inheritDoc} */ @Override public Context extractContext(String diagnosticId, Context context) { return AmqpPropagationFormatUtil.extractContext(diagnosticId, context); } @Override public Context getSharedSpanBuilder(String spanName, Context context) { return context.addData(SPAN_BUILDER_KEY, getSpanBuilder(spanName, context)); } /** * Starts a new child {@link Span} with parent being the remote and uses the {@link Span} is in the current Context, * to return an object that represents that scope. * <p>The scope is exited when the returned object is closed.</p> * * @param spanName The name of the returned Span. * @param context The {@link Context} containing the {@link SpanContext}. * @return The returned {@link Span} and the scope in a {@link Context} object. */ private Context startScopedSpan(String spanName, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); Span span; SpanContext spanContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); if (spanContext != null) { span = startSpanWithRemoteParent(spanName, spanContext); } else { Builder spanBuilder = getSpanBuilder(spanName, context); span = spanBuilder.setSpanKind(Span.Kind.CONSUMER).startSpan(); } if (span.isRecording()) { // If span is sampled in, add additional request attributes addSpanRequestAttributes(span, context, spanName); } return context.addData(PARENT_SPAN_KEY, span).addData("scope", TRACER.withSpan(span)); } /** * Creates a {@link Builder} to create and start a new child {@link Span} with parent being the remote and * designated by the {@link SpanContext}. * * @param spanName The name of the returned Span. * @param spanContext The remote parent context of the returned Span. * @return A {@link Span} with parent being the remote {@link Span} designated by the {@link SpanContext}. */ private static Span startSpanWithRemoteParent(String spanName, SpanContext spanContext) { Builder spanBuilder = TRACER.spanBuilder(spanName).setParent(spanContext); spanBuilder.setSpanKind(Span.Kind.CONSUMER); return spanBuilder.startSpan(); } /** * Extracts the {@link SpanContext trace identifiers} and the {@link SpanContext} of the current tracing span as * text and returns in a {@link Context} object. * * @param span The current tracing span. * @return The {@link Context} containing the {@link SpanContext} and trace-parent of the * current span. */ private static Context setContextData(Span span) { SpanContext spanContext = span.getContext(); final String traceparent = AmqpPropagationFormatUtil.getDiagnosticId(spanContext); return new Context(DIAGNOSTIC_ID_KEY, traceparent).addData(SPAN_CONTEXT_KEY, spanContext); } /** * Extracts request attributes from the given {@code context} and adds it to the started span. * * @param span The span to which request attributes are to be added. * @param context The context containing the request attributes. * @param spanName The name of the returned Span containing the component value. */ private void addSpanRequestAttributes(Span span, Context context, String spanName) { Objects.requireNonNull(span, "'span' cannot be null."); span.setAttribute(COMPONENT, AttributeValue.stringAttributeValue(parseComponentValue(spanName))); span.setAttribute( MESSAGE_BUS_DESTINATION, AttributeValue.stringAttributeValue(getOrDefault(context, ENTITY_PATH_KEY, "", String.class))); span.setAttribute( PEER_ENDPOINT, AttributeValue.stringAttributeValue(getOrDefault(context, HOST_NAME_KEY, "", String.class))); } /** * Extracts the component name from the given span name. * * @param spanName The spanName containing the component name i.e spanName = "EventHubs.send" * @return The component name contained in the context i.e "eventhubs" */ private static String parseComponentValue(String spanName) { if (spanName != null && !spanName.isEmpty()) { int componentNameEndIndex = spanName.lastIndexOf("."); if (componentNameEndIndex != -1) { return spanName.substring(0, componentNameEndIndex); } } return ""; } /** * Returns a {@link Builder} to create and start a new child {@link Span} with parent being * the designated {@code Span}. * * @param spanName The name of the returned Span. * @param context The context containing the span and the span name. * @return A {@code Span.Builder} to create and start a new {@code Span}. */ private Builder getSpanBuilder(String spanName, Context context) { Span parentSpan = getOrDefault(context, PARENT_SPAN_KEY, null, Span.class); String spanNameKey = getOrDefault(context, USER_SPAN_NAME_KEY, null, String.class); if (spanNameKey == null) { spanNameKey = spanName; } if (parentSpan == null) { parentSpan = TRACER.getCurrentSpan(); } return TRACER.spanBuilder(spanNameKey).setParent(parentSpan); } /** * Returns the value of the specified key from the context. * * @param key The name of the attribute that needs to be extracted from the {@code Context}. * @param defaultValue the value to return in data not found. * @param clazz clazz the type of raw class to find data for. * @param context The context containing the specified key. * * @return The T type of raw class object */ @SuppressWarnings("unchecked") private <T> T getOrDefault(Context context, String key, T defaultValue, Class<T> clazz) { final Optional<Object> optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { logger.warning("Could not extract key '{}' of type '{}' from context.", key, clazz); return defaultValue; }); return (T) result; } }
40.354037
120
0.656226
51506cfe1079fb76f570e112681fa4da3f19b49b
453
package com.ajgaonkar.leetcode; import org.junit.Test; import static org.junit.Assert.*; public class LC392_Is_SubsequenceTest { LC392_Is_Subsequence test = new LC392_Is_Subsequence(); @Test public void test(){ assertEquals(true, test.isSubsequence("abc", "ahbgdc")); assertEquals(true, test.isSubsequence("abc", "abc")); assertEquals(false, test.isSubsequence("axc", "ahbgdc")); assertEquals(false, test.isSubsequence("abc", "ab")); } }
26.647059
59
0.737307
2be579366ee195ce7fe65a6daf75396e6bd5afe5
597
package io.quarkus.hibernate.orm.singlepersistenceunit.entityassignment.packageincludedthroughconfig; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class EntityIncludedThroughPackageConfig { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "includedSeq") public long id; public String name; public EntityIncludedThroughPackageConfig() { } public EntityIncludedThroughPackageConfig(String name) { this.name = name; } }
23.88
101
0.777219
14b56fa42c5e5bc1a3f2b8f46cc69113cfd47cb1
812
package io.github.padlocks.customorigins.player; import net.minecraft.client.network.ClientPlayerEntity; import java.lang.ref.WeakReference; public final class PlayerTicker { private static PlayerTicker ticker = new PlayerTicker(null); public static PlayerTicker get(final ClientPlayerEntity player) { if (ticker.ref.get() != player) { ticker = new PlayerTicker(player); } return ticker; } private final WeakReference<ClientPlayerEntity> ref; private PlayerTicker(final ClientPlayerEntity player) { this.ref = new WeakReference<>(player); } public void afterInputTick(final ClientPlayerEntity player) { final float flightSpeed = FlightHelper.getFlightSpeed(player); player.abilities.setFlySpeed(flightSpeed); } }
29
70
0.714286
332397200f2a4a8c8cc69e64b61f86bd138f4ecd
884
package cl.getapps.sgme.injection.component; import cl.getapps.sgme.ui.ayuda.AyudaActivity; import cl.getapps.sgme.ui.eventos.EventosActivity; import cl.getapps.sgme.ui.eventos.detalle.DetalleEventoActivity; import cl.getapps.sgme.ui.hojaderuta.HojaRutaActivity; import dagger.Subcomponent; import cl.getapps.sgme.injection.PerActivity; import cl.getapps.sgme.injection.module.ActivityModule; import cl.getapps.sgme.ui.main.MainActivity; /** * This component inject dependencies to all Activities across the application */ @PerActivity @Subcomponent(modules = ActivityModule.class) public interface ActivityComponent { void inject(MainActivity mainActivity); void inject(EventosActivity eventosActivity); void inject(HojaRutaActivity hojaRutaActivity); void inject(AyudaActivity ayudaActivity); void inject(DetalleEventoActivity detalleEventoActivity); }
30.482759
78
0.816742
3a80460aa6d468be3cf0da0b52b6e6c707f1dc6c
315
package com.example.springmvc.localdate; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.time.LocalDate; /** * @author Hodur * @date 2021/8/5 */ @Data public class LocalDateItem { private Long id; @JsonFormat(pattern = "yyyy-MM-dd") private LocalDate date; }
15.75
51
0.71746
9644048af5ad10e9f959a2da627d29b969aa8d78
1,298
package com.thakkali.model; public class CheckOut { private int order_id; private int id; private String name; private int quantity; private int price; private int max_count; private String image_url; public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public int getOrder_id() { return order_id; } public void setOrder_id(int order_id) { this.order_id = order_id; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getMax_count() { return max_count; } public void setMax_count(int max_count) { this.max_count = max_count; } public CheckOut() {} @Override public String toString() { return "CheckOut [id=" + id + ", name=" + name + ", quantity=" + quantity + ", price=" + price + ", max_count=" + max_count + "]"; } }
18.542857
97
0.634052
d29da3bf24412b10c593ccbb168f1b023867d649
4,065
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. * </p> */ package io.shardingsphere.core.executor.sql; import io.shardingsphere.core.constant.ConnectionMode; import io.shardingsphere.core.event.ShardingEventBusInstance; import io.shardingsphere.core.executor.ShardingExecuteEngine; import io.shardingsphere.core.executor.sql.event.overall.OverallExecutionEvent; import io.shardingsphere.core.executor.sql.threadlocal.ExecutorExceptionHandler; import lombok.RequiredArgsConstructor; import java.sql.SQLException; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * SQL execute template. * * @author gaohongtao * @author zhangliang * @author maxiaoguang * @author panjuan */ @RequiredArgsConstructor public final class SQLExecuteTemplate { private final ShardingExecuteEngine executeEngine; private final ConnectionMode connectionMode; /** * Execute. * * @param executeUnits execute units * @param executeCallback execute callback * @param <T> class type of return value * @return execute result * @throws SQLException SQL exception */ public <T> List<T> execute(final Collection<? extends StatementExecuteUnit> executeUnits, final SQLExecuteCallback<T> executeCallback) throws SQLException { return execute(executeUnits, null, executeCallback); } /** * Execute. * * @param executeUnits execute units * @param firstExecuteCallback first execute callback * @param executeCallback execute callback * @param <T> class type of return value * @return execute result * @throws SQLException SQL exception */ public <T> List<T> execute( final Collection<? extends StatementExecuteUnit> executeUnits, final SQLExecuteCallback<T> firstExecuteCallback, final SQLExecuteCallback<T> executeCallback) throws SQLException { OverallExecutionEvent event = new OverallExecutionEvent(executeUnits.size() > 1); ShardingEventBusInstance.getInstance().post(event); try { List<T> result = ConnectionMode.MEMORY_STRICTLY == connectionMode ? executeEngine.execute(new LinkedList<>(executeUnits), firstExecuteCallback, executeCallback) : executeEngine.groupExecute(getExecuteUnitGroups(executeUnits), firstExecuteCallback, executeCallback); event.setExecuteSuccess(); return result; // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON event.setExecuteFailure(ex); ExecutorExceptionHandler.handleException(ex); return Collections.emptyList(); } finally { ShardingEventBusInstance.getInstance().post(event); } } private Map<String, Collection<StatementExecuteUnit>> getExecuteUnitGroups(final Collection<? extends StatementExecuteUnit> executeUnits) { Map<String, Collection<StatementExecuteUnit>> result = new LinkedHashMap<>(executeUnits.size(), 1); for (StatementExecuteUnit each : executeUnits) { String dataSourceName = each.getSqlExecutionUnit().getDataSource(); if (!result.keySet().contains(dataSourceName)) { result.put(dataSourceName, new LinkedList<StatementExecuteUnit>()); } result.get(dataSourceName).add(each); } return result; } }
38.714286
191
0.709717
5cc4859106bb657599cba8ce30119ec550a43107
4,736
package cn.saberking.jvav.apm.web.controller.system; import cn.saberking.jvav.apm.common.annotation.Log; import cn.saberking.jvav.apm.common.config.ApmConfig; import cn.saberking.jvav.apm.common.constant.Constants; import cn.saberking.jvav.apm.common.core.controller.BaseController; import cn.saberking.jvav.apm.common.core.domain.AjaxResult; import cn.saberking.jvav.apm.common.core.domain.entity.SysUser; import cn.saberking.jvav.apm.common.core.domain.model.LoginUser; import cn.saberking.jvav.apm.common.enums.BusinessType; import cn.saberking.jvav.apm.common.utils.SecurityUtils; import cn.saberking.jvav.apm.common.utils.ServletUtils; import cn.saberking.jvav.apm.common.utils.file.FileUploadUtils; import cn.saberking.jvav.apm.common.utils.file.FileUtils; import cn.saberking.jvav.apm.framework.web.service.TokenService; import cn.saberking.jvav.apm.system.service.ISysUserService; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.IOException; /** * 个人信息 业务处理 * * @author apm */ @RestController @RequestMapping("/system/user/profile") public class SysProfileController extends BaseController { @Resource private ISysUserService userService; @Resource private TokenService tokenService; /** * 个人信息 */ @GetMapping public AjaxResult profile() { LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest()); SysUser user = loginUser.getUser(); AjaxResult ajax = AjaxResult.success(user); ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername())); ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername())); return ajax; } /** * 修改用户 */ @Log(title = "个人信息", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult updateProfile(@RequestBody SysUser user) { if (userService.updateUserProfile(user) > 0) { LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest()); // 更新缓存用户信息 loginUser.getUser().setNickName(user.getNickName()); loginUser.getUser().setPhonenumber(user.getPhonenumber()); loginUser.getUser().setEmail(user.getEmail()); loginUser.getUser().setSex(user.getSex()); tokenService.setLoginUser(loginUser); return AjaxResult.success(); } return AjaxResult.error("修改个人信息异常,请联系管理员"); } /** * 重置密码 */ @Log(title = "个人信息", businessType = BusinessType.UPDATE) @PutMapping("/updatePwd") public AjaxResult updatePwd(String oldPassword, String newPassword) { LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest()); String userName = loginUser.getUsername(); String password = loginUser.getPassword(); if (!SecurityUtils.matchesPassword(oldPassword, password)) { return AjaxResult.error("修改密码失败,旧密码错误"); } if (SecurityUtils.matchesPassword(newPassword, password)) { return AjaxResult.error("新密码不能与旧密码相同"); } if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) { // 更新缓存用户密码 loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword)); tokenService.setLoginUser(loginUser); return AjaxResult.success(); } return AjaxResult.error("修改密码异常,请联系管理员"); } /** * 头像上传 */ @Log(title = "用户头像", businessType = BusinessType.UPDATE) @PostMapping("/avatar") public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException { if (!file.isEmpty()) { LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest()); String oldAvatar = loginUser.getUser().getAvatar(); String avatar = FileUploadUtils.upload(ApmConfig.getAvatarPath(), file); if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) { if (oldAvatar != null) { String relPath = oldAvatar.replace(Constants.RESOURCE_PREFIX, ApmConfig.getProfile()); System.out.println("原头像真实路径:" + relPath); FileUtils.deleteFile(relPath); } AjaxResult ajax = AjaxResult.success(); ajax.put("imgUrl", avatar); // 更新缓存用户头像 loginUser.getUser().setAvatar(avatar); tokenService.setLoginUser(loginUser); return ajax; } } return AjaxResult.error("上传图片异常,请联系管理员"); } }
39.466667
106
0.672086
e1c636f16ff8276e38d469b4729ca45b6eb24505
2,532
package de.fau.amos.virtualledger.android.views.bankingOverview.deleteBankAccessAccount; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import de.fau.amos.virtualledger.android.views.bankingOverview.deleteBankAccessAccount.functions.BiConsumer; import de.fau.amos.virtualledger.android.views.bankingOverview.deleteBankAccessAccount.functions.BiFunction; import de.fau.amos.virtualledger.dtos.BankAccess; import de.fau.amos.virtualledger.dtos.BankAccount; /** * Created by sebastian on 21.05.17. * Shows a deletion Dialog. Shows the item name extracted by the getName function. * If the User approves the deletion, the approvedAction will be executed */ public class DeleteDialog { private BankAccess bankAccess; private BankAccount bankAccount; private BiFunction<BankAccess, BankAccount, String> getName; private BiConsumer<BankAccess, BankAccount> approvedAction; private Context context; /** * @param bankAccess = the bank access * @param bankAccount = the bank account if neccessary * @param getName = the name extractor to extract the name of the access and the account * @param approvedAction = the action that is executed when the delete option is approved */ public DeleteDialog(Context context, BankAccess bankAccess, BankAccount bankAccount, BiFunction<BankAccess, BankAccount, String> getName, BiConsumer<BankAccess, BankAccount> approvedAction) { this.bankAccess = bankAccess; this.bankAccount = bankAccount; this.getName = getName; this.approvedAction = approvedAction; this.context = context; } /** * shows the popup */ public void show() { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle("DELETE CONFIRMATION"); alert.setMessage("Are you sure to delete " + this.getName.apply(bankAccess, bankAccount)+"?"); alert.setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); approvedAction.accept(bankAccess, bankAccount); } }); alert.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); } }
36.171429
195
0.698262
2b05d5fb1cadcecd425376492dd4fd784e54205e
682
package com.spring.di.constructor.dependentObjList; import java.util.Iterator; import java.util.List; public class Question { private int id; private String name; private List answers; // Define Constructor Question() { System.out.println("def cons"); } public Question(int id, String name, List answers) { super(); this.id = id; this.name = name; this.answers = answers; } void show(){ System.out.println(id+" "+name); Iterator itr = answers.iterator(); while(itr.hasNext()) { String ans =(String)itr.next(); System.out.println(ans.toString()); } } }
16.238095
55
0.589443
5976fa94c667400b0d640269d196390af33a8dea
1,053
package com.example.designPattern.create_type.prototype.deep_copy; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * @author: zhoupb * @Description: 奖状原型类: 深克隆 测试类 * @since: version 1.0 */ public class Client { public static void main(String[] args) throws Exception { Citation citation = new Citation(); Student stu = new Student(); stu.setName("张三"); citation.setStu(stu); // 创建对象输出流对象 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e:/a.txt")); // 写对象 oos.writeObject(citation); // 释放资源 oos.close(); // 创建对象输入流对象 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e:/a.txt")); // 读对象 Citation citation1 = (Citation) ois.readObject(); // 释放资源 ois.close(); // 修改克隆对象的属性 citation1.getStu().setName("李四"); citation.show(); citation1.show(); } }
24.488372
90
0.621083
c66b5cb7757c4be5e0d273731350dcb5f7e622dc
751
/** * <p>Title : SPI:服务提供接口</p> * <p>Description : * * SPI = Service Provider Interface 服务提供接口 * * 原理:反射机制 * * JDK SPI: 通过java.util.ServiceLoader实现,模块化开发,解除耦合 * 服务提供者模块(jar) 在META-INF/services目录下 添加接口文件,文件内容为接口实现类的全路径 * 如:文件名为【example.MyService】,文件内容为【example.MyServiceImpl1,example.MyServiceImpl2】 * 服务消费者模块(jar) 则通过ServiceLoader.load动态获取接口实例 * * Spring SPI: 通过org.springframework.core.io.support.SpringFactoriesLoader 实现 * 服务提供者 在META-INF/spring.factories文件中,记录接口与实现的键值对,即可: * example.MyService=example.MyServiceImpl1,example.MyServiceImpl2 逗号分隔 * 服务消费者 通过调用SpringFactoriesLoader.loadFactories 获取所有的SPI服务列表 * * * * </p> * <p>Date : 2019-01-30 </p> * * @author : hejie */ package hj.action.tomcat.springboot.SPI;
28.884615
86
0.729694
6b29ee6b728266c8723d84ee8f432d97419dcfdb
4,114
/******************************************************************************* * Code contributed to the webinos 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. * * Copyright 2011-2012 Paddy Byers * ******************************************************************************/ package org.webinos.app.wrt.ui; import org.webinos.app.R; import org.webinos.app.wrt.mgr.WidgetConfig; import org.webinos.app.wrt.mgr.WidgetManagerService; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class WidgetListAdapter extends ArrayAdapter<String> { private final Context context; private final String[] values; public WidgetListAdapter(Context context, String[] values) { super(context, R.layout.rowlayout, values); this.context = context; this.values = values; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.rowlayout, parent, false); TextView labelView = (TextView) rowView.findViewById(R.id.label); TextView detailView = (TextView) rowView.findViewById(R.id.detail); ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); String installId = values[position]; /* decide what to show as the main label text */ String labelText = null; WidgetConfig widgetConfig = WidgetManagerService.getInstance().getWidgetConfig(installId); if(widgetConfig == null) { labelText = "widgetConfig is null - widget not properly installed"; return rowView; } if(widgetConfig.name != null) labelText = widgetConfig.name.visual; if(labelText == null || labelText.isEmpty()) { if(widgetConfig.shortName != null) labelText = widgetConfig.shortName.visual; if(labelText == null || labelText.isEmpty()) { labelText = widgetConfig.id; if(labelText == null || labelText.isEmpty()) { labelText = "Untitled"; } } } labelView.setText(labelText); /* decide what to show as the detail label text */ String descriptionText = null; if(widgetConfig.description != null) descriptionText = widgetConfig.description.visual; if(descriptionText == null) descriptionText = ""; String authorText = null; if(widgetConfig.author != null) { if(widgetConfig.author.name != null) authorText = widgetConfig.author.name.visual; if(authorText == null || authorText.isEmpty()) { authorText = widgetConfig.author.href; if(authorText == null) authorText = ""; } } String versionText = null; if(widgetConfig.version != null) versionText = widgetConfig.version.visual; if(versionText == null) versionText = ""; String detailText = authorText; if(!versionText.isEmpty()) { if(!detailText.isEmpty()) detailText += " "; detailText += versionText; } if(!descriptionText.isEmpty()) { if(!detailText.isEmpty()) detailText += " "; detailText += descriptionText; } detailView.setText(detailText); /* decide what to show as the icon */ String prefIcon = widgetConfig.prefIcon; if(prefIcon == null || prefIcon.isEmpty()) { imageView.setImageResource(R.drawable.webinos_icon); } else { String iconPath = WidgetManagerService.getInstance().getWidgetDir(installId) + '/' + prefIcon; imageView.setImageDrawable(Drawable.createFromPath(iconPath)); } return rowView; } }
34.571429
97
0.70491
215f9ab83f4a16e9d9cd3d7d54b9d175d40a1166
626
package com.nbs.iais.ms.common.db.domains.abstracts; import com.nbs.iais.ms.common.db.domains.interfaces.MultilingualText; import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class AbstractMultiLanguageText extends AbstractDomainObject implements MultilingualText { public AbstractMultiLanguageText() { } public AbstractMultiLanguageText(String lang, String text) { } @Override public void addText(String lang, String text) { getMap().put(lang, text); } @Override public String getText(final String lang) { return getMap().get(lang); } }
24.076923
106
0.731629
427c23afac02c4c05eccf0670a68cb70a71f3e04
3,714
/* * Copyright © 2016 Cask Data, 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 co.cask.cdap.etl.tool.config; import co.cask.cdap.api.artifact.ArtifactScope; import co.cask.cdap.api.artifact.ArtifactSummary; import co.cask.cdap.client.ArtifactClient; import co.cask.cdap.client.NamespaceClient; import co.cask.cdap.etl.proto.ArtifactSelectorConfig; import co.cask.cdap.etl.proto.UpgradeContext; import co.cask.cdap.proto.NamespaceMeta; import co.cask.cdap.proto.artifact.PluginInfo; import co.cask.cdap.proto.id.ArtifactId; import co.cask.cdap.proto.id.NamespaceId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import javax.annotation.Nullable; /** * Uses an ArtifactClient to get the artifact for a specific plugin. */ public class ClientUpgradeContext implements UpgradeContext { private static final Logger LOG = LoggerFactory.getLogger(ClientUpgradeContext.class); private final NamespaceClient namespaceClient; private final ArtifactClient artifactClient; private final String artifactName; private final String artifactVersion; private ArtifactId artifactId; public ClientUpgradeContext(NamespaceClient namespaceClient, ArtifactClient artifactClient, String artifactName, String artifactVersion) { this.namespaceClient = namespaceClient; this.artifactClient = artifactClient; this.artifactName = artifactName; this.artifactVersion = artifactVersion; } @Nullable @Override public ArtifactSelectorConfig getPluginArtifact(String pluginType, String pluginName) { try { List<PluginInfo> plugins = artifactClient.getPluginInfo(getArtifactId(), pluginType, pluginName, ArtifactScope.SYSTEM); if (plugins.isEmpty()) { return null; } // doesn't really matter which one we choose, as all of them should be valid. // choosing the last one because that tends to be the one with the highest version. // order is not guaranteed though. ArtifactSummary chosenArtifact = plugins.get(plugins.size() - 1).getArtifact(); return new ArtifactSelectorConfig(chosenArtifact.getScope().name(), chosenArtifact.getName(), chosenArtifact.getVersion()); } catch (Exception e) { LOG.warn("Unable to find an artifact for plugin of type {} and name {}. " + "Plugin artifact section will be left empty.", pluginType, pluginName); return null; } } private ArtifactId getArtifactId() { if (artifactId == null) { // just need to get a namespace that exists, ArtifactScope.SYSTEM will take care of the rest. NamespaceId namespaceId = NamespaceId.DEFAULT; try { List<NamespaceMeta> namespaces = namespaceClient.list(); if (!namespaces.isEmpty()) { namespaceId = namespaceClient.list().get(0).getNamespaceId(); } } catch (Exception e) { LOG.warn("Unable to list namespaces. Plugin artifact sections will likely be left empty.", e); } artifactId = namespaceId.artifact(artifactName, artifactVersion); } return artifactId; } }
38.6875
114
0.713786
296454494937e00e7f814f754a467b2181717e67
772
package com.tui.architecture.eventdriven.stresstest.core.event; import lombok.EqualsAndHashCode; import lombok.ToString; import org.springframework.kafka.support.KafkaHeaders; /* * Message event * * @author joseluis.nogueira on 28/08/2019 */ @EqualsAndHashCode(callSuper = false) @ToString public class DataModifiedEvent extends KafkaEvent { public static final String MEDIA_TYPE_HEADER = "media-type"; public static final String OPERATION_HEADER = "operation"; public DataModifiedEvent(String key, String mediaType, Object source, EEventOperation eEventOperation) { super(source); addHeader(MEDIA_TYPE_HEADER, mediaType); addHeader(OPERATION_HEADER, eEventOperation.getOperation()); addHeader(KafkaHeaders.MESSAGE_KEY, key.getBytes()); } }
30.88
106
0.786269
ee47eaeb989e4bf2fe9094c602d76741261a22be
627
package com.sophia.store.entity.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @AllArgsConstructor @NoArgsConstructor @ToString @ApiModel(value = "返回分页消息实体") public class PageResponse extends Response { @ApiModelProperty(value = "分页大小", example = "20") private int pageSize = 20; @ApiModelProperty(value = "总消息数", example = "100") private int totalRows = 0; @ApiModelProperty(value = "总页面数", example = "200") private int totalPages = 0; }
27.26087
54
0.751196
18b5c6461b9834794dfc1cb9d1961fbc69b195ee
463
package com.tek271.util.reflect; import java.util.List; import junit.framework.TestCase; public class ReflectUtilTest extends TestCase { public void testGetPackageDirectoryOfClass() { String dir= ReflectUtil.getPackageDirectoryOfClass(String.class); assertEquals("java/lang", dir); } public void testGetSuperclasses() { List supers= ReflectUtil.getSuperclasses(String.class); assertEquals(1, supers.size()); } }
23.15
70
0.719222
1b92bca9afeda7e69fd3d4ede234b8f5b7ffbe8d
894
public class MexicanWave { public static void main(String...Args) { String str = " gap "; String [] wave = wave(str); for (int i = 0; i < wave.length; i++) { System.out.println(wave[i]); } } public static String[] wave(String str) { str = str.toLowerCase(); //Contar espacios int spaces = 0; for(int sn = 0 ; sn < str.length(); sn++) { if(str.charAt(sn) == ' ') { spaces++; } } String [] variants = new String [(str.length() - spaces)]; for (int x = 0, y = 0; x < str.length(); x++) { if(str.charAt(x) != ' ') { variants[y] = str.substring(0, x) + String.valueOf(str.charAt(x)).toUpperCase() + str.substring(x+1, str.length()); y++; } } return variants; } }
24.833333
131
0.448546
69b3680dae793407666f83ebea42b6ede23ffece
333
package io.zephyr.kernel.core; import io.zephyr.kernel.Coordinate; import io.zephyr.kernel.Module; import lombok.NonNull; public interface ModuleClasspathManager { void install(@NonNull Module module); void uninstall(@NonNull Coordinate coordinate); void uninstall(@NonNull Module module); void check(Module module); }
19.588235
49
0.780781
704d2756d3c82810b066b483ac3c8de2140cdbcb
308
package mobi.tarantino.stub.auto.feature.splashScreen; import dagger.Component; import mobi.tarantino.stub.auto.di.BaseComponent; import mobi.tarantino.stub.auto.di.PerActivity; @PerActivity @Component(dependencies = {BaseComponent.class} ) public interface TestSplashComponent extends SplashComponent { }
25.666667
62
0.831169
49c53ee67e4ce037802005ebebc83d10aa504374
2,522
/* * ### * phresco-pom * * Copyright (C) 1999 - 2012 Photon Infotech 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 com.phresco.pom.test; import java.io.File; import java.io.IOException; import javax.xml.bind.JAXBException; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.phresco.pom.exception.PhrescoPomException; import com.phresco.pom.util.POMErrorCode; import com.phresco.pom.util.PomProcessor; public class PomProcessorRemoveModuleTest { @Before public void prepare() throws IOException, JAXBException { File file = new File("pomTest.xml"); if(file.exists()) { file.delete(); } } @Test public void validRemoveModule() { try { PomProcessor processor = new PomProcessor(new File("pomTest.xml")); processor.addModule("photon"); processor.addModule("phresco"); processor.removeModule("phresco"); processor.save(); int actual = processor.getModel().getModules().getModule().size(); int expected = 1; Assert.assertEquals(actual,expected); } catch (JAXBException e) { Assert.fail("Remove Module Failed!"); } catch (IOException e) { Assert.fail("Remove Module Failed!"); } catch(PhrescoPomException ph){ Assert.fail("Remove Module Failed!"); } } @Test public void invalidRemoveModule() { try { PomProcessor processor = new PomProcessor(new File("pomTest.xml")); processor.addModule("photon"); processor.addModule("phresco"); processor.removeModule("DLF"); processor.save(); } catch (JAXBException e) { Assert.fail("Remove Module Failed!"); } catch (IOException e) { Assert.fail("Remove Module Failed!"); } catch(PhrescoPomException ph){ Assert.assertTrue(ph.getErrorCode() == POMErrorCode.MODULE_NOT_FOUND); } } @After public void delete() { File file = new File("pomTest.xml"); if(file.exists()) { file.delete(); } } }
27.11828
75
0.685567
f7e42ff7c4fe90577356e8dc2fe12433ea9bd3c1
1,457
package edu.escuelaing.arsw.DatagramServer; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; public class DatagramTimeServer { DatagramSocket socket; public DatagramTimeServer() { try { socket = new DatagramSocket(4445); } catch (SocketException ex) { Logger.getLogger(DatagramTimeServer.class.getName()).log(Level.SEVERE, null, ex); } } public void startServer() { byte[] buf = new byte[256]; try { while(true) { DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String dString = new Date().toString(); buf = dString.getBytes(); InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } } catch (IOException ex) { Logger.getLogger(DatagramTimeServer.class.getName()).log(Level.SEVERE, null, ex); } socket.close(); } public static void main(String[] args) { DatagramTimeServer ds = new DatagramTimeServer(); ds.startServer(); } }
31
93
0.608099
fdef9490e67d9d9d7a20988d6cb9230b13d41d39
1,717
package org.infinispan.counter.impl.factory; import java.util.concurrent.CompletionStage; import org.infinispan.Cache; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.impl.strong.AbstractStrongCounter; import org.infinispan.counter.impl.strong.BoundedStrongCounter; import org.infinispan.counter.impl.strong.StrongCounterKey; import org.infinispan.counter.impl.strong.UnboundedStrongCounter; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; /** * Created bounded and unbounded {@link StrongCounter} stored in a {@link Cache}. * * @since 14.0 */ @Scope(Scopes.GLOBAL) public class CacheBasedStrongCounterFactory extends CacheBaseCounterFactory<StrongCounterKey> implements StrongCounterFactory { @Override public CompletionStage<StrongCounter> createStrongCounter(String name, CounterConfiguration configuration) { assert configuration.type() != CounterType.WEAK; return blockingManager.thenApplyBlocking(cache(configuration), cache -> { AbstractStrongCounter counter =configuration.type() == CounterType.BOUNDED_STRONG ? new BoundedStrongCounter(name, cache, configuration, notificationManager) : new UnboundedStrongCounter(name, cache, configuration, notificationManager); counter.init(); return counter; }, "create-strong-counter" + name); } @Override public CompletionStage<Void> removeStrongCounter(String name) { return getCounterCacheAsync().thenCompose(cache -> AbstractStrongCounter.removeStrongCounter(cache, name)); } }
40.880952
127
0.780431
02b94c15df498afb29e8fb5abd5828902e0643cc
1,221
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.me.calculator; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.ejb.Stateless; /** * * @author Junaid */ @WebService(serviceName = "CalculatorWS") @Stateless() public class CalculatorWS { /** * Web service operation */ @WebMethod(operationName = "add") public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) { int k = i + j; return k; } /** * Web service operation */ @WebMethod(operationName = "subtract") public int subtract(@WebParam(name = "i") int i, @WebParam(name = "j") int j) { int k = i - j; return k; } /** * Web service operation */ @WebMethod(operationName = "multiply") public int multiply(@WebParam(name = "i") int i, @WebParam(name = "j") int j) { int k = i * j; return k; } /** * Web service operation */ @WebMethod(operationName = "divide") public int divide(@WebParam(name = "i") int i, @WebParam(name = "j") int j) { int k = i / j; return k; } }
21.803571
83
0.571663
dd5af911305284a9a94e5c60d4163ea7261b717a
1,713
package com.routon.plcloud.device.core.service; import com.routon.plcloud.device.data.entity.Vrdevice; import java.util.List; import java.util.Map; /** * @author FireWang * @date 2020/5/07 15:09 */ public interface VrdeviceService { /** * 根据设备格式新增设备软件 * * @param vrdevice * @return * @throws Exception */ boolean insertVrDevice(Vrdevice vrdevice) throws Exception; /** * 根据设备格式删除设备软件 * * @param vrdevice * @return * @throws Exception */ boolean deleteVrDevice(Vrdevice vrdevice) throws Exception; /** * 修改设备软件信息 * * @param vrdevice * @return * @throws Exception */ boolean update(Vrdevice vrdevice) throws Exception; /** * 根据vrdeviceid查询设备所有(包括历史)软件列表 * * @param vrdeviceid * @return * @throws Exception */ Vrdevice searchByDeviceId(String vrdeviceid) throws Exception; /** * 根据id获取设备软件 * * @param id * @return * @throws Exception */ Vrdevice getById(Integer id) throws Exception; /** * 根据条件获取最大条数 * * @param paramMap * @return * @throws Exception */ Integer getMaxCount(Map<String, Object> paramMap); /** * 根据条件获取列表 * * @param paramMap * @return * @throws Exception */ List<Vrdevice> getMaxList(Map<String, Object> paramMap) throws Exception; /** * 根据条件查询设备列表并分页 * * @param paramMap 查询条件Map * @param page 页号 * @param pageSize 条数 * @return * @throws Exception */ List<Vrdevice> searchvrdeviceforpage(Map<String, Object> paramMap, Integer page, Integer pageSize) throws Exception; }
19.689655
120
0.595447
96d008a34a45291044b43ca61ac038f4f8e9a50d
355
package org.nibiru.oauth.android.ioc; import org.nibiru.oauth.android.business.AndroidOAuth2Manager; import org.nibiru.oauth.core.api.OAuth2Manager; import dagger.Module; import dagger.Provides; @Module public class AndroidModule { @Provides public OAuth2Manager getOAuth2Manager(AndroidOAuth2Manager manager) { return manager; } }
22.1875
73
0.780282
fe193f926f0df9b343835bb3738d84cae3552f78
862
package de.deeprobin.amethyst_mod.mixin; import de.deeprobin.amethyst_mod.AmethystMod; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.DefaultBiomeCreator; import net.minecraft.world.biome.GenerationSettings.Builder; import net.minecraft.world.gen.GenerationStep; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(DefaultBiomeCreator.class) public abstract class MixinDefaultBiomeCreator { @Inject(method = "method_31065", at = @At("HEAD")) private static void addEndOres(Builder builder, CallbackInfoReturnable<Biome> info) { builder.feature(GenerationStep.Feature.SURFACE_STRUCTURES, AmethystMod.THE_END_AMETHYST_ORE_FEATURE); } }
37.478261
109
0.819026
12e5d26d45cba94f626c4ced3a2a35fb9f794390
317
package hrms.business.abstracts; import hrms.core.business.baseService.BaseService; import hrms.core.utilities.results.DataResult; import hrms.entities.concretes.GithubAccount; public interface GithubAccountService extends BaseService<GithubAccount, Integer> { DataResult<GithubAccount> getByUser(Integer id); }
35.222222
83
0.839117
864551a57d30a75c4532cb88c199a8b9ad171185
78
package com.tutorialspoint.inheritance; public interface AnimalImp { }
13
40
0.75641
86d8e63cbd2e9b7b04d1ae15b5a51660dd3589c8
364
package cn.ruleengine.web.store.mapper; import cn.ruleengine.web.store.entity.RuleEngineConditionGroupCondition; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author dqw * @since 2020-07-16 */ public interface RuleEngineConditionGroupConditionMapper extends BaseMapper<RuleEngineConditionGroupCondition> { }
20.222222
112
0.774725
bee81148690c024341ad68782e56e24d9a613b26
1,084
package no.paneon.api.diagram.puml; import no.paneon.api.utils.Config; import no.paneon.api.logging.LogMethod; import no.paneon.api.graph.DiscriminatorNode; import no.paneon.api.graph.Node; import no.paneon.api.logging.AspectLogger.LogLevel; public class DiscriminatorEntity extends Entity { String type; private DiscriminatorEntity(String type) { super(); this.type = type; } public DiscriminatorEntity(Node node) { super(); this.type = node.getName(); } @LogMethod(level=LogLevel.DEBUG) public String toString() { StringBuilder res = new StringBuilder(); if(Config.getIncludeDebug()) { res.append( getCommentInfo() ); } res.append( "diamond " + this.type ); res.append( NEWLINE ); return res.toString(); } @LogMethod(level=LogLevel.DEBUG) public int hashCode() { return this.type.hashCode(); } @Override @LogMethod(level=LogLevel.DEBUG) public boolean equals(Object o) { if(o instanceof DiscriminatorEntity) { return type.contentEquals(((DiscriminatorEntity)o).type); } return false; } }
19.017544
60
0.70203
3360fc6c68339ecba2429542fa3cc16a48cfa86a
456
package me.hardcoded.compiler.parser.expr; import me.hardcoded.compiler.impl.ISyntaxPosition; import me.hardcoded.compiler.parser.type.TreeType; public class NullExpr extends Expr { public NullExpr(ISyntaxPosition syntaxPosition) { super(syntaxPosition); } @Override public boolean isEmpty() { return false; } @Override public boolean isPure() { return true; } @Override public TreeType getTreeType() { return TreeType.NULL; } }
17.538462
50
0.75
2ae0fd92dcd17bbf98b0537db3c790f34d5dcd99
3,965
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.quarkus.support.spring.test; import java.io.File; import java.net.JarURLConnection; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.jar.Attributes; import java.util.jar.Manifest; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; @QuarkusTest public class SpringSupportTest { @Test public void springClassLoading() { // Verify that classes excluded by the Quarkus Spring extensions can be loaded // I.e check they are not blacklisted since the camel-quarkus-support-spring-(beans,context,core) jars will provide them String[] classNames = new String[] { // From: org.springframework:spring-beans "org.springframework.beans.factory.InitializingBean", // From: org.springframework:spring-context "org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor", // From: org.springframework:spring-core "org.springframework.core.SpringVersion", }; for (String className : classNames) { RestAssured.given() .pathParam("className", className) .when() .get("/classloading/{className}") .then() .statusCode(204); } } @Test public void verifySourcesJarManifest() throws Exception { String[] springModules = new String[] { "beans", "context", "core" }; for (String module : springModules) { Path path = Paths.get("../" + module + "/target"); File file = path.toFile(); if (!file.exists()) { throw new IllegalStateException("The sources JAR location does not exist: " + file.getAbsolutePath()); } File[] files = file .listFiles(f -> f.getName().matches("^camel-quarkus-support-spring-" + module + "-.*-sources.jar")); if (files.length == 1) { URL url = new URL("jar:file:" + files[0].getAbsolutePath() + "!/"); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest manifest = jarConnection.getManifest(); assertNotNull(manifest); Attributes attributes = manifest.getMainAttributes(); assertNotNull(attributes.getValue("Specification-Version")); assertNotNull(attributes.getValue("Implementation-Version")); } else if (files.length == 0) { throw new IllegalStateException( "Detected no camel-quarkus-support-spring-" + module + " sources JAR in: " + file.getAbsolutePath()); } else { throw new IllegalStateException( "Detected multiple camel-quarkus-support-spring-" + module + " sources JARs in: " + file.getAbsolutePath()); } } } }
42.634409
128
0.621942
a516d752f4129d49bcba7c539fd6ee7152ae70d7
1,104
/* * mumbot * By Kailari (Ilari Tommiska) * * Copyright (c) 2016. Ilari Tommiska (MIT License) */ package se.erikwelander.zubat.services.protocols.mumble.protocol.mumbot.packet; import com.google.protobuf.Message; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; /** * Packets consist of prefix and payload */ public class Packet { private final PacketType type; private final Message payload; public Packet(PacketType type, Message payload) { this.payload = payload; this.type = type; } public void writeTo(OutputStream stream) throws IOException { byte[] payload = this.payload.toByteArray(); byte[] length = ByteBuffer.allocate(4).putInt(payload.length).array(); // Prefix stream.write(this.type.toBytes()); stream.write(length); // Payload stream.write(payload); } public PacketType getType() { return this.type; } public Message getMessage() { return this.payload; } }
22.530612
80
0.628623
29692e979af5c62d4b1d4d68a590d074c97178cb
228
package com.group.nuntius.obp.domain; import lombok.Data; @Data public class ATM { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } }
13.411765
37
0.596491
f0c748f4ee26ef867b050fa64fe3bb5198e4c06e
686
package jp.gr.java_conf.alpius.pino.graphics; import jp.gr.java_conf.alpius.pino.graphics.color.ColorSpace; abstract class RGBFormat implements PixelFormat { private final ColorSpace anyRgbColorSpace; private final boolean hasAlpha; protected RGBFormat(ColorSpace anyRgbColorSpace, boolean hasAlpha) { assert anyRgbColorSpace.getType() == ColorSpace.TYPE_RGB : "anyRgbColorSpace is not RGB family"; this.anyRgbColorSpace = anyRgbColorSpace; this.hasAlpha = hasAlpha; } @Override public ColorSpace getColorSpace() { return anyRgbColorSpace; } @Override public boolean hasAlpha() { return hasAlpha; } }
27.44
104
0.717201
52ea57dde70208a43783b57d0da2117af110a211
1,478
package org.openrewrite.definitions; import java.io.IOException; import static java.util.Collections.emptyList; import org.openrewrite.java.AddField; import org.openrewrite.java.JavaRefactorVisitor; import org.openrewrite.java.tree.J; import org.openrewrite.java.tree.TreeBuilder; import org.openrewrite.refactor.RefactorProcessor; public class AddLogger extends JavaRefactorVisitor { @Override public J.Package visitPackage(J.Package pkg) { return pkg.withExpr(TreeBuilder.buildName("org.openrewrite.after").withPrefix(pkg.getPrefix().concat(" "))); } public J visitClassDecl(J.ClassDecl clazz) { if(needsLogger(clazz) && clazz .findFields("org.slf4j.Logger") .isEmpty()) { andThen(new AddField.Scoped( clazz, emptyList(), // modifiers "org.slf4j.Logger", "logger", // field name "LoggerFactory.getLogger(" + clazz.getSimpleName() + ".class);" // Assignment expression )); // since this is used in the initializer above // maybeAddImport("org.slf4j.LoggerFactory"); addImport("org.slf4j.LoggerFactory"); } return super.visitClassDecl(clazz); } private boolean needsLogger(J.ClassDecl clazz) { return true; } public static void main(String... args) throws IOException { RefactorProcessor.run(new AddLogger(), "B.java"); } }
33.590909
116
0.645467
4bd54b7858743edfa32c69c8e6efe07fa314493c
340
package com.challenge.entity; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.sql.Timestamp; @Embeddable public class SubmissionPK implements Serializable { @ManyToOne private User userId; @ManyToOne private Challenge challengeId; }
17.894737
51
0.779412
3627fb85ef30bc981557cc30a65aee09239eac35
5,752
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.spring.tests.generate; import com.intellij.testFramework.TestDataPath; import org.jetbrains.kotlin.test.JUnit3RunnerWithInners; import org.jetbrains.kotlin.test.KotlinTestUtils; import org.jetbrains.kotlin.test.TargetBackend; import org.jetbrains.kotlin.test.TestMetadata; import org.junit.runner.RunWith; import java.io.File; import java.util.regex.Pattern; /** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */ @SuppressWarnings("all") @TestMetadata("ultimate/testData/spring/core/generate") @TestDataPath("$PROJECT_ROOT") @RunWith(JUnit3RunnerWithInners.class) public class GenerateSpringDependencyActionTestGenerated extends AbstractGenerateSpringDependencyActionTest { public void testAllFilesPresentInGenerate() throws Exception { KotlinTestUtils.assertAllTestsPresentInSingleGeneratedClass(this.getClass(), new File("ultimate/testData/spring/core/generate"), Pattern.compile("^([\\w]+)\\.kt$"), TargetBackend.ANY); } @TestMetadata("autowiredDependencies/duplicatingPropertyAnnotationConfig.kt") public void testAutowiredDependencies_DuplicatingPropertyAnnotationConfig() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/autowiredDependencies/duplicatingPropertyAnnotationConfig.kt"); doTest(fileName); } @TestMetadata("autowiredDependencies/duplicatingPropertyXmlConfig.kt") public void testAutowiredDependencies_DuplicatingPropertyXmlConfig() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/autowiredDependencies/duplicatingPropertyXmlConfig.kt"); doTest(fileName); } @TestMetadata("autowiredDependencies/multiplePropertiesAnnotationConfig.kt") public void testAutowiredDependencies_MultiplePropertiesAnnotationConfig() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/autowiredDependencies/multiplePropertiesAnnotationConfig.kt"); doTest(fileName); } @TestMetadata("autowiredDependencies/multiplePropertiesXmlConfig.kt") public void testAutowiredDependencies_MultiplePropertiesXmlConfig() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/autowiredDependencies/multiplePropertiesXmlConfig.kt"); doTest(fileName); } @TestMetadata("autowiredDependencies/propertyWithQualifierAnnotationConfig.kt") public void testAutowiredDependencies_PropertyWithQualifierAnnotationConfig() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/autowiredDependencies/propertyWithQualifierAnnotationConfig.kt"); doTest(fileName); } @TestMetadata("autowiredDependencies/propertyWithQualifierXmlConfig.kt") public void testAutowiredDependencies_PropertyWithQualifierXmlConfig() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/autowiredDependencies/propertyWithQualifierXmlConfig.kt"); doTest(fileName); } @TestMetadata("autowiredDependencies/singlePropertyAnnotationConfig.kt") public void testAutowiredDependencies_SinglePropertyAnnotationConfig() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/autowiredDependencies/singlePropertyAnnotationConfig.kt"); doTest(fileName); } @TestMetadata("autowiredDependencies/singlePropertyXmlConfig.kt") public void testAutowiredDependencies_SinglePropertyXmlConfig() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/autowiredDependencies/singlePropertyXmlConfig.kt"); doTest(fileName); } @TestMetadata("beanDependenciesByXml/firstConstructor.kt") public void testBeanDependenciesByXml_FirstConstructor() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/beanDependenciesByXml/firstConstructor.kt"); doTest(fileName); } @TestMetadata("beanDependenciesByXml/primaryConstructorAddParam.kt") public void testBeanDependenciesByXml_PrimaryConstructorAddParam() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/beanDependenciesByXml/primaryConstructorAddParam.kt"); doTest(fileName); } @TestMetadata("beanDependenciesByXml/property.kt") public void testBeanDependenciesByXml_Property() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/beanDependenciesByXml/property.kt"); doTest(fileName); } @TestMetadata("beanDependenciesByXml/secondaryConstructorAddParam.kt") public void testBeanDependenciesByXml_SecondaryConstructorAddParam() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/beanDependenciesByXml/secondaryConstructorAddParam.kt"); doTest(fileName); } @TestMetadata("beanDependenciesByXml/setter.kt") public void testBeanDependenciesByXml_Setter() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("ultimate/testData/spring/core/generate/beanDependenciesByXml/setter.kt"); doTest(fileName); } }
54.264151
192
0.799896
452cd5b838106b6dce5d478f7d58ee32d75201e6
969
/* * Copyright 2020 Sukhvir Thapar * * 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.sukhvir41.cli; import java.util.logging.Level; import java.util.logging.Logger; public final class LogManager { private final static Logger LOGGER = Logger.getAnonymousLogger(); public static void setLoggerLevel(Level level) { LOGGER.setLevel(level); } public static Logger getLogger() { return LOGGER; } }
26.189189
75
0.723426
9f419931b309e7e4bfee1420251ce9f694e5e387
430
package org.malloc.leet.code; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * @author malloc * @since 2020/6/18 */ class TwoSumTest { private final TwoSum twoSum = new TwoSum(); @Test void twoSum() { int[] r = twoSum.twoSum(new int[]{2, 7, 11, 15}, 9); Assertions.assertArrayEquals(new int[]{0, 1}, r); } }
20.47619
60
0.644186
a6a3809965f8b3838f5a376f8fd0367b27488bc3
765
package br.com.livrariaweb.persistence.dao; import java.util.List; /** * Defines as operações básicas de acesso e manipulação aos dados * armazenados no banco de dados. * * @author thiago-amm * @version v1.0.0 12/01/2019 * @since v1.0.0 */ public interface DAO<T> { /** * Insere um registro no banco de dados. * @param t referência para o objeto a ser inserido */ DAO<T> insert(T t) throws DAOException; DAO<T> update(T t) throws DAOException; DAO<T> save(T t) throws DAOException; DAO<T> delete(T t) throws DAOException; DAO<T> deleteById(Integer id) throws DAOException; DAO<T> deleteAll() throws DAOException; T selectById(Integer id) throws DAOException; List<T> selectAll() throws DAOException; }
28.333333
66
0.684967
dddce7d00aaa69636d0d92660bca84a11e659e75
745
package com.github.kornilova203.matlab.stub; import com.github.kornilova203.matlab.psi.MatlabFunctionDeclaration; import com.intellij.psi.stubs.StringStubIndexExtension; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; public class MatlabFunctionDeclarationIndex extends StringStubIndexExtension<MatlabFunctionDeclaration> { public static final StubIndexKey<String, MatlabFunctionDeclaration> KEY = StubIndexKey.createIndexKey("matlab.function.declaration"); @Override public @NotNull StubIndexKey<String, MatlabFunctionDeclaration> getKey() { return KEY; } @Override public int getVersion() { return super.getVersion() + MatlabIndexVersion.INDEX_VERSION; } }
35.47619
137
0.791946
f1e9d6a6578660d72cb68322d73df7050e7ae089
17,630
package org.sdnhub.flowtags; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.channels.spi.SelectorProvider; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import org.opendaylight.controller.sal.core.Node; //import org.openflow.protocol.factory.BasicFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MiddleboxHandler { // check protocol_plugin Controller.java nad ControllerIO.java // methods run at ControllerIO private static final Logger logger = LoggerFactory .getLogger(MiddleboxHandler.class); private Thread middleboxHandlerThread; private boolean running; private Selector selector; private final SocketChannel socket; // private final BasicFactory factory; private final AtomicInteger xid; private final String instanceName; private IMessageReadWrite msgReadWriteService; private PriorityBlockingQueue<PriorityMessage> transmitQ; private Thread transmitThread; /* Added by Toby for control message */ private FTTags ftTags = null; private FTOutputTags ftOutTags = null; private FTMiddeBoxes mbes = null; private CoreRouters coreRouters = null; private HashMap<String, EdgeResponder> edgeSW = null; // End // public MiddleboxHandler(SocketChannel sc, String name) { /* Added by Toby for control message */ public MiddleboxHandler(SocketChannel sc, String name, FTTags ftTags, FTOutputTags ftOutTags, CoreRouters coreRouters, HashMap<String, EdgeResponder> edgeSW, FTMiddeBoxes mbes) { this.socket = sc; this.instanceName = name; /* Added by Toby for control message */ this.ftTags = ftTags; this.ftOutTags = ftOutTags; this.coreRouters = coreRouters; this.edgeSW = edgeSW; this.mbes = mbes; // End this.xid = new AtomicInteger(this.socket.hashCode()); // this.factory = new BasicFactory(); } public boolean isRunning() { return running; } private void startHandlerThread() { middleboxHandlerThread = new Thread(new Runnable() { @Override public void run() { running = true; while (running) { try { // wait for an incoming connection selector.select(0); logger.info("Incoming data"); Iterator<SelectionKey> selectedKeys = selector .selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey skey = selectedKeys.next(); selectedKeys.remove(); if (skey.isValid() && skey.isWritable()) { logger.info("Resume send messages"); resumeSend(); } if (skey.isValid() && skey.isReadable()) { logger.info("Handling messages"); handleMessages(); } } } catch (Exception e) { reportError(e); } } } }, instanceName); middleboxHandlerThread.start(); } public void handleMessages() { List<FTMessage> msgs = null; try { if (msgReadWriteService != null) { msgs = msgReadWriteService.readMessages(); } } catch (Exception e) { // reportError(e); // LC: Close socket, middlebox connection error logger.info("Stopping " + instanceName); stop(); return; } if (msgs == null) { return; } for (FTMessage msg : msgs) { // TODO: LC handle response try { FTMessage reply = null; // TODO: LC, add more modules, add logic using ODL msg platform // if its a field query if (msg.type == FTType.QUERY) { reply = new FTMessage(FTType.QUERY, msg.mbid, 0, FTTagfield.TOS.getInt()); } if (msg.type == FTType.INTAG) { logger.info("INTAG mbid: {} state: {} tag: {}", msg.mbid, msg.state, msg.tag); FTFiveTuple ftFiveTuple = this.consumeTag(msg.tag); if (ftFiveTuple != null) { logger.info("INTAG " + ftFiveTuple.toString()); reply = new FTMessage(FTType.INTAG, msg.mbid, 0, 1, this.ftTags.getFiveTuple(msg.tag)); } else { logger.info("INTAG NULL"); reply = new FTMessage(FTType.INTAG, msg.mbid, 0, 0); } } if (msg.type == FTType.OUTTAG) { logger.info("OUTTAG mbid: {} state: {} tag: {}", msg.mbid, msg.state, msg.tag); int newTag = this.generateTag(msg.mbid, msg.state, msg.tag); logger.info("OUTTAG newTag: {}", newTag); reply = new FTMessage(FTType.OUTTAG, msg.mbid, newTag, 1, FTProtocol.TCP, "", "", (short) 0, (short) 0); } /* Added by Toby for control message */ if (msg.type == FTType.CONTROL) { FTControlMessage controlMessage = msg.getControlMessage(); ArrayList<Integer> args = controlMessage.getArgs(); CoreRouter router; System.out.println("Control Message:" + controlMessage.toString()); switch (controlMessage.getControlType()) { case FTControlMessage.TAG_ADD: int next = 5; if (args.size() == 7) { next = args.get(6); } if (this.ftTags.add( args.get(0), new FTFiveTuple(args.get(1), args.get(2), args .get(3), args.get(4), args.get(5)),next)) { reply = new FTMessage(new FTControlMessage( "TAG ADD OK\n" + this.ftTags.toString() + "\n\n")); } else { reply = new FTMessage(new FTControlMessage( "TAG ADD NG\n" + this.ftTags.toString() + "\n\n")); } break; case FTControlMessage.TAG_DEL: if (this.ftTags.del(args.get(0))) { this.coreRouters.removeTagRoute(args.get(0)); reply = new FTMessage(new FTControlMessage( "TAG DEL OK\n" + this.ftTags.toString() + "\n\n")); } else { reply = new FTMessage(new FTControlMessage( "TAG DEL NG\n" + this.ftTags.toString() + "\n\n")); } break; case FTControlMessage.TAG_DUMP: reply = new FTMessage(new FTControlMessage( "TAG DUMP OK\n" + this.ftTags.toString() + "\n\n")); break; case FTControlMessage.TAG_CLEAR: this.ftTags.clear(); this.coreRouters.removeAllTagRoutes(); reply = new FTMessage(new FTControlMessage( "TAG CLEAR OK\n" + this.ftTags.toString() + "\n\n")); break; case FTControlMessage.OUTTAG_ADD: if (this.ftOutTags.add(args.get(0), args.get(1), args.get(2), args.get(3),args.get(4))) { if(args.get(3) != 0){ this.coreRouters.setTagRoute(args.get(3)/4, args.get(4)); } reply = new FTMessage(new FTControlMessage( "OUTTAG ADD OK\n" + this.ftOutTags.toString() + "\n\n")); } else { reply = new FTMessage(new FTControlMessage( "OUTTAG ADD NG\n" + this.ftOutTags.toString() + "\n\n")); } break; case FTControlMessage.OUTTAG_DEL: if (this.ftOutTags.del(args.get(0), args.get(1), args.get(2))) { reply = new FTMessage(new FTControlMessage( "OUTTAG DEL OK\n" + this.ftOutTags.toString() + "\n\n")); } else { reply = new FTMessage(new FTControlMessage( "OUTTAG DEL NG\n" + this.ftOutTags.toString() + "\n\n")); } break; case FTControlMessage.OUTTAG_DUMP: reply = new FTMessage(new FTControlMessage( "OUTTAG DUMP OK\n" + this.ftOutTags.toString() + "\n\n")); break; case FTControlMessage.OUTTAG_CLEAR: this.ftOutTags.clear(); reply = new FTMessage(new FTControlMessage( "OUTTAG CLEAR OK\n" + this.ftOutTags.toString() + "\n\n")); break; case FTControlMessage.MB_ADD: if(this.mbes.add(args.get(0), args.get(1), args.get(2),args.get(3),args.get(4))){ int mbid = args.get(0); // Requrired for the mininet, host <-> controller if(this.edgeSW.get(this.mbes.getSWID(mbid)) != null){ this.edgeSW.get(this.mbes.getSWID(mbid)).setMBType(this.mbes.getType(mbid)); } if(args.get(3) != 0){ this.coreRouters.setIpRoute(args.get(1), args.get(3),args.get(4)); } reply = new FTMessage(new FTControlMessage( "MB ADD OK\n" + this.mbes.toString() + "\n\n")); } else{ reply = new FTMessage(new FTControlMessage( "MB ADD NG\n" + this.mbes.toString() + "\n\n")); } break; case FTControlMessage.MB_DEL: if(this.mbes.del(args.get(0))){ int mbid = args.get(0); // Requrired for the mininet, host <-> controller if(this.edgeSW.get(this.mbes.getSWID(mbid)) != null){ this.edgeSW.get(this.mbes.getSWID(mbid)).setMBType(null); } reply = new FTMessage(new FTControlMessage( "MB DEL OK\n" + this.mbes.toString() + "\n\n")); } else{ reply = new FTMessage(new FTControlMessage( "MB DEL NG\n" + this.mbes.toString() + "\n\n")); } break; case FTControlMessage.MB_DUMP: reply = new FTMessage(new FTControlMessage( "MB DUMP OK\n" + this.mbes.toString() + "\n\n")); break; case FTControlMessage.MB_CLEAR: for(EdgeResponder edgeSW: this.edgeSW.values()){ edgeSW.setMBType(null); edgeSW.removeAllTagRoutes(); } this.mbes.clear(); reply = new FTMessage(new FTControlMessage( "MB CLEAR OK\n" + this.mbes.toString() + "\n\n")); break; case FTControlMessage.FW_ADD: long swID = (((long)args.get(0)) << 32) + (long)args.get(1); int hostID = args.get(2); int connectorID = args.get(3); router = this.coreRouters.getRouter(swID); if(router != null){ System.out.println("0"); router.addForwardingTable(hostID, connectorID); System.out.println("1"); reply = new FTMessage(new FTControlMessage( "FW ADD OK\n" + router.dumpForwardingTable() + "\n\n")); System.out.println("2"); } else { System.out.println("3"); reply = new FTMessage(new FTControlMessage( "FW ADD NG\nNo Router " + args.get(0) + "\n\n")); System.out.println("4"); } break; case FTControlMessage.FW_DEL: swID = (((long)args.get(0)) << 32) + (long)args.get(1); hostID = args.get(2); router = this.coreRouters.getRouter(swID); if(router != null){ router.delForwardingTable(hostID); reply = new FTMessage(new FTControlMessage( "FW DEL OK\n" + router.dumpForwardingTable() + "\n\n")); } else { reply = new FTMessage(new FTControlMessage( "FW DEL NG\nNo Router " + args.get(0) + "\n\n")); } break; case FTControlMessage.FW_DUMP: reply = new FTMessage(new FTControlMessage( "FW DUMP OK\n" + this.coreRouters.dumpForwardingTable()+"\n\n")); break; case FTControlMessage.FW_CLEAR: this.coreRouters.clearForwardingTable(); reply = new FTMessage(new FTControlMessage( "FW CLEAR OK\n" + this.coreRouters.dumpForwardingTable()+"\n\n")); break; case FTControlMessage.TEST_ADD: int tag = args.get(0); int testGeneratorId = args.get(1); int hostId = args.get(2); int senderSrcIP = args.get(3); int generatorSrcIP = args.get(4); System.out.println("Tag:" + tag + " hostID:" + hostId); this.coreRouters.setTagRouteWithLocation(tag/4, hostId); System.out.println("Tag:" + (tag/4+1) + " testGeneratorId:" + testGeneratorId); this.coreRouters.setTagRouteWithLocation(tag/4+1, testGeneratorId); this.edgeSW.get(FTUtil.getSWID(hostId)).setTestSenderRule(tag, tag+4,senderSrcIP,generatorSrcIP); reply = new FTMessage(new FTControlMessage("Test ADD Success\n\n")); break; case FTControlMessage.TAG_GENERATE: hostId = args.get(0); tag = args.get(1); int srcIP = args.get(2); int dstIP = args.get(3); int srcPort = args.get(4); int dstPort = args.get(5); int proto = args.get(6); if(this.edgeSW.containsKey(FTUtil.getSWID(hostId))){ this.edgeSW.get(FTUtil.getSWID(hostId)).setExplicitTagGenerate(srcIP, dstIP,srcPort, dstPort, proto,tag); } reply = new FTMessage(new FTControlMessage("Explicit Tag Generate Success\n\n")); break; case FTControlMessage.TAG_GENERATE_DEL: hostId = args.get(0); tag = args.get(1); srcIP = args.get(2); dstIP = args.get(3); System.out.println("DEL ID:"+hostId); if(this.edgeSW.containsKey(FTUtil.getSWID(hostId))){ System.out.println("Try to del"); this.edgeSW.get(FTUtil.getSWID(hostId)).delExplicitTagGenerate(srcIP, dstIP); } reply = new FTMessage(new FTControlMessage("Explicit Tag Del Success\n\n")); break; case FTControlMessage.TAG_GENERATE_CLEAR: hostId = args.get(0); if(this.edgeSW.containsKey(FTUtil.getSWID(hostId))){ this.edgeSW.get(FTUtil.getSWID(hostId)).clearExplicitTagGenerate(); } reply = new FTMessage(new FTControlMessage("Explicit Tag Clear Success\n\n")); break; } } // End if (reply != null) { msgReadWriteService.asyncSend(reply); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private int generateTag(int mid, int state, int preTag) { int newTag = -1; newTag = this.ftOutTags.get(mid, state, preTag); if(newTag == -1 ){ newTag = this.ftOutTags.getWithSrcIP(mid, state, preTag); } // Toby: We need to write some error handler // We cannot find good tag for generation if(newTag == -1){ newTag = 0; } // Toby: This is dirty hack for the evaluation of DDoS Project // I'll add mux logic here. if( mid == 61 && state == 1){ // Attack newTag = 40; } else if ( mid == 61 && state == 0){ // Non Attack newTag = 20; } return newTag; } private FTFiveTuple consumeTag(int tag) { return this.ftTags.getFiveTuple(tag); } private void stopInternal() { // logger.debug("{} receives stop signal", // (isOperational() ? HexString.toHexString(sid) : "unknown")); running = false; // cancelSwitchTimer(); try { selector.wakeup(); selector.close(); } catch (Exception e) { } try { socket.close(); } catch (Exception e) { } try { msgReadWriteService.stop(); } catch (Exception e) { } logger.debug("executor shutdown now"); // executor.shutdownNow(); msgReadWriteService = null; } // private void cancelSwitchTimer() { // if (this.periodicTimer != null) { // this.periodicTimer.cancel(); // } // } public void start() { try { startTransmitThread(); setupCommChannel(); // sendFirstHello(); startHandlerThread(); } catch (Exception e) { reportError(e); } } /* * Setup communication services */ private void setupCommChannel() throws Exception { this.selector = SelectorProvider.provider().openSelector(); this.socket.configureBlocking(false); this.socket.socket().setTcpNoDelay(true); this.msgReadWriteService = getMessageReadWriteService(); } public void stop() { stopInternal(); if (middleboxHandlerThread != null) { middleboxHandlerThread.interrupt(); } if (transmitThread != null) { transmitThread.interrupt(); } } public void resumeSend() { try { if (msgReadWriteService != null) { msgReadWriteService.resumeSend(); } } catch (Exception e) { reportError(e); } } class PriorityMessageTransmit implements Runnable { @Override public void run() { running = true; while (running) { try { PriorityMessage pmsg = transmitQ.take(); msgReadWriteService.asyncSend(pmsg.msg); /* * If syncReply is set to true, wait for the response back. */ if (pmsg.syncReply) { // syncMessageInternal(pmsg.msg, pmsg.msg.getXid(), // false); } } catch (InterruptedException ie) { reportError(new InterruptedException( "PriorityMessageTransmit thread interrupted")); } catch (Exception e) { reportError(e); } } transmitQ = null; } } private IMessageReadWrite getMessageReadWriteService() throws Exception { // String str = System.getProperty("secureChannelEnabled"); // return ((str != null) && (str.trim().equalsIgnoreCase("true"))) ? new // SecureMessageReadWriteService(socket, // selector) : new MessageReadWriteService(socket, selector); // LC: no secure socket return new MessageReadWriteService(socket, selector); } /* * Setup and start the transmit thread */ private void startTransmitThread() { this.transmitQ = new PriorityBlockingQueue<PriorityMessage>(11, new Comparator<PriorityMessage>() { @Override public int compare(PriorityMessage p1, PriorityMessage p2) { if (p2.priority != p1.priority) { return p2.priority - p1.priority; } else { return (p2.seqNum < p1.seqNum) ? 1 : -1; } } }); this.transmitThread = new Thread(new PriorityMessageTransmit()); this.transmitThread.start(); } private void reportError(Exception e) { // if (!running) { // logger.debug("Caught exception {} while switch {} is shutting down. Skip", // e.getMessage(), // (isOperational() ? HexString.toHexString(sid) : "unknown")); // return; // } logger.debug("Caught exception: ", e); // notify core of this error event and disconnect the switch // ((Controller) core).takeSwitchEventError(this); // clean up some internal states immediately stopInternal(); } }
29.780405
112
0.624957
756a50598b0c21a9f891c4534b868162907c99dd
3,023
package org.jxls.builder.xml; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jxls.area.Area; import org.jxls.area.XlsArea; import org.jxls.builder.AreaBuilder; import org.jxls.transform.Transformer; import ch.qos.logback.core.Context; import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.action.NewRuleAction; import ch.qos.logback.core.joran.spi.ElementSelector; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; /** * Creates an area based on the XML definition * * @author Leonid Vysochyn */ public class XmlAreaBuilder implements AreaBuilder { private final InputStream xmlInputStream; private Transformer transformer; private final boolean clearTemplateCells; public XmlAreaBuilder(Transformer transformer) { this(null, transformer, true); } public XmlAreaBuilder(InputStream xmlInputStream, Transformer transformer) { this(xmlInputStream, transformer, true); } public XmlAreaBuilder(InputStream xmlInputStream, Transformer transformer, boolean clearTemplateCells) { this.xmlInputStream = xmlInputStream; this.transformer = transformer; this.clearTemplateCells = clearTemplateCells; } @Override public Transformer getTransformer() { return transformer; } @Override public void setTransformer(Transformer transformer) { this.transformer = transformer; } public List<Area> build(InputStream is) { Map<ElementSelector, Action> ruleMap = new HashMap<>(); AreaAction areaAction = new AreaAction(transformer); ruleMap.put(new ElementSelector("*/area"), areaAction); ruleMap.put(new ElementSelector("*/each"), new EachAction()); ruleMap.put(new ElementSelector("*/if"), new IfAction()); ruleMap.put(new ElementSelector("*/user-command"), new UserCommandAction()); ruleMap.put(new ElementSelector("*/grid"), new GridAction()); // TODO ImageAction // TODO UpdateCellAction // TODO MergeCellsAction (plus documentation) ruleMap.put(new ElementSelector("*/user-action"), new NewRuleAction()); Context context = new ContextBase(); SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); simpleConfigurator.setContext(context); try { simpleConfigurator.doConfigure(is); } catch (JoranException e) { printOccurredErrors(context); } if (clearTemplateCells) { for (Area area : areaAction.getAreaList()) { ((XlsArea) area).clearCells(); } } return areaAction.getAreaList(); } @Override public List<Area> build() { return build(xmlInputStream); } private void printOccurredErrors(Context context) { StatusPrinter.print(context); } }
31.489583
108
0.690043
3b8af6dba0c1e4e000483773d942ad83992902af
782
package com.hbird.base.mvp.model.db.greendao; import com.hbird.base.mvp.model.entity.table.HbirdIncomeType; import com.hbird.base.mvp.model.entity.table.HbirdSpendType; import com.ljy.devring.db.GreenTableManager; import org.greenrobot.greendao.AbstractDao; /** * Created by Liul on 2018/8/31. * description: 系统支出类目表 数据表管理者 for GreenDao * DevRing中提供了GreenTableManager(基本的数据表管理者),继承它然后实现getDao方法,将GreenDao自动生成的对应XXXDao返回即可。 */ public class HbirdSpendTypeManager extends GreenTableManager<HbirdSpendType,Void> { private DaoSession mDaoSession; public HbirdSpendTypeManager(DaoSession daoSession) { mDaoSession = daoSession; } @Override public AbstractDao<HbirdSpendType, Void> getDao() { return mDaoSession.getHbirdSpendTypeDao(); } }
30.076923
86
0.776215
84dc83750217febf7ce604bc6bcd00dda4e40489
9,243
package org.openpaas.paasta.portal.common.api.domain.email; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.RandomStringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import org.openpaas.paasta.portal.common.api.config.EmailConfig; import org.openpaas.paasta.portal.common.api.domain.common.CommonService; import org.openpaas.paasta.portal.common.api.entity.portal.InviteUser; import org.openpaas.paasta.portal.common.api.repository.portal.InviteUserRepository; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Service; import org.springframework.util.FileCopyUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.slf4j.LoggerFactory.getLogger; @Service public class EmailServiceV3 { private final Logger logger = getLogger(this.getClass()); @Autowired EmailConfig emailConfig; @Autowired InviteUserRepository inviteUserRepository; @Autowired CommonService commonService; public Map resetEmail(String userId, String refreshToken, String seq) { logger.info("createEmail >> userId : " + userId + " " + "seq : " + seq); Map map = new HashMap(); ClassPathResource cpr = new ClassPathResource("template/loginpass.html"); try { byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream()); String data = new String(bdata, emailConfig.getCharset()); Document doc = Jsoup.parse(data); Elements elementAhref = doc.select("a[href]"); Elements elementSpan = doc.select("span"); if (elementAhref.size() != 0) { String link = emailConfig.getAuthUrl() + "/" + emailConfig.getExpiredUrl() + "?userId=" + userId + "&refreshToken=" + refreshToken + "&seq=" + seq; logger.debug("link : " + link); elementAhref.get(0).attr("href", link); } if (elementSpan.size() != 0) { elementSpan.get(0).childNode(0).attr("text", userId); } if (emailConfig.sendEmail(userId, doc.outerHtml())) { map.put("result", true); map.put("msg", "You have successfully completed the task."); } else { map.put("result", false); map.put("msg", "System error."); } } catch (Exception e) { e.printStackTrace(); map.put("result", false); map.put("msg", e.getMessage()); } finally { IOUtils.closeQuietly(); } return map; } public Map createEmail(String userId, String refreshToken, String seq) { logger.info("createEmail >> userId : " + userId + " " + "seq : " + seq); Map map = new HashMap(); try { ClassPathResource cpr = new ClassPathResource("template/loginemail.html"); byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream()); String data = new String(bdata, emailConfig.getCharset()); Document doc = Jsoup.parse(data); Elements elementAhref = doc.select("a[href]"); if (elementAhref.size() != 0) { String link = emailConfig.getAuthUrl() + "/" + emailConfig.getCreateUrl() + "?userId=" + userId + "&refreshToken=" + refreshToken + "&seq=" + seq; logger.info("link : " + link); elementAhref.get(0).attr("href", link); } logger.info(doc.outerHtml()); if (emailConfig.sendEmail(userId, doc.outerHtml())) { map.put("result", true); map.put("msg", "You have successfully completed the task."); } else { map.put("result", false); map.put("msg", "System error."); } } catch (Exception e) { e.printStackTrace(); logger.info("Exception ::::: " + e.getMessage()); map.put("result", false); map.put("msg", e.getMessage()); } return map; } public Boolean inviteOrgEmail(Map body) { String[] userEmails; if (body.get("userEmail").toString().equals("")) return false; try { userEmails = body.get("userEmail").toString().split(","); logger.info("LENGTH ::" + userEmails.length); for (String userEmail : userEmails) { userEmail = userEmail.trim(); InviteUser inviteUser = new InviteUser(); List<InviteUser> user = inviteUserRepository.findByUserIdAndOrgGuid(userEmail, body.get("orgId").toString()); //TODO 하나 이상일 수 있나? if (user.size() > 0) { inviteUser.setId(user.get(0).getId()); } inviteUser.setUserId(userEmail); inviteUser.setGubun("send"); inviteUser.setRole(body.get("userRole").toString()); inviteUser.setOrgGuid(body.get("orgId").toString()); inviteUser.setInvitename(body.get("invitename").toString()); String randomId = RandomStringUtils.randomAlphanumeric(17).toUpperCase() + RandomStringUtils.randomAlphanumeric(2).toUpperCase(); inviteUser.setToken(randomId); //TODO 성공한 사람만 email 날릴 것인지 inviteUserRepository.save(inviteUser); inviteOrgEmailSend(userEmail, body.get("orgName").toString(), randomId, body.get("seq").toString()); } } catch (Exception e) { logger.info("ERROR ::" + e.getMessage()); return false; } return true; } public Map inviteAccept(Map body) { Map map = new HashMap(); try { List<InviteUser> user = inviteUserRepository.findByTokenAndGubunNot(body.get("token").toString(), "success"); if (user.size() > 0) { map.put("id", user.get(0).getId()); map.put("role", user.get(0).getRole()); map.put("orgGuid", user.get(0).getOrgGuid()); map.put("userId", user.get(0).getUserId()); map.put("result", true); } else { map.put("result", false); } } catch (Exception e) { e.printStackTrace(); map.put("result", false); } return map; } public Map inviteAcceptUpdate(Map body) { try { //InviteUser inviteUser = new InviteUser(); InviteUser user = inviteUserRepository.findById(Integer.parseInt(body.get("id").toString())); user.setGubun(body.get("gubun").toString()); inviteUserRepository.save(user); body.put("result", true); } catch (Exception e) { e.printStackTrace(); body.put("result", false); } return body; } public Map inviteOrgEmailSend(String userId, String orgName, String refreshToken, String seq) { logger.info("inviteOrgEmailSend >> userId : " + userId + "seq : " + seq); Map map = new HashMap(); try { ClassPathResource cpr = new ClassPathResource("template/invitation.html"); byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream()); String data = new String(bdata, emailConfig.getCharset()); Document doc = Jsoup.parse(data); final Elements elementAhref = doc.select("a[href]"); if (elementAhref.size() != 0) { String link = String.format("%s/%s?userId=%s&orgName=%s&refreshToken=%s&seq=%s", emailConfig.getAuthUrl(), emailConfig.getInviteUrl(), userId, orgName, refreshToken, seq); logger.info("link : {}", link); //link += "&seq="+seq; elementAhref.get(0).attr("href", link); } final Elements elementSpanId = doc.select("span[id=paasta_id]"); if (elementSpanId.size() >= 0) { logger.info("invite user id : {}", userId); elementSpanId.get(0).text(userId); } final Elements elementSpanOrg = doc.select("span[id=paasta_org]"); if (elementSpanOrg.size() >= 0) { logger.info("invite {} into org : {}", userId, orgName); elementSpanOrg.get(0).text(orgName); } logger.info(doc.outerHtml()); if (emailConfig.sendEmail(userId, doc.outerHtml())) { map.put("result", true); map.put("msg", "You have successfully completed the task."); } else { map.put("result", false); map.put("msg", "System error."); } } catch (Exception e) { logger.info("Exception (Simple) ::::: {}", e.getMessage()); logger.info("Exception (Stacktrace) ::::: ", e); map.put("result", false); map.put("msg", e.getMessage()); } return map; } }
38.037037
163
0.561181
be1c088e37c2257b99f3f723a87df859b5c652e5
6,882
/* * Copyright 2013 University of Glasgow. * * 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 broadwick.stochastic.algorithms; import broadwick.rng.RNG; import broadwick.stochastic.AmountManager; import broadwick.stochastic.SimulationEvent; import broadwick.stochastic.StochasticSimulator; import broadwick.stochastic.SimulationException; import broadwick.stochastic.TransitionKernel; import java.io.Serializable; import lombok.ToString; import lombok.extern.slf4j.Slf4j; /** * Implementation of Gillespie's Direct method. It is a simple Monte-Carlo algorithm which draws from a from Gillspie * derived distribution a reaction that will fire and a time at which the reaction will fire. * <p> * For reference see Daniel T. Gillespie., A General Method for Numerically Simulating the Stochastic Time Evolution of * Coupled Chemical Reactions, J.Comp.Phys. 22, 403 (1976) */ @ToString @Slf4j public class GillespieSimple extends StochasticSimulator implements Serializable { /** * No args constructor. Do not use, it is added so that the class can be deserialised if needed. */ public GillespieSimple() { super(); } /** * Implementation of Gillespie's Direct method. * @param amountManager the amount manager used in the simulator. * @param transitionKernel the transition kernel to be used with the stochastic solver. */ public GillespieSimple(final AmountManager amountManager, final TransitionKernel transitionKernel) { this(amountManager, transitionKernel, false); } /** * Implementation of Gillespie's Direct method. * @param amountManager the amount manager used in the simulator. * @param transitionKernel the transition kernel to be used with the stochastic solver. * @param reverseTime true if we wish to go backwards in time. */ public GillespieSimple(final AmountManager amountManager, final TransitionKernel transitionKernel, final boolean reverseTime) { super(amountManager, transitionKernel, reverseTime); } @Override public final void reinitialize() { changed = true; } @Override public final void performStep() { final double rTotal = calculateRTotal(); // obtain mu and tau by the direct method described in chapter 5A page 417ff final double tau = directMCTau(rTotal); if ((tau != Double.NEGATIVE_INFINITY) && (tau != Double.POSITIVE_INFINITY)) { changed = false; while (isThetaEventInCurrentStep(tau) && !changed) { doThetaEvent(); } if (changed) { performStep(); return; } if (Double.compare(rTotal, 0.0) != 0) { final SimulationEvent mu = directMCReaction(); doEvent(mu, getCurrentTime() + tau); } } // advance the time setCurrentTime(getCurrentTime() + tau); if ((tau != Double.NEGATIVE_INFINITY) && (tau != Double.POSITIVE_INFINITY)) { doThetaEvent(); } } /** * Calculate the h's described in (14) page 413 and the sum a (26) page 418. * @return the sum of the probabilities of all events. */ private double calculateRTotal() { double rTotal = 0.0; for (final SimulationEvent event : this.getTransitionKernel().getTransitionEvents()) { if (this.getTransitionKernel().getTransitionProbability(event) != null) { rTotal += this.getTransitionKernel().getTransitionProbability(event); } } return rTotal; } /** * Determine of there is a theta event in the current time step, taking into account possible reverse time jumps. * @param tau the time interval (will be negative for reverse time). * @return true if a theta event is found. */ private boolean isThetaEventInCurrentStep(final double tau) { final double nextEventTime = getNextThetaEventTime(); if (reverseTime) { return getCurrentTime() >= nextEventTime && getCurrentTime() + tau < nextEventTime; } else { return getCurrentTime() <= nextEventTime && getCurrentTime() + tau > nextEventTime; } } @Override public final String getName() { return "Gillespie Direct Method"; } @Override public final void setRngSeed(final int seed) { GENERATOR.seed(seed); } /** * obtains a random (but following a specific distribution) reaction as described by the direct method in chapter 5A * page 417ff. * @return the simulation event selected. */ private SimulationEvent directMCReaction() { final double rTotal = calculateRTotal(); final double test = GENERATOR.getDouble() * rTotal; double sum = 0; for (final SimulationEvent event : getTransitionKernel().getTransitionEvents()) { if (this.getTransitionKernel().getTransitionProbability(event) != null) { sum += this.getTransitionKernel().getTransitionProbability(event); } if (test <= sum) { return event; } } final StringBuilder sb = new StringBuilder(100); sb.append("No reaction could be selected!\nreaction = "); sb.append(test).append("\n"); sb.append(this.getTransitionKernel().getTransitionEvents().toString()); throw new SimulationException(sb.toString()); } /** * obtains a random (but following a specific distribution) timestep as described by the direct method in chapter 5A * page 417ff. * @param sum sum of the propensities * @return tau */ protected final double directMCTau(final double sum) { if (Double.compare(sum, 0.0) == 0) { return getNextThetaEventTime(); } final double r1 = GENERATOR.getDouble(); final double tau = (1 / sum) * Math.log(1 / r1); if (reverseTime) { return -1.0 * tau; } return tau; } private boolean changed = false; private static final RNG GENERATOR = new RNG(RNG.Generator.Well19937c); /** * The serialVersionUID. */ private static final long serialVersionUID = -953479930339424502L; }
36.221053
120
0.650683
c50cfafb351b139950a49bfba71abc5a529e3cd2
3,972
package org.hisp.dhis.coldchain.equipment; import java.util.ArrayList; import java.util.List; import org.hisp.dhis.common.BaseNameableObject; /** * @author Mithilesh Kumar Thakur * * @version EquipmentTypeAttributeGroup.javaMar 5, 2013 11:47:03 AM */ public class EquipmentTypeAttributeGroup extends BaseNameableObject { /** * Determines if a de-serialized file is compatible with this class. */ private static final long serialVersionUID = -6551567526188061690L; private int id; private String name; private String description; private EquipmentType equipmentType; private List<EquipmentType_Attribute> equipmentType_Attributes = new ArrayList<EquipmentType_Attribute>(); private Integer sortOrder; // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- public EquipmentTypeAttributeGroup() { } public EquipmentTypeAttributeGroup( String name ) { this.name = name; } public EquipmentTypeAttributeGroup( String name, String description ) { this.name = name; this.description = description; } public EquipmentTypeAttributeGroup( String name, String description , EquipmentType equipmentType ) { this.name = name; this.description = description; this.equipmentType = equipmentType; } public EquipmentTypeAttributeGroup( String name, String description , EquipmentType equipmentType, Integer sortOrder ) { this.name = name; this.description = description; this.equipmentType = equipmentType; this.sortOrder = sortOrder; } // ------------------------------------------------------------------------- // hashCode, equals and toString // ------------------------------------------------------------------------- @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null ) { return false; } if ( !(o instanceof EquipmentTypeAttributeGroup) ) { return false; } final EquipmentTypeAttributeGroup other = (EquipmentTypeAttributeGroup) o; return name.equals( other.getName() ); } @Override public String toString() { return "[" + name + "]"; } // ------------------------------------------------------------------------- // Getters and setters // ------------------------------------------------------------------------- public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public String getDescription() { return description; } public void setDescription( String description ) { this.description = description; } public EquipmentType getEquipmentType() { return equipmentType; } public void setEquipmentType( EquipmentType equipmentType ) { this.equipmentType = equipmentType; } public List<EquipmentType_Attribute> getEquipmentType_Attributes() { return equipmentType_Attributes; } public void setEquipmentType_Attributes( List<EquipmentType_Attribute> equipmentType_Attributes ) { this.equipmentType_Attributes = equipmentType_Attributes; } public Integer getSortOrder() { return sortOrder; } public void setSortOrder( Integer sortOrder ) { this.sortOrder = sortOrder; } }
22.697143
122
0.541037
ab448b549775f30bbcc6cc8e2c7ccdda5f688657
1,437
package com.github.aaronshan.functions.math; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.BooleanWritable; import org.apache.hadoop.io.DoubleWritable; /** * @author ruifeng.shan * date: 18-7-23 */ @Description(name = "is_infinite" , value = "_FUNC_(double) - test if value is infinite." , extended = "Example:\n > select _FUNC_(double) from src;") public class UDFMathIsInfinite extends UDF { /** * A constant holding the positive infinity of type * {@code double}. It is equal to the value returned by * {@code Double.longBitsToDouble(0x7ff0000000000000L)}. */ public static final double POSITIVE_INFINITY = 1.0 / 0.0; /** * A constant holding the negative infinity of type * {@code double}. It is equal to the value returned by * {@code Double.longBitsToDouble(0xfff0000000000000L)}. */ public static final double NEGATIVE_INFINITY = -1.0 / 0.0; BooleanWritable result = new BooleanWritable(); public UDFMathIsInfinite() { } public BooleanWritable evaluate(DoubleWritable num) { if (num == null) { result.set(false); } else { result.set(isInfinite(num.get())); } return result; } private boolean isInfinite(double v) { return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY); } }
29.9375
68
0.654836
8e96d3fa9651fc0b825fdd0572df604070db13b7
6,945
package com.bergerkiller.bukkit.tc.properties.standard.category; import java.util.Optional; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import com.bergerkiller.bukkit.common.config.ConfigurationNode; import com.bergerkiller.bukkit.common.utils.ParseUtil; import com.bergerkiller.bukkit.tc.Permission; import com.bergerkiller.bukkit.tc.commands.annotations.CommandTargetTrain; import com.bergerkiller.bukkit.tc.properties.TrainProperties; import com.bergerkiller.bukkit.tc.properties.api.PropertyCheckPermission; import com.bergerkiller.bukkit.tc.properties.api.PropertyInvalidInputException; import com.bergerkiller.bukkit.tc.properties.api.PropertyParser; import com.bergerkiller.bukkit.tc.properties.api.context.PropertyParseContext; import com.bergerkiller.bukkit.tc.properties.standard.fieldbacked.FieldBackedStandardTrainProperty; import com.bergerkiller.bukkit.tc.properties.standard.type.BankingOptions; import cloud.commandframework.annotations.Argument; import cloud.commandframework.annotations.CommandDescription; import cloud.commandframework.annotations.CommandMethod; /** * Configures whether a train rolls inwards when taking (sharp) turns. */ public final class BankingOptionsProperty extends FieldBackedStandardTrainProperty<BankingOptions> { @CommandTargetTrain @PropertyCheckPermission("banking") @CommandMethod("train banking <strength> <smoothness>") @CommandDescription("Sets a new train banking strength and smoothness") private void trainSetBanking( final CommandSender sender, final TrainProperties properties, final @Argument("strength") double strength, final @Argument("smoothness") double smoothness ) { properties.setBanking(strength, smoothness); trainGetBankingInfo(sender, properties); } @CommandMethod("train banking") @CommandDescription("Displays the current train banking settings") private void trainGetBankingInfo( final CommandSender sender, final TrainProperties properties ) { if (properties.getBankingStrength() == 0.0) { sender.sendMessage(ChatColor.YELLOW + "Train banking " + ChatColor.RED + "is inactive. " + ChatColor.YELLOW + "Change strength to enable."); } else { sender.sendMessage(ChatColor.YELLOW + "Train banking " + ChatColor.BLUE + "strength " + ChatColor.WHITE + properties.getBankingStrength() + ChatColor.BLUE + " smoothness " + ChatColor.WHITE + properties.getBankingSmoothness()); } } @CommandTargetTrain @PropertyCheckPermission("banking") @CommandMethod("train banking strength <strength>") @CommandDescription("Sets a new train banking strength") private void trainSetBankingStrength( final CommandSender sender, final TrainProperties properties, final @Argument("strength") double strength ) { properties.setBankingStrength(strength); trainGetBankingStrength(sender, properties); } @CommandMethod("train banking strength") @CommandDescription("Displays the currently configured train banking strength") private void trainGetBankingStrength( final CommandSender sender, final TrainProperties properties ) { if (properties.getBankingStrength() == 0.0) { sender.sendMessage(ChatColor.YELLOW + "Train banking strength: " + ChatColor.WHITE + "0 " + ChatColor.RED + "(Inactive)"); } else { sender.sendMessage(ChatColor.YELLOW + "Train banking strength: " + ChatColor.WHITE + properties.getBankingStrength()); } } @CommandTargetTrain @PropertyCheckPermission("banking") @CommandMethod("train banking smoothness <strength>") @CommandDescription("Sets a new train banking smoothness") private void trainSetBankingSmoothness( final CommandSender sender, final TrainProperties properties, final @Argument("strength") double strength ) { properties.setBankingSmoothness(strength); trainGetBankingSmoothness(sender, properties); } @CommandMethod("train banking smoothness") @CommandDescription("Displays the currently configured train banking smoothness") private void trainGetBankingSmoothness( final CommandSender sender, final TrainProperties properties ) { sender.sendMessage(ChatColor.YELLOW + "Train banking smoothness: " + ChatColor.WHITE + properties.getBankingSmoothness()); } @PropertyParser("banking") public BankingOptions parseBanking(PropertyParseContext<BankingOptions> context) { String[] args = context.input().trim().split(" "); double newStrength, newSmoothness; if (args.length >= 2) { newStrength = ParseUtil.parseDouble(args[0], Double.NaN); newSmoothness = ParseUtil.parseDouble(args[1], Double.NaN); } else { newStrength = ParseUtil.parseDouble(context.input(), Double.NaN); newSmoothness = context.current().smoothness(); } if (Double.isNaN(newStrength)) { throw new PropertyInvalidInputException("Banking strength is not a number"); } if (Double.isNaN(newSmoothness)) { throw new PropertyInvalidInputException("Banking smoothness is not a number"); } return BankingOptions.create(newStrength, newSmoothness); } @Override public boolean hasPermission(CommandSender sender, String name) { return Permission.PROPERTY_BANKING.has(sender); } @Override public BankingOptions getDefault() { return BankingOptions.DEFAULT; } @Override public BankingOptions getData(TrainInternalData data) { return data.bankingOptionsData; } @Override public void setData(TrainInternalData data, BankingOptions value) { data.bankingOptionsData = value; } @Override public Optional<BankingOptions> readFromConfig(ConfigurationNode config) { if (!config.isNode("banking")) { return Optional.empty(); } ConfigurationNode banking = config.getNode("banking"); return Optional.of(BankingOptions.create( banking.get("strength", 0.0), banking.get("smoothness", 0.0) )); } @Override public void writeToConfig(ConfigurationNode config, Optional<BankingOptions> value) { if (value.isPresent()) { BankingOptions data = value.get(); ConfigurationNode banking = config.getNode("banking"); banking.set("strength", data.strength()); banking.set("smoothness", data.smoothness()); } else { config.remove("banking"); } } }
39.685714
109
0.685529
0848150e1a2c5a4cfb487245bec54dbff154edcf
9,854
package fr.insee.kraftwerk.core.outputs; import fr.insee.kraftwerk.core.inputs.ModeInputs; import fr.insee.kraftwerk.core.inputs.UserInputs; import fr.insee.kraftwerk.core.metadata.VariablesMap; import fr.insee.kraftwerk.core.utils.TextFileWriter; import fr.insee.kraftwerk.core.vtl.VtlBindings; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Class to manage the writing of output tables. */ @Slf4j public class OutputFiles { /** Final absolute path to the batch output folder */ @Getter private final Path outputFolder; private final VtlBindings vtlBindings; private final Set<String> datasetToCreate = new HashSet<>(); /** * When an instance is created, the output folder for the concerned batch * execution is created. * * @param outDirectory Out directory defined in application properties. * @param vtlBindings Vtl bindings where datasets are stored. * @param userInputs Used to get the campaign name and to filter intermediate * datasets that we don't want to output. */ public OutputFiles(Path outDirectory, VtlBindings vtlBindings, UserInputs userInputs) { // this.vtlBindings = vtlBindings; // setOutputDatasetNames(userInputs); // outputFolder = outDirectory; // createOutputFolder(); } /** Create output folder if doesn't exist. */ private void createOutputFolder() { try { Files.createDirectories(outputFolder); log.info(String.format("Created output folder: %s", outputFolder.toFile().getAbsolutePath())); } catch (IOException e) { log.error("Permission refused to create output folder: " + outputFolder, e); } } /** See getOutputDatasetNames doc. */ private void setOutputDatasetNames(UserInputs userInputs) { Set<String> unwantedDatasets = new HashSet<>(userInputs.getModes()); for (String modeName : userInputs.getModes()) { // NOTE: deprecated code since clean up processing class unwantedDatasets.add(modeName); unwantedDatasets.add(modeName + "_keep"); // datasets created during Reconciliation step } unwantedDatasets.add(userInputs.getMultimodeDatasetName()); for (String datasetName : vtlBindings.getDatasetNames()) { if (!unwantedDatasets.contains(datasetName)) { datasetToCreate.add(datasetName); } } } /** * We don't want to output unimodal datasets and the multimode dataset. This * method return the list of dataset names to be output, that are the dataset * created during the information levels processing step (one per group), and * those that might have been created by user VTL instructions. */ public Set<String> getOutputDatasetNames() { return datasetToCreate; } /** * Method to write CSV output tables from datasets that are in the bindings. */ public void writeOutputCsvTables() { for (String datasetName : datasetToCreate) { File outputFile = outputFolder.resolve(outputFileName(datasetName)).toFile(); if (outputFile.exists()) { CsvTableWriter.updateCsvTable(vtlBindings.getDataset(datasetName), outputFolder.resolve(outputFileName(datasetName))); } else { CsvTableWriter.writeCsvTable(vtlBindings.getDataset(datasetName), outputFolder.resolve(outputFileName(datasetName))); } } } public void writeImportScripts(Map<String, VariablesMap> metadataVariables) { // ImportScripts importScripts = new ImportScripts(); // for (String datasetName : datasetToCreate) { TableScriptInfo tableScriptInfo = new TableScriptInfo(datasetName, outputFileName(datasetName), vtlBindings.getDataset(datasetName).getDataStructure(), metadataVariables); importScripts.registerTable(tableScriptInfo); } // NOTE: commented unimplemented scripts //TextFileWriter.writeFile(outputFolder.resolve("import_base.R"), importScripts.scriptR_base()); TextFileWriter.writeFile(outputFolder.resolve("import_with_data_table.R"), importScripts.scriptR_dataTable()); //TextFileWriter.writeFile(outputFolder.resolve("import_with_pandas.py"), importScripts.scriptPython_pandas()); TextFileWriter.writeFile(outputFolder.resolve("import.sas"), importScripts.scriptSAS()); } /** * Return the name of the file to be written from the dataset name. */ public String outputFileName(String datasetName) { return outputFolder.getFileName() + "_" + datasetName + ".csv"; } /** * Move the input file to another directory to archive it */ public void renameInputFile(Path inDirectory) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); File file = inDirectory.resolve("kraftwerk.json").toFile(); File file2 = inDirectory.resolve("kraftwerk-" + sdf.format(timestamp) + ".json").toFile(); if (file2.exists()) { log.warn(String.format("Trying to rename '%s' to '%s', but second file already exists.", file, file2)); log.warn("Timestamped input file will be over-written."); file2.delete(); } file.renameTo(file2); } public void moveInputFiles(UserInputs userInputs) { // Path inputFolder = userInputs.getInputDirectory(); String[] directories = inputFolder.toString().split(Pattern.quote(File.separator)); String campaignName = directories[directories.length-1]; // First we create an archive directory in case it doesn't exist if (!Files.exists(inputFolder.resolve("Archive"))) { inputFolder.resolve("Archive").toFile().mkdir(); } // for (String mode : userInputs.getModes()) { ModeInputs modeInputs = userInputs.getModeInputs(mode); // Move data file or folder in the archive Path dataPath = modeInputs.getDataFile(); Path newDataPath = inputFolder.resolve("Archive").resolve(getRoot(modeInputs.getDataFile(), campaignName)); if (!Files.exists(newDataPath)) { new File(newDataPath.getParent().toString()).mkdirs(); } // TODO: remove following code block (unused) // --------------------------------------------------------------- // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // get the last modified date and format it to the defined format // String nameNewFile = modeInputs.getDataFile().toString(); // nameNewFile = nameNewFile.substring(0, nameNewFile.lastIndexOf(".")) + "-" + sdf.format(timestamp) // + nameNewFile.substring(nameNewFile.lastIndexOf(".")); // <- throws an exception when data path is a folder (not containing "."), also might not work as expected if some folder name contains a "." // --------------------------------------------------------------- if (Files.isRegularFile(dataPath)) { try { Files.move(modeInputs.getDataFile(), newDataPath); } catch (IOException e) { log.error("Error occurred when trying to move data file or folder in the \"Archive\" directory."); log.error(e.getMessage()); } } else if (Files.isDirectory(dataPath)) { moveDirectory( dataPath.toFile(), inputFolder.resolve("Archive").resolve(getRoot(dataPath, campaignName)).toFile()); } else { log.debug(String.format("No file or directory at path: %s", dataPath)); } // If paradata, we move the paradata folder if (modeInputs.getParadataFolder() != null // TODO: simplify condition (UserInputs class shouldn't allow field content to equal "" or "null" (should be either a value or null) && !modeInputs.getParadataFolder().toString().contentEquals("") && !modeInputs.getParadataFolder().toString().contentEquals("null")) { moveDirectory( modeInputs.getParadataFolder().toFile(), inputFolder.resolve("Archive") .resolve(getRoot(modeInputs.getParadataFolder(), campaignName)).toFile()); } // If reporting data, we move reporting data files if (modeInputs.getReportingDataFile() != null // TODO: simplify condition (see above) && !modeInputs.getReportingDataFile().toString().equals("")) { if (!Files.exists(inputFolder.resolve("Archive").resolve(modeInputs.getReportingDataFile()).getParent())) { new File(getRoot(modeInputs.getReportingDataFile(), campaignName)).mkdirs(); } moveDirectory( modeInputs.getReportingDataFile().getParent().toFile(), inputFolder.resolve("Archive") .resolve(getRoot(modeInputs.getReportingDataFile(), campaignName)).toFile()); new File(modeInputs.getReportingDataFile().toString()).delete(); if (!Files.exists(inputFolder.resolve("Archive").resolve(modeInputs.getReportingDataFile()).getParent())) { } } } } private static String getRoot(Path path, String campaignName) { String[] directories = path.toString().split(Pattern.quote(File.separator)); int campaignIndex = Arrays.asList(directories).indexOf(campaignName); String[] newDirectories = Arrays.copyOfRange(directories, campaignIndex+1, directories.length); StringBuilder result = new StringBuilder(); String sep = ""; for (String directory : newDirectories) { result.append(sep).append(directory); sep = File.separator; } return result.toString(); } private static void moveDirectory(File sourceFile, File destFile) { if (sourceFile.isDirectory()) { File[] files = sourceFile.listFiles(); assert files != null; for (File file : files) moveDirectory(file, new File(destFile, file.getName())); if (!sourceFile.delete()) throw new RuntimeException(); } else { if (!destFile.getParentFile().exists()) if (!destFile.getParentFile().mkdirs()) throw new RuntimeException(); if (!sourceFile.renameTo(destFile)) throw new RuntimeException(); } } }
39.258964
203
0.717171
974b2972fdc9e252c333439c03a4c0bec53814fa
626
package com.mahogano.core.presta.mapper; import com.mahogano.core.presta.entity.Reassurance; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; public class ReassuranceMapper implements RowMapper<Reassurance> { @Override public Reassurance mapRow(ResultSet rs, int i) throws SQLException { Reassurance reassurance = new Reassurance(); reassurance.setIdReassurance(rs.getInt("id_reassurance")); reassurance.setIdShop(rs.getInt("id_shop")); reassurance.setFileName(rs.getString("file_name")); return reassurance; } }
29.809524
72
0.746006
4c4fbbcfdaa88dd87e0c9fb20206f81bfd60d66d
5,652
package org.cleancode; import java.text.ParseException; import java.util.*; public class ArgsV02 { private String schema; private String[] args; private boolean valid = true; private Set<Character> unexpectedArguments = new TreeSet<Character>(); private Map<Character, Boolean> booleanArgs = new HashMap<Character, Boolean>(); private Map<Character, String> stringArgs = new HashMap<Character, String>(); private Set<Character> argsFound = new HashSet<Character>(); private int currentArgument; private char errorArgument = '\0'; enum ErrorCode { OK, MISSING_STRING} private ErrorCode errorCode = ErrorCode.OK; public ArgsV02(String schema, String[] args) throws ParseException { this.schema = schema; this.args = args; valid = parse(); } private boolean parse() throws ParseException { if (schema.length() == 0 && args.length == 0) return true; parseSchema(); parseArguments(); return valid; } private boolean parseSchema() throws ParseException { for (String element : schema.split(",")) { if (element.length() > 0) { String trimmedElement = element.trim(); parseSchemaElement(trimmedElement); } } return true; } private void parseSchemaElement(String element) throws ParseException { char elementId = element.charAt(0); String elementTail = element.substring(1); validateSchemaElementId(elementId); if (isBooleanSchemaElement(elementTail)) parseBooleanSchemaElement(elementId); else if (isStringSchemaElement(elementTail)) parseStringSchemaElement(elementId); } private void validateSchemaElementId(char elementId) throws ParseException { if (!Character.isLetter(elementId)) { throw new ParseException( "Bad character:" + elementId + "in Args format: " + schema, 0); } } private void parseStringSchemaElement(char elementId) { stringArgs.put(elementId, ""); } private boolean isStringSchemaElement(String elementTail) { return elementTail.equals("*"); } private boolean isBooleanSchemaElement(String elementTail) { return elementTail.length() == 0; } private void parseBooleanSchemaElement(char elementId) { booleanArgs.put(elementId, false); } private boolean parseArguments() { for (currentArgument = 0; currentArgument < args.length; currentArgument++) { String arg = args[currentArgument]; parseArgument(arg); } return true; } private void parseArgument(String arg) { if (arg.startsWith("-")) parseElements(arg); } private void parseElements(String arg) { for (int i = 1; i < arg.length(); i++) parseElement(arg.charAt(i)); } private void parseElement(char argChar) { if (setArgument(argChar)) argsFound.add(argChar); else { unexpectedArguments.add(argChar); valid = false; } } private boolean setArgument(char argChar) { boolean set = true; if (isBoolean(argChar)) setBooleanArg(argChar, true); else if (isString(argChar)) setStringArg(argChar, ""); else set = false; return set; } private void setStringArg(char argChar, String s) { currentArgument++; try { stringArgs.put(argChar, args[currentArgument]); } catch (ArrayIndexOutOfBoundsException e) { valid = false; errorArgument = argChar; errorCode = ErrorCode.MISSING_STRING; } } private boolean isString(char argChar) { return stringArgs.containsKey(argChar); } private void setBooleanArg(char argChar, boolean value) { booleanArgs.put(argChar, value); } private boolean isBoolean(char argChar) { return booleanArgs.containsKey(argChar); } public int cardinality() { return argsFound.size(); } public String usage() { if (schema.length() > 0) return "-[" + schema + "]"; else return ""; } public String errorMessage() throws Exception { if (unexpectedArguments.size() > 0) { return unexpectedArgumentMessage(); } else switch (errorCode) { case MISSING_STRING: return String.format("Could not find string parameter for -%c.", errorArgument); case OK: throw new Exception("TILT: Should not get here."); } return ""; } private String unexpectedArgumentMessage() { StringBuffer message = new StringBuffer("Argument(s) -"); for (char c : unexpectedArguments) { message.append(c); } message.append(" unexpected."); return message.toString(); } public boolean getBoolean(char arg) { return falseIfNull(booleanArgs.get(arg)); } private boolean falseIfNull(Boolean b) { return b == null ? false : b; } public String getString(char arg) { return blankIfNull(stringArgs.get(arg)); } private String blankIfNull(String s) { return s == null ? "" : s; } public boolean has(char arg) { return argsFound.contains(arg); } public boolean isValid() { return valid; } }
33.052632
84
0.592711
b218dc54bac061db81bd2261ca09962c5050acf3
1,138
package vip.mate.gateway.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; /** * Nacos路由工具类配置 * @author pangu */ @Configuration public class NacosGatewayConfig { public static final long DEFAULT_TIMEOUT = 30000; public static String NACOS_SERVER_ADDR; public static String NACOS_NAMESPACE; public static String NACOS_ROUTE_DATA_ID; public static String NACOS_ROUTE_GROUP; @Value("${spring.cloud.nacos.discovery.server-addr}") public void setNacosServerAddr(String nacosServerAddr){ NACOS_SERVER_ADDR = nacosServerAddr; } @Value("${spring.cloud.nacos.discovery.namespace}") public void setNacosNamespace(String nacosNamespace){ NACOS_NAMESPACE = nacosNamespace; } @Value("${mate.route.config.data-id}") public void setNacosRouteDataId(String nacosRouteDataId){ NACOS_ROUTE_DATA_ID = nacosRouteDataId + ".json"; } @Value("${mate.route.config.group}") public void setNacosRouteGroup(String nacosRouteGroup){ NACOS_ROUTE_GROUP = nacosRouteGroup; } }
26.465116
61
0.734622
97b745acc8f855b8b094952f1b9589c8e4c1f010
303
package loteria; //Em desenvolvimento.... public class SistemaLoterica { public static void main(String[] args) { LotericaInterna loterica = new LotericaInterna(); Usuario u1 = new Usuario(); loterica.premiacao(loterica.compararJogo(loterica.sorteio(), u1.fazerJogo(u1.escolha()))); } }
16.833333
92
0.722772
9f9e06301b0dcb13016861bdf7c6a3383386d804
7,692
import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.Timer; public class Logica implements ILogica { Jogo jogo; public boolean jogando; public List<Player> players = null; public Enemy[][] enemies = new Enemy[17][13]; public int enemyCount = 0; Logica(IJogo jogo) { this.jogo = (Jogo) jogo; } public void executa() { AtomicBoolean roda = new AtomicBoolean(true); this.players = new ArrayList<>(); this.players.add(new Player(0, 3)); this.players.add(new Player(16, 3)); this.jogo.sendCommand(0, "READY", new String[] { "P1", "" + this.players.get(0).x, "" + this.players.get(0).y, "" + this.players.get(1).x, "" + this.players.get(1).y, "" + this.jogo.segundos }); this.jogo.sendCommand(1, "READY", new String[] { "P2", "" + this.players.get(1).x, "" + this.players.get(1).y, "" + this.players.get(0).x, "" + this.players.get(0).y, "" + this.jogo.segundos }); Timer en = new Timer(2000, (ae) -> { if (!roda.get()) { ((Timer) ae.getSource()).stop(); return; } this.doEnemiesHit(); }); Timer jogo = new Timer(1000, (ae) -> { if (!roda.get()) { ((Timer) ae.getSource()).stop(); return; } if (this.jogo.segundos > 0) { this.jogo.segundos--; } else { roda.set(false); ((Timer) ae.getSource()).stop(); } }); Timer t = new Timer(10000, (ae) -> { if (!roda.get()) { ((Timer) ae.getSource()).stop(); return; } Enemy enemy = this.spawnEnemy(); if (enemy == null) { return; } enemies[enemy.x][enemy.y] = enemy; this.jogo.sendCommand(0, "SPAWNENEMY", new String[] { "" + enemy.x, "" + enemy.y }); this.jogo.sendCommand(1, "SPAWNENEMY", new String[] { "" + enemy.x, "" + enemy.y }); }); en.start(); t.start(); jogo.start(); new Thread(() -> { while (this.jogo.clienteVivo[0] && this.jogo.clienteVivo[1] && this.jogo.segundos > 0 && roda.get()) { // } System.out.println("Fim de jogo"); roda.set(false); int P1pontos = this.players.get(0).score; int P2pontos = this.players.get(1).score; if (this.jogo.clienteVivo[0] && this.jogo.clienteVivo[1]) { if (P1pontos == P2pontos) { this.jogo.sendCommand(0, "END", new String[] { "D" }); this.jogo.sendCommand(1, "END", new String[] { "D" }); } else { this.jogo.sendCommand(0, "END", new String[] { P1pontos > P2pontos ? "P1" : "P2" }); this.jogo.sendCommand(1, "END", new String[] { P1pontos > P2pontos ? "P2" : "P1" }); } } else if (this.jogo.clienteVivo[0]) { this.jogo.sendCommand(0, "END", new String[] { "P1" }); this.jogo.sendCommand(1, "END", new String[] { "P2" }); } else { this.jogo.sendCommand(0, "END", new String[] { "P2" }); this.jogo.sendCommand(1, "END", new String[] { "P1" }); } }).start(); } public int getDamage() { return (int) Math.ceil(5 + Math.random() * (10 - 5)); } public boolean colide(int player, int x, int y) { return x < 0 || x > 16 || y < 3 || y > 12 || (x == this.players.get(1 - player).x && y == this.players.get(1 - player).y) || this.enemies[x][y] != null; } public boolean movePlayer(int player, int dx, int dy) { Player p = this.players.get(player); p.x += dx; p.y += dy; if (dx == 0 && dy < 0) { p.direction = "up"; } else if (dx == 0 && dy > 0) { p.direction = "down"; } else if (dx < 0 && dy == 0) { p.direction = "left"; } else if (dx > 0 && dy == 0) { p.direction = "right"; } if (this.colide(player, p.x, p.y)) { p.x -= dx; p.y -= dy; } return true; } public boolean hitEnemy(int numJogador, int x, int y, int damage) { if (x < 0 || x > 16 || y < 3 || y > 12 || this.enemies[x][y] == null) { return false; } this.enemies[x][y].life -= damage; if (this.enemies[x][y].life <= 0) { this.enemies[x][y] = null; this.enemyCount--; this.players.get(numJogador).score += 10; if (numJogador == 0) { this.jogo.sendCommand(0, "ENEMYKILL", new String[] { "P1" }); this.jogo.sendCommand(1, "ENEMYKILL", new String[] { "P2" }); } else { this.jogo.sendCommand(0, "ENEMYKILL", new String[] { "P2" }); this.jogo.sendCommand(1, "ENEMYKILL", new String[] { "P1" }); } } return true; } public Enemy spawnEnemy() { if (this.enemyCount == 17 * 10 - 3) { return null; } int x = 0; int y = 0; do { x = (int) Math.ceil(0 + Math.random() * (16 - 0)); y = (int) Math.ceil(3 + Math.random() * (12 - 3)); } while (this.enemies[x][y] != null || (this.players.get(0).x == x && this.players.get(0).y == y) || (this.players.get(1).x == x && this.players.get(1).y == y)); this.enemyCount++; return new Enemy(x, y); } public void doEnemiesHit() { int P1x = this.players.get(0).x; int P1y = this.players.get(0).y; if (this.jogo.clienteVivo[0]) { for (int x = P1x - 1; x <= P1x + 1; x++) { for (int y = P1y - 1; y <= P1y + 1; y++) { if (x > 0 && x < 17 && y > 2 && y < 13 && this.enemies[x][y] != null) { int damage = this.getDamage(); this.players.get(0).life -= damage; if (this.players.get(0).life < 0) { this.jogo.clienteVivo[0] = false; } this.jogo.sendCommand(0, "ENEMYHIT", new String[] { "P1", "" + damage, "" + x, "" + y }); this.jogo.sendCommand(1, "ENEMYHIT", new String[] { "P2", "" + damage, "" + x, "" + y }); break; } } } } int P2x = this.players.get(1).x; int P2y = this.players.get(1).y; if (this.jogo.clienteVivo[1]) { for (int x = P2x - 1; x <= P2x + 1; x++) { for (int y = P2y - 1; y <= P2y + 1; y++) { if (x > 0 && x < 17 && y > 2 && y < 13 && this.enemies[x][y] != null) { int damage = this.getDamage(); this.players.get(0).life -= damage; if (this.players.get(0).life < 0) { this.jogo.clienteVivo[0] = false; } this.jogo.sendCommand(0, "ENEMYHIT", new String[] { "P2", "" + damage, "" + x, "" + y }); this.jogo.sendCommand(1, "ENEMYHIT", new String[] { "P1", "" + damage, "" + x, "" + y }); break; } } } } } }
33.885463
118
0.432657
85f945ba23c8cd2b9957cc29041c524a5960061b
2,312
package ru.stqa.pft.mantis.tests; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import ru.lanwen.verbalregex.VerbalExpression; import ru.stqa.pft.mantis.appmanager.DbHelper; import ru.stqa.pft.mantis.appmanager.HttpSession; import ru.stqa.pft.mantis.model.MailMessage; import ru.stqa.pft.mantis.model.UserData; import ru.stqa.pft.mantis.model.Users; import javax.mail.MessagingException; import java.io.IOException; import java.sql.*; import java.util.List; import static org.testng.Assert.assertTrue; public class ChangePassTests extends TestBase{ public void startMailServer(){ app.mail().start(); } @Test public void testLogin() throws IOException, MessagingException, InterruptedException { UserData user = DbHelper.testDbConnection(); String username = user.getUsername(); String email = user.getEmail(); String password = "password"; String newpassword = "newpassword"; String adminname = app.getProperty("web.adminLogin"); String adminpwd = app.getProperty("web.adminPassword"); HttpSession session = app.newSession(); app.changePass().admLogin(adminname, adminpwd); app.changePass().gotoReset(); app.changePass().selectUser(username); app.james().doesUserExist(username); app.changePass().resetPassword(); app.changePass().logout(); List<MailMessage> mailMessages = app.james().waitForMail(username, password, 60000); String confirmationLink = findConfirmationLink(mailMessages, email); System.out.println(confirmationLink); app.changePass().finishPwdReset(confirmationLink, newpassword, username); app.changePass().loginAsUser(username, newpassword); assertTrue(session.isLoggedInAs(username)); } private String findConfirmationLink(List<MailMessage> mailMessages, String email) { MailMessage mailMessage = mailMessages.stream().filter((m) -> m.to.equals(email)).findFirst().get(); VerbalExpression regex = VerbalExpression.regex() .find("http://").nonSpace().oneOrMore().build(); return regex.getText(mailMessage.text); } @AfterMethod(alwaysRun = true) public void stopMailServer(){ app.mail().stop(); } }
39.186441
108
0.703287
a2ddb7dbe6f61d0bd75a40a45f4015309c4eca49
688
package frc.robot.auto; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.DriveSubsystem; public class StopTrajectory extends CommandBase { private DriveSubsystem robotDrive; public StopTrajectory(DriveSubsystem robotDrive) { this.robotDrive = robotDrive; } @Override public void initialize() { System.out.println("Stopping Trajectory"); // robotDrive.drive(0, 0, 0, false); robotDrive.setWheelSpeed(0.0); } @Override public void execute() { } @Override public void end(boolean interrupted) { } @Override public boolean isFinished() { return true; } }
20.235294
54
0.664244
11ea72a3ddb0c699b40cf072abfc5694c26fe0f6
393
package co.paystack.android.api.model; import com.google.gson.annotations.SerializedName; /** * An API response always includes a status and a message */ public class ApiResponse extends BaseApiModel { @SerializedName("status") public String status; @SerializedName("message") public String message; @SerializedName("errors") public boolean hasErrors = false; }
20.684211
57
0.73028
790319b08e39fa5ede6eea875012f11aca37e4a1
557
package com.andyadc.codeblocks.common.event; import java.util.concurrent.Executor; import java.util.concurrent.ForkJoinPool; /** * Parallel {@link EventDispatcher} implementation uses {@link ForkJoinPool#commonPool() JDK common thread pool} * * @see ForkJoinPool#commonPool() */ public class ParallelEventDispatcher extends AbstractEventDispatcher { public static final String NAME = "parallel"; public ParallelEventDispatcher(Executor executor) { super(executor); } public ParallelEventDispatcher() { this(ForkJoinPool.commonPool()); } }
24.217391
112
0.777379
80384f1412ffcef93fdb169a9e2c6f1bc4a618ca
7,801
/* * Copyright (c) 2012-2017 ZoxWeb.com LLC. * * 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.zoxweb.shared.security.shiro; import java.util.Date; import org.zoxweb.shared.data.TimeStampDAO; import org.zoxweb.shared.util.CRUD; import org.zoxweb.shared.util.Const.Status; import org.zoxweb.shared.util.NVConfigEntity.ArrayType; import org.zoxweb.shared.util.GetNVConfig; import org.zoxweb.shared.util.NVConfig; import org.zoxweb.shared.util.NVConfigEntity; import org.zoxweb.shared.util.NVConfigEntityLocal; import org.zoxweb.shared.util.NVConfigManager; import org.zoxweb.shared.util.NVEntity; import org.zoxweb.shared.util.SharedUtil; /** * */ @SuppressWarnings("serial") public class ShiroAssociationRuleDAO extends TimeStampDAO { public enum Param implements GetNVConfig { ASSOCIATE(NVConfigManager.createNVConfig("associate", "The object to associate", "Associate", true, false, false, true, true, String.class, null)), REFERENCE_TYPE(NVConfigManager.createNVConfig("reference_type", "The type of the object associate", "ReferenceType", false, false, false, true, false, String.class, null)), ASSOCIATION_CRUD(NVConfigManager.createNVConfig("crud", "crud", "CRUD", true, true, CRUD.class)), ASSOCIATED_TO(NVConfigManager.createNVConfig("associated_to", "The object associated with", "AssociatedTo", true, false, false, true, false, String.class, null)), ASSOCIATION_STATUS(NVConfigManager.createNVConfig("association_status", "Association status", "AssociationStatus", true, true, Status.class)), ASSOCIATION_TYPE(NVConfigManager.createNVConfig("association_type", "Association type", "AssociationType", true, true, ShiroAssociationType.class)), EXPIRATION(NVConfigManager.createNVConfig("expiration", "Expiration date if set", "Expiration", true, true, Date.class)), PATTERN(NVConfigManager.createNVConfig("pattern", "Shiro compatible pattern", "Pattern", true, true, String.class)), ASSOCIATION(NVConfigManager.createNVConfigEntity("association", "The shiro association permission or role", "Association", false, false, ShiroDomainDAO.class, ArrayType.NOT_ARRAY)), ; private final NVConfig nvc; Param(NVConfig nvc) { this.nvc = nvc; } public NVConfig getNVConfig() { return nvc; } } /** * This NVConfigEntity type constant is set to an instantiation of a NVConfigEntityLocal object based on UserIDDAO. */ public static final NVConfigEntity NVC_SHIRO_ASSOCIATION_RULE_DAO = new NVConfigEntityLocal("shiro_association_rule_dao", null , "ShiroAssociationRuleDAO", true, false, false, false, ShiroAssociationRuleDAO.class, SharedUtil.extractNVConfigs(Param.values()), null, false, TimeStampDAO.NVC_TIME_STAMP_DAO); private String dynamicPattern; public ShiroAssociationRuleDAO() { super(NVC_SHIRO_ASSOCIATION_RULE_DAO); setExpiration(null); } public ShiroAssociationRuleDAO(String name, NVEntity associate, NVEntity associatedTo, Status status, ShiroAssociationType at, Date expiration, CRUD crud) { this(name, associate != null ? associate.getReferenceID() : null, associate != null ? associate.getClass().getName() : null, associatedTo != null ? associatedTo.getReferenceID() : null, status, at, expiration, crud); } public ShiroAssociationRuleDAO(String name, String associate, String associateRefType, String associatedTo, Status status, ShiroAssociationType at, Date expiration, CRUD crud) { this(); SharedUtil.checkIfNulls("Null parameters", name, associate, associatedTo, at, crud); setName(name); setAssociate(associate); setAssociatedTo(associatedTo); setAssociationType(at); setExpiration(expiration); setReferenceType(associateRefType); setCRUD(crud); if (status == null) { status = Status.ACTIVE; } setAssociationStatus(status); } public ShiroAssociationRuleDAO(String name, ShiroDomainDAO associate, ShiroAssociationType at, NVEntity associateTo) { this(); SharedUtil.checkIfNulls("Null parameters", name, associate, at, associateTo); if(associate == associateTo || associate.equals(associateTo)) { throw new IllegalArgumentException("Invalid association rule"); } setName(name); setAssociatedTo(associateTo.getReferenceID()); setAssociationType(at); setExpiration(null); setAssociationStatus(Status.ACTIVE); setAssociation(associate); } public ShiroAssociationType getAssociationType() { return lookupValue(Param.ASSOCIATION_TYPE); } @Override public void setName(String name) { if (name != null) { name = name.toLowerCase(); } super.setName(name); } public void setAssociationType(ShiroAssociationType assType) { setValue(Param.ASSOCIATION_TYPE, assType); } public String getAssociate() { return lookupValue(Param.ASSOCIATE); } public void setAssociate(String associate) { setValue(Param.ASSOCIATE, associate); } public String getReferenceType() { return lookupValue(Param.REFERENCE_TYPE); } public void setReferenceType(String associateRefType) { setValue(Param.REFERENCE_TYPE, associateRefType); } public String getAssociatedTo() { return lookupValue(Param.ASSOCIATED_TO); } public void setAssociatedTo(String associatedTo) { setValue(Param.ASSOCIATED_TO, associatedTo); } public String getPattern() { String ret = lookupValue(Param.PATTERN); if (ret == null) { return getDynamicPattern(); } return ret; } public void setPattern(String pattern) { setValue(Param.PATTERN, pattern); } public CRUD getCRUD() { return lookupValue(Param.ASSOCIATION_CRUD); } public void setCRUD(CRUD crud) { setValue(Param.ASSOCIATION_CRUD, crud); } public Date getExpiration() { Long val = lookupValue(Param.EXPIRATION); if (val == null || val == -1) { return null; } return new Date(val); } public void setExpiration(Date date) { if (date == null) { setValue(Param.EXPIRATION, (long)-1); } else { setValue(Param.EXPIRATION, date.getTime()); } } public Status getAssociationStatus() { return lookupValue(Param.ASSOCIATION_STATUS); } public void setAssociationStatus(Status status) { setValue(Param.ASSOCIATION_STATUS, status); } private synchronized String getDynamicPattern() { if (dynamicPattern == null) { switch(getAssociationType()) { case PERMISSION_TO_ROLE: break; case PERMISSION_TO_SUBJECT: dynamicPattern = SharedUtil.toCanonicalID(':', getName(), getCRUD(), getAssociate()).toLowerCase(); case ROLEGROUP_TO_SUBJECT: break; case ROLE_TO_ROLEGROUP: break; case ROLE_TO_SUBJECT: break; case PERMISSION_TO_RESOURCE: break; case ROLE_TO_RESOURCE: break; } } return dynamicPattern; } public <V extends ShiroDomainDAO> V getAssociation() { return lookupValue(Param.ASSOCIATION); } public <V extends ShiroDomainDAO> void setAssociation(V association) { setValue(Param.ASSOCIATION, association); setAssociate(association.getReferenceID()); } }
27.761566
307
0.716318
640fad4fd883ab83a0158274b423dfbffbb1d89a
1,485
package com.oregonstate.snooze.service.impl; import com.oregonstate.snooze.model.Group; import com.oregonstate.snooze.service.GroupService; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath*:/*.xml"}) public class GroupServiceImplTest { private Group group; @Resource @Autowired private GroupService groupService; @Before public void setUp() { group = new Group(); group.setGroupName("testGroupName"); } @After public void tearDown() { // test delete assertEquals(1, groupService.deleteByPrimaryKey(group.getGroupId())); } @Test public void groupServiceTest() { assertEquals(1, groupService.insert(group)); //Group select assertNotNull(groupService.selectByPrimaryKey(group.getGroupId())); //test update group.setGroupName("newGroupName"); groupService.updateByPrimaryKey(group); assertEquals("newGroupName", groupService.selectByPrimaryKey(group.getGroupId()).getGroupName()); } }
27.5
105
0.73468
775a728e3906da483b5e1fb6b657083b3ce331b5
1,854
package manggo.com.downloadutil; import android.app.Activity; import android.app.DownloadManager; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.webkit.URLUtil; //import com.tencent.smtt.sdk.URLUtil; import static android.content.Context.DOWNLOAD_SERVICE; public class DownloadUtil extends Thread { public void download(String url, String contentDisposition, String mimeType, Activity activity) { // 指定下载地址 DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); // 允许媒体扫描,根据下载的文件类型被加入相册、音乐等媒体库 request.allowScanningByMediaScanner(); // 设置通知的显示类型,下载进行时和完成后显示通知 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // 设置通知栏的标题,如果不设置,默认使用文件名 // request.setTitle("This is title"); // 设置通知栏的描述 request.setDescription("This is description"); // 允许在计费流量下下载 request.setAllowedOverMetered(false); // 允许该记录在下载管理界面可见 request.setVisibleInDownloadsUi(false); // 允许漫游时下载 request.setAllowedOverRoaming(true); // 允许下载的网路类型 request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); // 设置下载文件保存的路径和文件名 String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType); Log.e("fileName:{}", fileName); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); // 另外可选一下方法,自定义下载路径 // request.setDestinationUri() // request.setDestinationInExternalFilesDir() final DownloadManager downloadManager = (DownloadManager)activity.getSystemService(DOWNLOAD_SERVICE); // 添加一个下载任务 long downloadId = downloadManager.enqueue(request); Log.e("downloadId:{}", downloadId+""); } }
37.836735
109
0.71521
5413172a5aa6f7d1b8ed56cbb8c728cbbe688793
2,929
package com.daemonize.daemonengine.implementations; import com.daemonize.daemonengine.DaemonState; import com.daemonize.daemonengine.EagerDaemon; import com.daemonize.daemonengine.SideQuestDaemon; import com.daemonize.daemonengine.consumer.Consumer; import com.daemonize.daemonengine.quests.SideQuest; import com.daemonize.daemonengine.quests.BaseQuest; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SideQuestDaemonEngine extends BaseDaemonEngine<SideQuestDaemonEngine> implements SideQuestDaemon<SideQuestDaemonEngine>, EagerDaemon<SideQuestDaemonEngine> { private volatile SideQuest currentSideQuest; private final Lock sideQuestLock = new ReentrantLock(); private final Condition sideQuestCondition = sideQuestLock.newCondition(); public SideQuestDaemonEngine(){ super(); } public <T, Q extends SideQuest<T>> Q setSideQuest(Consumer consumer, final Q sideQuest) { setSideQuest(sideQuest.setConsumer(consumer)); return sideQuest; } @Override public void setSideQuest(SideQuest quest) { sideQuestLock.lock(); if (getState().equals(DaemonState.SIDE_QUEST)) clearAndInterrupt(); else { if (currentSideQuest == null) sideQuestCondition.signal(); } currentSideQuest = quest; sideQuestLock.unlock(); } @Override public SideQuest getSideQuest() { return currentSideQuest; } @Override protected BaseQuest getQuest() { sideQuestLock.lock(); try { while (currentSideQuest == null) { setDaemonState(DaemonState.IDLE); sideQuestCondition.await(); } } catch (InterruptedException ex) { } finally { sideQuestLock.unlock(); } return currentSideQuest; } @Override public SideQuestDaemonEngine clear() { return this; } @Override protected boolean runQuest(BaseQuest quest) { if(!quest.run()) { sideQuestLock.lock(); currentSideQuest = null; sideQuestLock.unlock(); } return true; } @Override protected void cleanUp() { sideQuestLock.lock(); currentSideQuest = null; sideQuestLock.unlock(); } @Override public void stop() { sideQuestLock.lock(); if (currentSideQuest == null) sideQuestCondition.signal(); sideQuestLock.unlock(); super.stop(); } @Override public SideQuestDaemonEngine interrupt() { if (!daemonState.equals(DaemonState.STOPPED) && !daemonState.equals(DaemonState.IDLE)) { if (daemonThread != null && !Thread.currentThread().equals(daemonThread) && daemonThread.isAlive()) { daemonThread.interrupt(); } } return this; } @Override public SideQuestDaemonEngine clearAndInterrupt() { sideQuestLock.lock(); currentSideQuest = null; sideQuestLock.unlock(); return interrupt(); } }
24.408333
170
0.70297
a2abead202c673f99e76ddefc23fe65e7bdc4155
327
package com.microsoft.conference.management.domain.Models; public class SeatAvailableQuantity { public String SeatTypeId; public int AvailableQuantity; public SeatAvailableQuantity(String seatTypeId, int availableQuantity) { SeatTypeId = seatTypeId; AvailableQuantity = availableQuantity; } }
27.25
76
0.75841
dbabdcddc82549061eee5bf18c77f956dfe08651
3,243
package rapaio.data.filter.var; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import rapaio.data.Var; import rapaio.data.VarBinary; import rapaio.data.VarDouble; import rapaio.data.VarInt; import rapaio.data.VarLong; import rapaio.data.VarNominal; /** * Created by <a href="mailto:[email protected]">Aurelian Tutuianu</a> on 9/28/18. */ public class VToIntTest { @Rule public final ExpectedException expectedException = ExpectedException.none(); @Test public void testToInt() { Var num1 = VarDouble.wrap(1.0, 2.0, 1.2, Double.NaN, 3.0, Double.NaN, 3.2); Var nom1 = VarNominal.copy("1", "2", "1.2", "?", "3", "?", "4"); Var nom2 = VarNominal.copy("1", "2", "1.2", "mimi", "3", "lulu", "3.2"); Var idx1 = VarInt.copy(1, 2, 3, Integer.MIN_VALUE, 3, Integer.MIN_VALUE, 4); Var bin1 = VarBinary.copy(1, 0, 1, -1, 1, -1, 0); // by default transformer Assert.assertTrue(VarInt.wrap(1, 2, 1, Integer.MIN_VALUE, 3, Integer.MIN_VALUE, 3) .deepEquals(num1.fapply(VToInt.byDefault()))); Assert.assertTrue(VarInt.wrap(1, 2, Integer.MIN_VALUE, Integer.MIN_VALUE, 3, Integer.MIN_VALUE, 4) .deepEquals(nom1.fapply(VToInt.byDefault()))); Assert.assertTrue(VarInt.wrap(1, 2, Integer.MIN_VALUE, Integer.MIN_VALUE, 3, Integer.MIN_VALUE, Integer.MIN_VALUE) .deepEquals(nom2.fapply(VToInt.byDefault()))); Assert.assertTrue(VarInt.wrap(1, 2, 3, Integer.MIN_VALUE, 3, Integer.MIN_VALUE, 4) .deepEquals(idx1.fapply(VToInt.byDefault()))); Assert.assertTrue(VarInt.wrap(1, 0, 1, Integer.MIN_VALUE, 1, Integer.MIN_VALUE, 0) .deepEquals(bin1.fapply(VToInt.byDefault()))); // by spot transformer Assert.assertTrue(VarInt.wrap(1, 1, 1, 0, 1, 0, 1) .deepEquals(num1.fapply(VToInt.bySpot(s -> s.isMissing() ? 0 : 1)))); // by value transformer Assert.assertTrue(VarInt.wrap(1, 2, 1, Integer.MIN_VALUE, 3, Integer.MIN_VALUE, 3) .deepEquals(num1.fapply(VToInt.fromDouble(x -> Double.isNaN(x) ? Integer.MIN_VALUE : Double.valueOf(x).intValue())))); // by index transformer Assert.assertTrue(VarInt.wrap(1, 2, 3, Integer.MIN_VALUE, 3, Integer.MIN_VALUE, 4) .deepEquals(idx1.fapply(VToInt.fromInt(x -> x)))); // by label transformer Assert.assertTrue(VarInt.wrap(1, 2, Integer.MIN_VALUE, Integer.MIN_VALUE, 3, Integer.MIN_VALUE, 4) .deepEquals(nom1.fapply(VToInt.byLabel(txt -> { if (txt.equals("?")) return Integer.MIN_VALUE; try { return Integer.parseInt(txt); } catch (NumberFormatException e) { return Integer.MIN_VALUE; } })))); } @Test public void testUnsupportedLongToDouble() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Variable type: long is not supported."); VarLong.wrap(1, 2, 3).fapply(VToInt.byDefault()); } }
39.072289
134
0.612704
6fa568b662ee4f72afa71d615bb6e2c073357372
2,866
package com.openvehicletracking.collector.verticle; import com.openvehicletracking.collector.AppConstants; import com.openvehicletracking.collector.Config; import com.openvehicletracking.collector.database.MongoCollection; import com.openvehicletracking.collector.database.Record; import com.openvehicletracking.core.CacheKeyGenerator; import com.openvehicletracking.core.DeviceState; import com.openvehicletracking.core.exception.StateCreateNotSupportException; import com.openvehicletracking.core.protocol.Message; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import io.vertx.core.net.NetSocket; import io.vertx.redis.RedisClient; import io.vertx.redis.RedisOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Objects; public class MessageProcessorVerticle extends AbstractMessageProcessorVerticle { private static Logger LOGGER = LoggerFactory.getLogger(TcpVerticle.class); private RedisClient redisClient; public MessageProcessorVerticle(NetSocket socket) { super(socket); } @Override public void handler(Buffer buffer) { Message deviceMessage = getMessage(buffer); if (deviceMessage == null) { return; } JsonObject message = createJsonMessage(deviceMessage); if (message != null) { vertx.eventBus().<JsonObject>send(AppConstants.Events.PERSIST, new Record(MongoCollection.MESSAGES, message), result -> { LOGGER.info(result.result().body().encodePrettily()); }); } DeviceState state = null; try { state = deviceMessage.createState(); } catch (StateCreateNotSupportException ignored) {} if (state == null || device == null) { LOGGER.info("State or device is null, device: {}, state: {}", device, state); return; } final String stateAsJson = state.asJson(); redisClient.set(CacheKeyGenerator.stateCacheKey(device.getId()), stateAsJson, handler -> { if (handler.succeeded()) { LOGGER.debug("state write for deviceId: {}, state: {}, result: {}", device.getId(), stateAsJson, handler.result()); } }); } @Override public void start() throws Exception { super.start(); RedisOptions redisOptions = new RedisOptions(); redisOptions.setHost(Config.getInstance().getString("cache.redis.host", "localhost")) .setPort(Config.getInstance().getInt("cache.redis.port", 6379)) .setEncoding("UTF-8"); redisClient = RedisClient.create(vertx, redisOptions); } @Override public void stop() throws Exception { super.stop(); redisClient.close(handler -> LOGGER.debug("redis connection closed for device {}", device.getId())); } }
35.382716
133
0.680391
af1100feb72029b7e05e5215db82df08c479c47c
992
package com.mastering.spring.springboot.configuration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties("application") public class ApplicationConfiguration { private boolean enableSwitchForService1; private String service1Url; private int service1Timeout; public boolean isEnableSwitchForService1() { return enableSwitchForService1; } public void setEnableSwitchForService1(boolean enableSwitchForService1) { this.enableSwitchForService1 = enableSwitchForService1; } public String getService1Url() { return service1Url; } public void setService1Url(String service1Url) { this.service1Url = service1Url; } public int getService1Timeout() { return service1Timeout; } public void setService1Timeout(int service1Timeout) { this.service1Timeout = service1Timeout; } }
26.810811
77
0.75
09a7f8df5606ce0d4a0fe5db8ab1f6d6b8be7a7f
524
package com.moon.lang.ref; import com.moon.lang.reflect.ConstructorUtil; import com.moon.util.assertions.Assertions; import org.junit.jupiter.api.Test; import java.util.WeakHashMap; /** * @author benshaoye */ class WeakMapManagerTestTest { static final Assertions assertions = Assertions.of(); @Test void testManage() { assertions.assertThrows(() -> ConstructorUtil.newInstance(WeakMapManager.class, true)); assertions.assertThrows(() -> WeakMapManager.manage(new WeakHashMap<>())); } }
26.2
95
0.725191
f90d5f3472a8b4aba8b292834b00c944029bb168
1,892
package com.chappie.engine.math; public class Vector2i { private int x,y; public Vector2i(int x, int y) { this.x = x; this.y = y; } public Vector2i(int val) { this.x = val; this.y = val; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public String toString() { return "[" + x + "; " + y + "]"; } public void add(Vector2f other) { x += other.getX(); y += other.getY(); } public void subtract(Vector2f other) { x -= other.getX(); y -= other.getY(); } public void addX(int xt) { x += xt; } public void addY(int yt) { y += yt; } public Vector2f asVector2f() { return new Vector2f(x,y); } public float getMagnitude() { return (float) Math.sqrt(Math.pow(x, 2)+Math.pow(y, 2)); } public static boolean equals(Vector2i first, Vector2i second) { return (first.getX() == second.getX())&&(first.getY() == second.getY()); } public static Vector2i getSum(Vector2i f, Vector2i s) { return new Vector2i(f.getX()+s.getX(), f.getY()+s.getY()); } public static Vector2i getDifference(Vector2i f, Vector2i s) { return new Vector2i(f.getX()-s.getX(), f.getY()-s.getY()); } public static Vector2i getDivision(Vector2i f, Vector2i s) { return new Vector2i(f.getX()/s.getX(), f.getY()/s.getY()); } public static Vector2i getDivision(Vector2f f, Vector2i s) { return new Vector2i((int)f.getX()/s.getX(), (int)f.getY()/s.getY()); } public static Vector2i getProduct(Vector2i f, Vector2i s) { return new Vector2i(f.getX()*s.getX(), f.getY()*s.getY()); } public static double getDistance(Vector2i f, Vector2i s) { return Math.sqrt(Math.pow(s.getX()-f.getX(), 2)+Math.pow(s.getY()-f.getY(), 2)); } }
20.565217
83
0.588266
9730ccb5b29ee4a33c8191cc5ce76d84a03f2226
413
package com.javatest.eurekaclient; import com.fasterxml.jackson.annotation.JsonAutoDetect; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) public class Abc { private String dDAb; private String vvA; }
22.944444
115
0.823245
e88639f83f3ba5af847db3b35c42c439405c632d
36,876
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2002-2018 Hitachi Vantara. All rights reserved. */ package org.pentaho.platform.dataaccess.datasource.wizard.service.impl; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.when; import static org.mockito.Mockito.never; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.argThat; import static org.mockito.Mockito.matches; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.times; import java.sql.Connection; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.TreeSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertArrayEquals; import org.junit.After; import org.junit.Before; import org.mockito.ArgumentMatcher; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.pentaho.agilebi.modeler.ModelerException; import org.pentaho.agilebi.modeler.ModelerPerspective; import org.pentaho.agilebi.modeler.ModelerWorkspace; import org.pentaho.commons.connection.IPentahoConnection; import org.pentaho.commons.connection.IPentahoResultSet; import org.pentaho.database.model.DatabaseConnection; import org.pentaho.database.model.DatabaseType; import org.pentaho.database.model.IDatabaseConnection; import org.pentaho.database.model.IDatabaseType; import org.pentaho.metadata.model.Domain; import org.pentaho.metadata.model.LogicalModel; import org.pentaho.metadata.model.SqlDataSource; import org.pentaho.metadata.model.SqlPhysicalModel; import org.pentaho.metadata.model.SqlPhysicalTable; import org.pentaho.metadata.model.concept.types.LocaleType; import org.pentaho.metadata.repository.DomainAlreadyExistsException; import org.pentaho.metadata.repository.DomainIdNullException; import org.pentaho.metadata.repository.DomainStorageException; import org.pentaho.metadata.repository.IMetadataDomainRepository; import org.pentaho.platform.api.engine.IPentahoObjectFactory; import org.pentaho.platform.api.engine.IPentahoSession; import org.pentaho.platform.dataaccess.datasource.DatasourceType; import org.pentaho.platform.dataaccess.datasource.beans.BusinessData; import org.pentaho.platform.dataaccess.datasource.beans.LogicalModelSummary; import org.pentaho.platform.dataaccess.datasource.beans.SerializedResultSet; import org.pentaho.platform.dataaccess.datasource.wizard.models.CsvFileInfo; import org.pentaho.platform.dataaccess.datasource.wizard.models.DatasourceDTO; import org.pentaho.platform.dataaccess.datasource.wizard.models.DatasourceModel; import org.pentaho.platform.dataaccess.datasource.wizard.models.ModelInfo; import org.pentaho.platform.dataaccess.datasource.wizard.service.DatasourceServiceException; import org.pentaho.platform.dataaccess.datasource.wizard.service.SqlQueriesNotSupportedException; import org.pentaho.platform.dataaccess.datasource.wizard.sources.query.QueryDatasourceSummary; import org.pentaho.platform.engine.core.TestObjectFactory; import org.pentaho.platform.engine.core.system.PentahoSessionHolder; import org.pentaho.platform.engine.core.system.PentahoSystem; import org.pentaho.platform.plugin.action.mondrian.catalog.IMondrianCatalogService; import org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalog; import org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalogServiceException; import org.pentaho.platform.plugin.services.connections.sql.SQLConnection; import org.pentaho.platform.plugin.services.connections.sql.SQLMetaData; import org.junit.Test; public class DSWDatasourceServiceImplTest { private static final String CONNECTION_NAME = "[connection 接続 <;>!@#$%^&*()_-=+.,]"; private static final String DB_TYPE = "jdbc"; private static final String VALID_QUERY = "valid query"; private static final String QUERY_COLUMN_ALREADY_EXIST = "invalid query"; private static final String PREVIEW_LIMIT = "100"; private static final String DOMAIN_ID_2MODELS = "DOMAIN_ID_2MODELS"; private static final String DOMAIN_ID_DOES_NOT_EXIST = "DOMAIN_ID_DOESNOT_EXIST"; private static final String MODEL_NAME = "modelName"; private static final String LOGICAL_MODEL_ID_DEFAULT = "<def>"; private static final String LOGICAL_MODEL_ID_REPORTING = "Reporting"; private static final String LOGICAL_MODEL_ID_ANALYSIS = "Analysis"; private static final String LOGICAL_MODEL_CONTEXTNAME = "contextName"; private static final String STRING_DEFAULT = "<def>"; private LogicalModel analysisModel; private LogicalModel reportingModel; private DSWDatasourceServiceImpl dswService; private Domain domain2Models; private final IMetadataDomainRepository domainRepository = mock( IMetadataDomainRepository.class ); private ModelerWorkspace workspace2Models; private IPentahoObjectFactory pentahoObjectFactory; private final IMondrianCatalogService mondrianService = mock( IMondrianCatalogService.class ); private final SQLConnection sqlConnection = mock( SQLConnection.class ); private final Connection nativeConnection = mock( Connection.class ); private final ModelerService modelerService = mock( ModelerService.class ); private int[] columnTypes = new int[]{ Types.INTEGER }; private Object[] columns = new Object[]{ "id" }; @Before public void setUp() throws Exception { SqlDataSource dataSource = new SqlDataSource(); dataSource.setDatabaseName( CONNECTION_NAME ); SqlPhysicalTable sqlTable = new SqlPhysicalTable(); sqlTable.setTargetTable( VALID_QUERY ); SqlPhysicalModel sqlModel = new SqlPhysicalModel(); sqlModel.addPhysicalTable( sqlTable ); sqlModel.setDatasource( dataSource ); analysisModel = new LogicalModel(); analysisModel.setId( LOGICAL_MODEL_ID_ANALYSIS ); analysisModel.setProperty( DSWDatasourceServiceImpl.LM_PROP_VISIBLE, LOGICAL_MODEL_CONTEXTNAME ); reportingModel = new LogicalModel(); reportingModel.setId( LOGICAL_MODEL_ID_REPORTING ); domain2Models = new Domain(); domain2Models.setId( DOMAIN_ID_2MODELS ); domain2Models.addLogicalModel( analysisModel ); domain2Models.addLogicalModel( reportingModel ); domain2Models.setLocales( Arrays.asList( new LocaleType( "en_US", "Test locale" ) ) ); domain2Models.addPhysicalModel( sqlModel ); Set<String> domains = new TreeSet<String>(); domains.add( DOMAIN_ID_2MODELS ); doReturn( domain2Models ).when( domainRepository ).getDomain( DOMAIN_ID_2MODELS ); doReturn( domains ).when( domainRepository ).getDomainIds(); doAnswer( new Answer<Object>() { @Override public Void answer( InvocationOnMock invocation ) throws Throwable { final String modelId = (String) invocation.getArguments()[ 1 ]; final LogicalModel modelToRemove = domain2Models.findLogicalModel( modelId ); domain2Models.getLogicalModels().remove( modelToRemove ); return null; } } ).when( domainRepository ).removeModel( anyString(), anyString() ); workspace2Models = mock( ModelerWorkspace.class ); when( workspace2Models.getLogicalModel( ModelerPerspective.ANALYSIS ) ).thenReturn( analysisModel ); when( workspace2Models.getLogicalModel( ModelerPerspective.REPORTING ) ).thenReturn( reportingModel ); dswService = spy( new DSWDatasourceServiceImpl( mock( ConnectionServiceImpl.class ) ) ); doNothing().when( dswService ).checkSqlQueriesSupported( anyString() ); dswService.setMetadataDomainRepository( domainRepository ); Object[][] coumnHeaders = new Object[][]{ columns }; SQLMetaData metadata = mock( SQLMetaData.class ); when( metadata.getColumnHeaders() ).thenReturn( coumnHeaders ); when( metadata.getJDBCColumnTypes() ).thenReturn( columnTypes ); IPentahoResultSet resultSet = mock( IPentahoResultSet.class ); when( resultSet.getMetaData() ).thenReturn( metadata ); doReturn( resultSet ).when( sqlConnection ).executeQuery( matches( "(.*" + VALID_QUERY + ".*)" ) ); when( sqlConnection.executeQuery( matches( "(.*" + QUERY_COLUMN_ALREADY_EXIST + ".*)" ) ) ).thenThrow( new SQLException( "Reason", "S0021", 21 ) ); doReturn( nativeConnection ).when( sqlConnection ).getNativeConnection(); MondrianCatalog catalog = mock( MondrianCatalog.class ); doReturn( catalog ).when( mondrianService ).getCatalog( anyString(), any( IPentahoSession.class ) ); pentahoObjectFactory = mock( IPentahoObjectFactory.class ); when( pentahoObjectFactory.objectDefined( anyString() ) ).thenReturn( true ); when( pentahoObjectFactory.get( this.anyClass(), anyString(), any( IPentahoSession.class ) ) ) .thenAnswer( new Answer<Object>() { @Override public Object answer( InvocationOnMock invocation ) throws Throwable { if ( invocation.getArguments()[0].equals( IMondrianCatalogService.class ) ) { return mondrianService; } if ( invocation.getArguments()[0].equals( IPentahoConnection.class ) ) { return sqlConnection; } if ( invocation.getArguments()[0].equals( IMetadataDomainRepository.class ) ) { return domainRepository; } return null; } } ); PentahoSystem.registerObjectFactory( pentahoObjectFactory ); IPentahoSession pentahoSessionMock = mock( IPentahoSession.class ); when( pentahoSessionMock.getName() ).thenReturn( "sessionName" ); PentahoSessionHolder.setSession( pentahoSessionMock ); } @After public void tearDown() { PentahoSystem.deregisterObjectFactory( pentahoObjectFactory ); PentahoSystem.clearObjectFactory(); PentahoSessionHolder.removeSession(); } @Test public void testDeleteLogicalModel_allModelsRemoved() throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( workspace2Models ).when( dswService ).createModelerWorkspace(); assertTrue( dswService.deleteLogicalModel( DOMAIN_ID_2MODELS, MODEL_NAME ) ); verify( domainRepository ).removeModel( DOMAIN_ID_2MODELS, LOGICAL_MODEL_ID_REPORTING ); verify( domainRepository ).removeModel( DOMAIN_ID_2MODELS, LOGICAL_MODEL_ID_ANALYSIS ); } @Test public void testDeleteLogicalModel_removeReportingModelIfAnalysisModelDoesNotExist() throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); ModelerWorkspace workspace = mock( ModelerWorkspace.class ); when( workspace.getLogicalModel( ModelerPerspective.REPORTING ) ).thenReturn( reportingModel ); doReturn( workspace ).when( dswService ).createModelerWorkspace(); doCallRealMethod().when( dswService ).deleteLogicalModel( DOMAIN_ID_2MODELS, MODEL_NAME ); assertTrue( dswService.deleteLogicalModel( DOMAIN_ID_2MODELS, MODEL_NAME ) ); verify( domainRepository ).removeModel( DOMAIN_ID_2MODELS, LOGICAL_MODEL_ID_REPORTING ); } @Test public void testDeleteLogicalModel_keepDomainIfLogicalModelExist() throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( workspace2Models ).when( dswService ).createModelerWorkspace(); LogicalModel logicalModel = new LogicalModel(); logicalModel.setId( LOGICAL_MODEL_ID_DEFAULT ); domain2Models.getLogicalModels().add( logicalModel ); assertTrue( dswService.deleteLogicalModel( DOMAIN_ID_2MODELS, MODEL_NAME ) ); List<LogicalModel> logicalModels = domain2Models.getLogicalModels(); assertNotNull( logicalModels ); assertEquals( 1, logicalModels.size() ); verify( domainRepository, never() ).removeDomain( domain2Models.getId() ); } @Test public void testDeleteLogicalModel_removeDomainIfLogicalModelDoesNotExist() throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( workspace2Models ).when( dswService ).createModelerWorkspace(); assertTrue( dswService.deleteLogicalModel( DOMAIN_ID_2MODELS, MODEL_NAME ) ); assertTrue( domain2Models.getLogicalModels().isEmpty() ); verify( domainRepository ).removeDomain( domain2Models.getId() ); } @Test public void testDeleteLogicalModel_DoNotDeleteAnyWithoutPermissions() throws Exception { doReturn( false ).when( dswService ).hasDataAccessPermission(); doReturn( workspace2Models ).when( dswService ).createModelerWorkspace(); assertFalse( dswService.deleteLogicalModel( DOMAIN_ID_2MODELS, MODEL_NAME ) ); List<LogicalModel> logicalModels = domain2Models.getLogicalModels(); assertNotNull( logicalModels ); assertEquals( 2, logicalModels.size() ); verify( domainRepository, never() ).removeDomain( domain2Models.getId() ); verify( domainRepository, never() ).removeModel( DOMAIN_ID_2MODELS, LOGICAL_MODEL_ID_REPORTING ); } @Test public void testDeleteLogicalModel_DomainDoesNotExist() throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( workspace2Models ).when( dswService ).createModelerWorkspace(); //domain already deleted or does not exist, we return that delete operation was successful assertTrue( dswService.deleteLogicalModel( DOMAIN_ID_DOES_NOT_EXIST, MODEL_NAME ) ); } @Test public void testDeleteLogicalModel_MondrianDeleted() throws Exception { String mondrianName = "mondrianRef"; analysisModel.setProperty( DSWDatasourceServiceImpl.LM_PROP_MONDRIAN_CATALOG_REF, mondrianName ); doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( workspace2Models ).when( dswService ).createModelerWorkspace(); assertTrue( dswService.deleteLogicalModel( DOMAIN_ID_2MODELS, MODEL_NAME ) ); verify( mondrianService ).removeCatalog( eq( mondrianName ), any( IPentahoSession.class ) ); } @Test( expected = DatasourceServiceException.class ) public void testDeleteLogicalModel_DomainStorageException() throws Exception { testDeleteLogicalModel_Exception( DomainStorageException.class ); } @Test( expected = DatasourceServiceException.class ) public void testDeleteLogicalModel_MondrianCatalogServiceException() throws Exception { testDeleteLogicalModel_Exception( MondrianCatalogServiceException.class ); } @Test( expected = DatasourceServiceException.class ) public void testDeleteLogicalModel_DomainIdNullException() throws Exception { testDeleteLogicalModel_Exception( DomainIdNullException.class ); } private void testDeleteLogicalModel_Exception( Class<? extends Throwable> clazz ) throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( workspace2Models ).when( dswService ).createModelerWorkspace(); doThrow( clazz ).when( domainRepository ).removeModel( anyString(), anyString() ); dswService.deleteLogicalModel( null, MODEL_NAME ); } @Test( expected = DatasourceServiceException.class ) public void testSaveLogicalModel__DoNotSaveAnyWithoutPermissions() throws Exception { doReturn( false ).when( dswService ).hasDataAccessPermission(); assertFalse( dswService.saveLogicalModel( domain2Models, false ) ); verify( domainRepository, never() ).storeDomain( any( Domain.class ), anyBoolean() ); } @Test public void testSaveLogicalModel() throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); assertTrue( dswService.saveLogicalModel( domain2Models, false ) ); verify( domainRepository ).storeDomain( any( Domain.class ), anyBoolean() ); } @Test( expected = DatasourceServiceException.class ) public void testSaveLogicalModel_DomainStorageException() throws Exception { testSaveLogicalModel_Exception( DomainStorageException.class ); } @Test( expected = DatasourceServiceException.class ) public void testSaveLogicalModel_DomainAlreadyExistsException() throws Exception { testSaveLogicalModel_Exception( DomainAlreadyExistsException.class ); } @Test( expected = DatasourceServiceException.class ) public void testSaveLogicalModel_DomainIdNullException() throws Exception { testSaveLogicalModel_Exception( DomainIdNullException.class ); } private void testSaveLogicalModel_Exception( Class<? extends Throwable> clazz ) throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); doThrow( clazz ).when( domainRepository ).storeDomain( any( Domain.class ), anyBoolean() ); dswService.saveLogicalModel( domain2Models, false ); } @Test public void testTestDataSourceConnection() throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); assertTrue( dswService.testDataSourceConnection( CONNECTION_NAME ) ); } @Test( expected = DatasourceServiceException.class ) public void testTestDataSourceConnection_NullNativeConnection() throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( null ).when( sqlConnection ).getNativeConnection(); assertTrue( dswService.testDataSourceConnection( CONNECTION_NAME ) ); } @Test( expected = DatasourceServiceException.class ) public void testTestDataSourceConnection_CouldNotClose() throws Exception { doReturn( true ).when( dswService ).hasDataAccessPermission(); doThrow( new SQLException() ).when( nativeConnection ).close(); assertTrue( dswService.testDataSourceConnection( CONNECTION_NAME ) ); } @Test( expected = DatasourceServiceException.class ) public void testTestDataSourceConnection_DoesNotHavePermission() throws Exception { doReturn( false ).when( dswService ).hasDataAccessPermission(); dswService.testDataSourceConnection( CONNECTION_NAME ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateLogicalModel_DoesNotHavePermission() throws DatasourceServiceException { doReturn( false ).when( dswService ).hasDataAccessPermission(); dswService.generateLogicalModel( MODEL_NAME, CONNECTION_NAME, DB_TYPE, VALID_QUERY, PREVIEW_LIMIT ); try { verify( dswService ).executeQuery( "[connection &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]", VALID_QUERY, PREVIEW_LIMIT ); } catch ( Exception e ) { e.printStackTrace(); } } @Test public void testGenerateLogicalModel() throws DatasourceServiceException { testGenerateLogicalModel( MODEL_NAME, CONNECTION_NAME, VALID_QUERY, null, null ); } @Test public void testGenerateLogicalModel_EmptyRoleList() throws DatasourceServiceException { List<String> roleList = new ArrayList<String>(); testGenerateLogicalModel( MODEL_NAME, CONNECTION_NAME, VALID_QUERY, roleList, null ); } @Test public void testGenerateLogicalModel_NonEmptyRoleList() throws DatasourceServiceException { PentahoSessionHolder.setSession( mock( IPentahoSession.class ) ); List<String> roleList = Arrays.asList( "systemRole" ); testGenerateLogicalModel( MODEL_NAME, CONNECTION_NAME, VALID_QUERY, roleList, null ); } @Test public void testGenerateLogicalModel_EmptyUserList() throws DatasourceServiceException { List<String> userList = new ArrayList<String>(); testGenerateLogicalModel( MODEL_NAME, CONNECTION_NAME, VALID_QUERY, null, userList ); } @Test public void testGenerateLogicalModel_NonEmptyUserList_NonEmptyRoles() throws DatasourceServiceException { PentahoSessionHolder.setSession( mock( IPentahoSession.class ) ); List<String> userList = Arrays.asList( "systemUser" ); List<String> roleList = Arrays.asList( "systemRole" ); testGenerateLogicalModel( MODEL_NAME, CONNECTION_NAME, VALID_QUERY, roleList, userList ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateLogicalModel_NonEmptyUserList_EmptyRoles() throws DatasourceServiceException { PentahoSessionHolder.setSession( mock( IPentahoSession.class ) ); List<String> userList = Arrays.asList( "systemUser" ); testGenerateLogicalModel( MODEL_NAME, CONNECTION_NAME, VALID_QUERY, null, userList ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateLogicalModel_UNABLE_TO_GENERATE_MODEL_NULLNAME() throws DatasourceServiceException { testGenerateLogicalModel( null, CONNECTION_NAME, VALID_QUERY, null, null ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateLogicalModel_UNABLE_TO_GENERATE_MODEL_NULLConnection() throws DatasourceServiceException { testGenerateLogicalModel( MODEL_NAME, null, VALID_QUERY, null, null ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateLogicalModel_UNABLE_TO_GENERATE_MODEL_NULLQUERY() throws DatasourceServiceException { testGenerateLogicalModel( MODEL_NAME, CONNECTION_NAME, null, null, null ); } private void testGenerateLogicalModel( String modelName, String connName, String query, List<String> roleList, List<String> userList ) throws DatasourceServiceException { doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( roleList ).when( dswService ).getPermittedRoleList(); doReturn( userList ).when( dswService ).getPermittedUserList(); doReturn( 1 ).when( dswService ).getDefaultAcls(); BusinessData businessData = dswService.generateLogicalModel( modelName, connName, DB_TYPE, query, PREVIEW_LIMIT ); try { verify( dswService ).executeQuery( "[connection &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]", query, PREVIEW_LIMIT ); } catch ( Exception e ) { e.printStackTrace(); } assertNotNull( businessData ); assertNotNull( businessData.getDomain() ); assertNotNull( businessData.getData() ); } @Test public void testDoPreview() throws DatasourceServiceException { doReturn( true ).when( dswService ).hasDataAccessPermission(); SerializedResultSet result = dswService.doPreview( CONNECTION_NAME, VALID_QUERY, PREVIEW_LIMIT ); try { verify( dswService ).executeQuery( "[connection &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]", VALID_QUERY, PREVIEW_LIMIT ); } catch ( Exception e ) { e.printStackTrace(); } assertNotNull( result ); assertArrayEquals( columns, result.getColumns() ); assertArrayEquals( columnTypes, result.getColumnTypes() ); } @Test( expected = DatasourceServiceException.class ) public void testDoPreview_DoesNotHavePermission() throws DatasourceServiceException { doReturn( false ).when( dswService ).hasDataAccessPermission(); dswService.doPreview( CONNECTION_NAME, VALID_QUERY, PREVIEW_LIMIT ); try { verify( dswService ).executeQuery( "[connection &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]", VALID_QUERY, PREVIEW_LIMIT ); } catch ( Exception e ) { e.printStackTrace(); } } @Test( expected = DatasourceServiceException.class ) public void testDoPreview_NullConnection() throws DatasourceServiceException { doReturn( true ).when( dswService ).hasDataAccessPermission(); dswService.doPreview( null, VALID_QUERY, PREVIEW_LIMIT ); try { verify( dswService ).executeQuery( "[connection &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]", VALID_QUERY, PREVIEW_LIMIT ); } catch ( Exception e ) { e.printStackTrace(); } } @Test( expected = DatasourceServiceException.class ) public void testDoPreview_NullQuery() throws DatasourceServiceException { doReturn( true ).when( dswService ).hasDataAccessPermission(); SerializedResultSet result = dswService.doPreview( CONNECTION_NAME, null, PREVIEW_LIMIT ); try { verify( dswService ).executeQuery( "[connection &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]", VALID_QUERY, PREVIEW_LIMIT ); } catch ( Exception e ) { e.printStackTrace(); } assertNotNull( result ); assertArrayEquals( columns, result.getColumns() ); assertArrayEquals( columnTypes, result.getColumnTypes() ); } @Test public void testGenerateQueryDomain() throws DatasourceServiceException { testGenerateQueryDomain( MODEL_NAME, VALID_QUERY, null, null ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateQueryDomain_EmptyModelName() throws DatasourceServiceException { testGenerateQueryDomain( "", VALID_QUERY, null, null ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateQueryDomain_UnableToSerializeCommonCause() throws Exception { doThrow( new Exception() ).when( modelerService ).serializeModels( any( Domain.class ), anyString() ); testGenerateQueryDomain( MODEL_NAME, VALID_QUERY, null, null ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateQueryDomain_UnableToSerialize() throws Exception { when( modelerService.serializeModels( any( Domain.class ), anyString() ) ).thenThrow( new ModelerException() ); testGenerateQueryDomain( MODEL_NAME, VALID_QUERY, null, null ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateQueryDomain_SQLException() throws Exception { testGenerateQueryDomain( MODEL_NAME, QUERY_COLUMN_ALREADY_EXIST, null, null ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateQueryDomain_NullQuery() throws DatasourceServiceException { testGenerateQueryDomain( MODEL_NAME, null, null, null ); } @Test public void testGenerateQueryDomain_EmptyRoleList() throws DatasourceServiceException { List<String> roleList = new ArrayList<String>(); testGenerateQueryDomain( MODEL_NAME, VALID_QUERY, roleList, null ); } @Test public void testGenerateQueryDomain_NonEmptyRoleList() throws DatasourceServiceException { List<String> roleList = Arrays.asList( "systemRole" ); testGenerateQueryDomain( MODEL_NAME, VALID_QUERY, roleList, null ); } @Test public void testGenerateQueryDomain_EmptyUserList() throws DatasourceServiceException { List<String> userList = new ArrayList<String>(); testGenerateQueryDomain( MODEL_NAME, VALID_QUERY, null, userList ); } @Test( expected = DatasourceServiceException.class ) public void testGenerateQueryDomain_NonEmptyUserList_EmptyRoles() throws DatasourceServiceException { List<String> userList = Arrays.asList( "systemUser" ); testGenerateQueryDomain( MODEL_NAME, VALID_QUERY, null, userList ); } @Test public void testGenerateQueryDomain_NonEmptyUserList_NonEmptyRoles() throws DatasourceServiceException { List<String> userList = Arrays.asList( "systemUser" ); List<String> roleList = Arrays.asList( "systemRole" ); testGenerateQueryDomain( MODEL_NAME, VALID_QUERY, roleList, userList ); } private void testGenerateQueryDomain( String modelName, String query, List<String> roleList, List<String> userList ) throws DatasourceServiceException { ModelInfo modelInfo = mock( ModelInfo.class ); when( modelInfo.getFileInfo() ).thenReturn( mock( CsvFileInfo.class ) ); DatasourceDTO datasourceDTO = new DatasourceDTO(); datasourceDTO.setConnectionName( CONNECTION_NAME ); datasourceDTO.setDatasourceName( CONNECTION_NAME ); datasourceDTO.setCsvModelInfo( modelInfo ); DatabaseConnection connectionSpy = spy( new DatabaseConnection() ); connectionSpy.setName( CONNECTION_NAME ); connectionSpy.setDatabaseName( "[database name 接続 <;>!@#$%^&*()_-=+.,]" ); connectionSpy.setDatabasePort( "123456" ); connectionSpy.setHostname( "[hostname 接続 <;>!@#$%^&*()_-=+.,]" ); connectionSpy.setPassword( "[password 接続 <;>!@#$%^&*()_-=+.,]" ); connectionSpy.setUsername( "[username 接続 <;>!@#$%^&*()_-=+.,]" ); connectionSpy.setDatabaseType( mock( IDatabaseType.class ) ); doReturn( modelerService ).when( dswService ).createModelerService(); doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( roleList ).when( dswService ).getPermittedRoleList(); doReturn( userList ).when( dswService ).getPermittedUserList(); doReturn( null ).when( dswService ).getGeoContext(); doReturn( 1 ).when( dswService ).getDefaultAcls(); QueryDatasourceSummary summary = dswService.generateQueryDomain( modelName, query, connectionSpy, datasourceDTO ); try { verify( dswService ).executeQuery( "[connection &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]", query, "1" ); } catch ( Exception e ) { e.printStackTrace(); } verify( connectionSpy ).setName( "[connection &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]" ); verify( connectionSpy ).setDatabaseName( "[database name &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]" ); verify( connectionSpy, times( 2 ) ).setDatabasePort( "123456" ); verify( connectionSpy ).setHostname( "[hostname &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]" ); verify( connectionSpy ).setPassword( "[password &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]" ); verify( connectionSpy ).setUsername( "[username &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]" ); assertNotNull( summary ); assertNotNull( summary.getDomain() ); assertEquals( CONNECTION_NAME, summary.getDomain().getId() ); } @Test( expected = DatasourceServiceException.class ) public void testGetLogicalModels_DoesNotHavePermissionViewPermission() throws DatasourceServiceException { doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( false ).when( dswService ).hasDataAccessViewPermission(); dswService.getLogicalModels( LOGICAL_MODEL_CONTEXTNAME ); } @Test public void testGetLogicalModels_visibleToContext() throws DatasourceServiceException { testGetLogicalModels_NullContext( LOGICAL_MODEL_CONTEXTNAME ); } @Test public void testGetLogicalModels_NonVisibleToContext() throws DatasourceServiceException { testGetLogicalModels_NullContext( "anotherContext" ); } @Test public void testGetLogicalModels_NullContext() throws DatasourceServiceException { testGetLogicalModels_NullContext( null ); } @Test public void testGetLogicalModels_EmptyContext() throws DatasourceServiceException { testGetLogicalModels_NullContext( "" ); } private void testGetLogicalModels_NullContext( String context ) throws DatasourceServiceException { doReturn( true ).when( dswService ).hasDataAccessPermission(); doReturn( true ).when( dswService ).hasDataAccessViewPermission(); List<LogicalModelSummary> models = dswService.getLogicalModels( context ); assertNotNull( models ); for ( LogicalModelSummary logicalModelSummary : models ) { assertEquals( domain2Models.getId(), logicalModelSummary.getDomainId() ); } } @Test public void testListDatasourceNames() throws Exception { IPentahoSession session = mock( IPentahoSession.class ); when( session.getId() ).thenReturn( "SessionId" ); when( session.getActionName() ).thenReturn( "ActionNAme" ); when( session.getProcessId() ).thenReturn( "ProcessId" ); PentahoSessionHolder.setSession( session ); List<String> datasources = dswService.listDatasourceNames(); assertNotNull( datasources ); assertFalse( datasources.isEmpty() ); assertTrue( datasources.contains( LOGICAL_MODEL_ID_REPORTING ) ); } @Test public void testLoadBusinessData() throws DatasourceServiceException { BusinessData businessData = dswService.loadBusinessData( DOMAIN_ID_2MODELS, MODEL_NAME ); assertNotNull( businessData ); //should load the domain with expected id assertEquals( DOMAIN_ID_2MODELS, businessData.getDomain().getId() ); } @Test public void testHasPermission_nullSession() { PentahoSessionHolder.setSession( null ); assertFalse( dswService.hasPermission() ); } //should create new modeler service without exception @Test public void testCreateModelerService() { ModelerService service = dswService.createModelerService(); assertNotNull( service ); } //should create new workspace without exception @Test public void testCreateModelerWorkspace() { ModelerWorkspace workspace = dswService.createModelerWorkspace(); assertNotNull( workspace ); } @Test( expected = SqlQueriesNotSupportedException.class ) public void testSqlQueries_AreNotSupported_PentahoDataServices() throws Exception { String connNameDataService = "connToDataService"; String dbTypeIdDataService = "Pentaho Data Services"; DatabaseType dbtype = new DatabaseType( dbTypeIdDataService, STRING_DEFAULT, null, 0, STRING_DEFAULT ); IDatabaseConnection connDataService = new DatabaseConnection(); connDataService.setDatabaseType( dbtype ); ConnectionServiceImpl connService = mock( ConnectionServiceImpl.class ); doReturn( connDataService ).when( connService ).getConnectionByName( eq( connNameDataService ) ); DSWDatasourceServiceImpl service = new DSWDatasourceServiceImpl( connService ); service.checkSqlQueriesSupported( connNameDataService ); } @Test public void testSqlQueries_Supported_PostgresDb() throws Exception { String connNamePostgres = "connToPostgresDb"; String dbTypeIdPostgres = "PostgresDb"; IDatabaseConnection connDataService = new DatabaseConnection(); connDataService.setDatabaseType( new DatabaseType( dbTypeIdPostgres, STRING_DEFAULT, null, 0, STRING_DEFAULT ) ); ConnectionServiceImpl connService = mock( ConnectionServiceImpl.class ); doReturn( connDataService ).when( connService ).getConnectionByName( eq( connNamePostgres ) ); DSWDatasourceServiceImpl service = new DSWDatasourceServiceImpl( connService ); service.checkSqlQueriesSupported( connNamePostgres ); } @Test public void testDeSerializeModelStateValidString() throws Exception { PentahoSystem.registerObjectFactory( new TestObjectFactory() ); DatasourceModel datasourceModel = spy( new DatasourceModel() ); doReturn( "testdatasource" ).when( datasourceModel ).generateTableName(); datasourceModel.setDatasourceName( "testDatasource" ); datasourceModel.setDatasourceType( DatasourceType.CSV ); DatasourceDTO dto = DatasourceDTO.generateDTO( datasourceModel ); assertNotNull( dto ); String serializedDTO = dswService.serializeModelState( dto ); dswService.deSerializeModelState( serializedDTO ); } @Test( expected = DatasourceServiceException.class ) public void testDeSerializeModelStateInvalidString() throws Exception { String notSafeString = "<com.malicious.DatasourceDTO>\n" + " <datasourceName>testDatasource</datasourceName>\n" + " <datasourceType>CSV</datasourceType>\n" + " <csvModelInfo>\n" + " <fileInfo>\n" + " <delimiter>,</delimiter>\n" + " <enclosure>&quot;</enclosure>\n" + " <headerRows>1</headerRows>\n" + " <currencySymbol></currencySymbol>\n" + " <decimalSymbol>.</decimalSymbol>\n" + " <groupSymbol>,</groupSymbol>\n" + " <ifNull>---</ifNull>\n" + " <nullStr></nullStr>\n" + " </fileInfo>\n" + " <stageTableName>testdatasource</stageTableName>\n" + " <validated>false</validated>\n" + " <csvInputErrors/>\n" + " <tableOutputErrors/>\n" + " </csvModelInfo>\n" + " <connectionName>SampleData</connectionName>\n" + " <version>2.0</version>\n" + "</com.malicious.DatasourceDTO>"; dswService.deSerializeModelState( notSafeString ); } private Class<?> anyClass() { return argThat( new AnyClassMatcher() ); } private class AnyClassMatcher extends ArgumentMatcher<Class<?>> { @Override public boolean matches( final Object arg ) { return true; } } }
46.095
154
0.752169
7905f403175bfee3d6047aa7f4a93aa9eba39b68
565
package com.alex.javaweb; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author : alexchen * @created : 9/7/20, Monday **/ public class HeaderServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { String userAgent = request.getHeader("User-Agent"); response.getWriter().println(userAgent); } catch (Exception e) { e.printStackTrace(); } } }
26.904762
81
0.676106
658225346864151bcaeb65a43f4e00dcb39d8122
2,384
package com.adrielcafe.recifebomdebola.ui.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.adrielcafe.recifebomdebola.R; import com.adrielcafe.recifebomdebola.model.LeaderBoard; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class LeaderBoardAdapter extends ArrayAdapter<LeaderBoard> { public LeaderBoardAdapter(Context context, List<LeaderBoard> items) { super(context, R.layout.list_item_leaderboard, items); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; LeaderBoard leaderBoard = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_leaderboard, parent, false); viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.teamView.setText(leaderBoard.getTeam()); viewHolder.pointsScoredView.setText(leaderBoard.getPointsScored()+""); viewHolder.matchesView.setText(leaderBoard.getMatches()+""); viewHolder.winsView.setText(leaderBoard.getWins()+""); viewHolder.drawsView.setText(leaderBoard.getDraws()+""); viewHolder.defeatsView.setText(leaderBoard.getDefeats()+""); if(position > 1){ viewHolder.teamView.setTextColor(getContext().getResources().getColor(R.color.red)); } else { viewHolder.teamView.setTextColor(getContext().getResources().getColor(android.R.color.black)); } return convertView; } static class ViewHolder { @Bind(R.id.team) TextView teamView; @Bind(R.id.points_scored) TextView pointsScoredView; @Bind(R.id.matches) TextView matchesView; @Bind(R.id.wins) TextView winsView; @Bind(R.id.draws) TextView drawsView; @Bind(R.id.defeats) TextView defeatsView; ViewHolder(View view) { ButterKnife.bind(this, view); } } }
34.057143
116
0.658557
3e9731e5e348a5497b7c5903e67f559333779040
5,556
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package es.davinciti.liferay.service; import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil; import com.liferay.portal.kernel.util.ReferenceRegistry; import com.liferay.portal.service.InvokableService; /** * Provides the remote service utility for NotaGasto. This utility wraps * {@link es.davinciti.liferay.service.impl.NotaGastoServiceImpl} and is the * primary access point for service operations in application layer code running * on a remote server. Methods of this service are expected to have security * checks based on the propagated JAAS credentials because this service can be * accessed remotely. * * @author Cmes * @see NotaGastoService * @see es.davinciti.liferay.service.base.NotaGastoServiceBaseImpl * @see es.davinciti.liferay.service.impl.NotaGastoServiceImpl * @generated */ public class NotaGastoServiceUtil { /* * NOTE FOR DEVELOPERS: * * Never modify this class directly. Add custom service methods to {@link es.davinciti.liferay.service.impl.NotaGastoServiceImpl} and rerun ServiceBuilder to regenerate this class. */ /** * Returns the Spring bean ID for this bean. * * @return the Spring bean ID for this bean */ public static java.lang.String getBeanIdentifier() { return getService().getBeanIdentifier(); } /** * Sets the Spring bean ID for this bean. * * @param beanIdentifier the Spring bean ID for this bean */ public static void setBeanIdentifier(java.lang.String beanIdentifier) { getService().setBeanIdentifier(beanIdentifier); } public static java.lang.Object invokeMethod(java.lang.String name, java.lang.String[] parameterTypes, java.lang.Object[] arguments) throws java.lang.Throwable { return getService().invokeMethod(name, parameterTypes, arguments); } public static java.lang.String getApplicationStatusName(long statusId, java.lang.String localeT) { return getService().getApplicationStatusName(statusId, localeT); } public static boolean isUsuarioAdministrador(long companyId, long userId) { return getService().isUsuarioAdministrador(companyId, userId); } public static boolean isUsuarioValidador(long companyId, long userId) { return getService().isUsuarioValidador(companyId, userId); } public static boolean isUsuarioBasico(long companyId, long userId) { return getService().isUsuarioBasico(companyId, userId); } /** * Devuelve un listado de las Organizations del Usuario */ public static com.liferay.portal.kernel.json.JSONArray getOrganizationSageCompanies( long companyId, long userId) { return getService().getOrganizationSageCompanies(companyId, userId); } public static com.liferay.portal.kernel.json.JSONArray getCompanyExpensesNote( long companyId) { return getService().getCompanyExpensesNote(companyId); } public static com.liferay.portal.kernel.json.JSONArray getUserExpensesNote( long companyId, long userId) { return getService().getUserExpensesNote(companyId, userId); } public static com.liferay.portal.kernel.json.JSONObject addNotaGasto( long companyId, long userId, java.lang.String dataIni, java.lang.String localeT) { return getService().addNotaGasto(companyId, userId, dataIni, localeT); } public static com.liferay.portal.kernel.json.JSONObject editNotaGasto( long notagastoId, com.liferay.portal.kernel.json.JSONObject data, java.lang.String localeT) { return getService().editNotaGasto(notagastoId, data, localeT); } public static com.liferay.portal.kernel.json.JSONObject deleteNotaGasto( long notagastoId, java.lang.String localeT) { return getService().deleteNotaGasto(notagastoId, localeT); } public static com.liferay.portal.kernel.json.JSONObject sendValidateNotaGasto( long notagastoId, java.lang.String localeT) { return getService().sendValidateNotaGasto(notagastoId, localeT); } public static com.liferay.portal.kernel.json.JSONObject denyNotaGasto( long notagastoId, java.lang.String localeT) { return getService().denyNotaGasto(notagastoId, localeT); } public static com.liferay.portal.kernel.json.JSONObject validateNotaGasto( long companyId, long userId, long notagastoId, java.lang.String localeT) { return getService() .validateNotaGasto(companyId, userId, notagastoId, localeT); } public static void clearService() { _service = null; } public static NotaGastoService getService() { if (_service == null) { InvokableService invokableService = (InvokableService)PortletBeanLocatorUtil.locate(ClpSerializer.getServletContextName(), NotaGastoService.class.getName()); if (invokableService instanceof NotaGastoService) { _service = (NotaGastoService)invokableService; } else { _service = new NotaGastoServiceClp(invokableService); } ReferenceRegistry.registerReference(NotaGastoServiceUtil.class, "_service"); } return _service; } /** * @deprecated As of 6.2.0 */ public void setService(NotaGastoService service) { } private static NotaGastoService _service; }
33.878049
181
0.771778
9b7f531335a8663c0be2330a3b3ed6041b1541dc
2,348
package com.bht.saigonparking.service.booking.repository.custom; import java.util.List; import java.util.Optional; import javax.persistence.Tuple; import javax.validation.constraints.NotNull; import com.bht.saigonparking.service.booking.entity.BookingEntity; import com.bht.saigonparking.service.booking.entity.BookingStatusEntity; /** * * @author bht */ public interface BookingRepositoryCustom { List<Tuple> countAllBookingGroupByStatus(); List<Tuple> countAllBookingOfParkingLotGroupByStatus(@NotNull Long parkingLotId); Long countAllBooking(); Long countAllBooking(@NotNull BookingStatusEntity bookingStatusEntity); Long countAllBookingOfCustomer(@NotNull Long customerId); Long countAllBookingOfParkingLot(@NotNull Long parkingLotId); Long countAllBookingOfParkingLot(@NotNull Long parkingLotId, @NotNull BookingStatusEntity bookingStatusEntity); Long countAllOnGoingBookingOfParkingLot(@NotNull Long parkingLotId); List<BookingEntity> getAllBooking(@NotNull Integer nRow, @NotNull Integer pageNumber); List<BookingEntity> getAllBooking(@NotNull BookingStatusEntity bookingStatusEntity, @NotNull Integer nRow, @NotNull Integer pageNumber); List<BookingEntity> getAllBookingOfCustomer(@NotNull Long customerId, @NotNull Integer nRow, @NotNull Integer pageNumber); List<BookingEntity> getAllBookingOfParkingLot(@NotNull Long parkingLotId, @NotNull Integer nRow, @NotNull Integer pageNumber); List<BookingEntity> getAllBookingOfParkingLot(@NotNull Long parkingLotId, @NotNull BookingStatusEntity bookingStatusEntity, @NotNull Integer nRow, @NotNull Integer pageNumber); List<BookingEntity> getAllOnGoingBookingOfParkingLot(@NotNull Long parkingLotId); Optional<BookingEntity> getFirstByCustomerIdAndIsFinished(@NotNull Long customerId, @NotNull Boolean isFinished); }
40.482759
117
0.642675
bcf10fe46489103f256641d48da79d7345390a53
1,676
package mall.dog.service.user.entity; import mall.dog.entity.user.UserInfo; import javax.validation.constraints.NotNull; /** * 2018/8/28 mall.dog.service.user.entity * * @author dylan * Home: http://blog.devdylan.cn */ public class UserRequest { @NotNull private String code; private String encryptedData; private String errMsg; private String iv; private String rawData; private String signature; @NotNull private UserInfo userInfo; public UserRequest() { } public UserRequest(String code, String encryptedData, String errMsg, String iv, String rawData, String signature, UserInfo userInfo) { this.code = code; this.encryptedData = encryptedData; this.errMsg = errMsg; this.iv = iv; this.rawData = rawData; this.signature = signature; this.userInfo = userInfo; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getEncryptedData() { return encryptedData; } public void setEncryptedData(String encryptedData) { this.encryptedData = encryptedData; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public String getIv() { return iv; } public void setIv(String iv) { this.iv = iv; } public String getRawData() { return rawData; } public void setRawData(String rawData) { this.rawData = rawData; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } }
17.829787
135
0.717184
a8e3068ff6f76139b253e062b814415bd960c694
19,342
/* Copyright 2008, 2009 Wolfgang Ginolas This file is part of P2PVPN. P2PVPN is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Foobar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ package org.p2pvpn.gui; import java.awt.BorderLayout; import java.net.URL; import java.util.Map; import java.util.logging.Handler; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import javax.swing.ImageIcon; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.text.Document; import org.p2pvpn.network.PeerID; import org.p2pvpn.network.ConnectionManager; import org.p2pvpn.network.Router; import org.p2pvpn.network.RoutungTableListener; import org.p2pvpn.network.UPnPPortForward; import org.p2pvpn.network.UPnPPortForwardListener; /** * This is an information window which shows many informations about the * current status od P2PVPN. * @author Wolfgang Ginolas */ public class InfoWindow extends javax.swing.JFrame implements RoutungTableListener, UPnPPortForwardListener { private static final int MAX_LOG_LEN = 10*1000; // the max length of the log TextArea private ConnectionManager connectionManager; private MainControl mainControl; private PeerID addrShown = null; private PeerGraph peerGraph; /** Creates new form Main * @param mainControl the MainControl */ public InfoWindow(MainControl mainControl) { this.mainControl = mainControl; this.connectionManager = null; setLocationByPlatform(true); initComponents(); peerGraph = new PeerGraph(); pnlPeerGraph.setLayout(new BorderLayout()); pnlPeerGraph.add(peerGraph); peerTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { for(int i=e.getFirstIndex(); i<=e.getLastIndex(); i++) { if (peerTable1.getSelectionModel().isSelectedIndex(i)) { peerSelected(i); break; } } } }); try { URL url = InfoWindow.class.getClassLoader().getResource("resources/images/info.png"); setIconImage(new ImageIcon(url).getImage()); } catch(Throwable e) {} startLogging(); } /** Called by MainControl, when the network has changed. */ void networkHasChanged() { connectionManager = mainControl.getConnectionManager(); if (connectionManager != null) { peerTable1.setModel(new PeerTableModel(connectionManager)); ipTable.setModel(new IPTableModel(connectionManager)); setLocalInfo( "ID: "+connectionManager.getLocalAddr()+ " Port: "+connectionManager.getServerPort()); connectionManager.getRouter().addTableListener(InfoWindow.this); //connectionManager.getUPnPPortForward().addListener(Main.this); } peerGraph.setConnectionManager(connectionManager); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); jSplitPane1 = new javax.swing.JSplitPane(); jPanel2 = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); peerInfo = new javax.swing.JTextArea(); aPanel1 = new javax.swing.JPanel(); connectBtn1 = new javax.swing.JButton(); hostConnectText1 = new javax.swing.JTextField(); localInfo1 = new javax.swing.JLabel(); jScrollPane4 = new javax.swing.JScrollPane(); peerTable1 = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); ipTable = new javax.swing.JTable(); pnlPeerGraph = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jScrollPane5 = new javax.swing.JScrollPane(); logText = new javax.swing.JTextArea(); jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); setTitle("P2PVPN"); jSplitPane1.setDividerLocation(250); jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); jSplitPane1.setContinuousLayout(true); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Info")); peerInfo.setColumns(20); peerInfo.setEditable(false); peerInfo.setRows(5); peerInfo.setText(" "); jScrollPane3.setViewportView(peerInfo); org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel2Layout.createSequentialGroup() .addContainerGap() .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel2Layout.createSequentialGroup() .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane1.setRightComponent(jPanel2); aPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Connections")); connectBtn1.setText("Connect To"); connectBtn1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { eventConnectTo(evt); } }); hostConnectText1.setToolTipText("host:port"); localInfo1.setText(" "); peerTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); peerTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane4.setViewportView(peerTable1); org.jdesktop.layout.GroupLayout aPanel1Layout = new org.jdesktop.layout.GroupLayout(aPanel1); aPanel1.setLayout(aPanel1Layout); aPanel1Layout.setHorizontalGroup( aPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(aPanel1Layout.createSequentialGroup() .add(aPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(aPanel1Layout.createSequentialGroup() .addContainerGap() .add(localInfo1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE)) .add(aPanel1Layout.createSequentialGroup() .add(12, 12, 12) .add(connectBtn1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(hostConnectText1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)) .add(aPanel1Layout.createSequentialGroup() .addContainerGap() .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE))) .addContainerGap()) ); aPanel1Layout.setVerticalGroup( aPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, aPanel1Layout.createSequentialGroup() .add(localInfo1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(aPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(hostConnectText1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(connectBtn1)) .addContainerGap()) ); jSplitPane1.setLeftComponent(aPanel1); jTabbedPane1.addTab("Connections", jSplitPane1); ipTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jScrollPane1.setViewportView(ipTable); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE) .addContainerGap()) ); jTabbedPane1.addTab("Known IPs", jPanel1); org.jdesktop.layout.GroupLayout pnlPeerGraphLayout = new org.jdesktop.layout.GroupLayout(pnlPeerGraph); pnlPeerGraph.setLayout(pnlPeerGraphLayout); pnlPeerGraphLayout.setHorizontalGroup( pnlPeerGraphLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 540, Short.MAX_VALUE) ); pnlPeerGraphLayout.setVerticalGroup( pnlPeerGraphLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 445, Short.MAX_VALUE) ); jTabbedPane1.addTab("Peer Graph", pnlPeerGraph); logText.setColumns(20); logText.setRows(5); jScrollPane5.setViewportView(logText); org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .addContainerGap() .add(jScrollPane5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .addContainerGap() .add(jScrollPane5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE) .addContainerGap()) ); jTabbedPane1.addTab("Log", jPanel4); jLabel1.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("P2PVPN"); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("0.7"); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("11. July 2009"); jLabel4.setText("<html>P2PVPN Copyright (C) 2008, 2009 Wolfgang Ginolas<br>\nThis program comes with ABSOLUTELY NO WARRANTY;<br>\nThis is free software, and you are welcome to redistribute it<br>\nunder certain conditions.\n"); org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel3Layout.createSequentialGroup() .addContainerGap() .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE) .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE) .add(jLabel4)) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel3Layout.createSequentialGroup() .addContainerGap() .add(jLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLabel2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLabel3) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLabel4) .addContainerGap(302, Short.MAX_VALUE)) ); jTabbedPane1.addTab("About", jPanel3); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap() .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void eventConnectTo(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eventConnectTo connectionManager.connectTo(hostConnectText1.getText()); }//GEN-LAST:event_eventConnectTo /** * Called, when the user selects a peer in the peer table. This * will show the database of the selected peer. * @param i the selected row */ private void peerSelected(int i) { if (i<0) { return; } addrShown = ((PeerTableModel)peerTable1.getModel()).getPeerID(i); tableChanged(null); } /** * Set information like the PeerID ant the local port which should be * shown to the user. * @param s the info */ public void setLocalInfo(String s) { localInfo1.setText(s); } /** * Called, when the peer-table changes. This will update * the database shown to the user. * @param router */ public void tableChanged(Router router) { SwingUtilities.invokeLater(new Runnable() { public void run() { tableChangedSave(); } }); } /** * Called, when the peer-table changes. This will update * the database shown to the user. */ public void tableChangedSave() { StringBuffer info = new StringBuffer(); info.append("Info for "+addrShown+"\n\n"); Map<String, String> map = connectionManager.getRouter().getPeerInfo(addrShown); if (map==null) { peerInfo.setText(""); return; } for(Map.Entry<String, String> e : map.entrySet()) { info.append(e.getKey()+"="+e.getValue()+"\n"); } peerInfo.setText(info.toString()); } public void upnpChanged(UPnPPortForward upnp) { /* InternetGatewayDevice igd = upnp.getIgd(); if (igd!=null) { upnpText.setText("Internet Gateway Device: "+igd.getIGDRootDevice().getModelName()+"\n"+ "External IP: "+upnp.getExternalIP()+"\n" + "Port mapped: "+upnp.isMapped()+"\n" + "Error: "+upnp.getError()); } else { upnpText.setText("Internet Gateway Device: not found"); } */ } /** * Initialize the logging-tab. */ public void startLogging() { LoggingWriter lt = new LoggingWriter(); lt.setFormatter(new SimpleFormatter()); Logger.getLogger("").addHandler(lt); } /** * A Logging-Handler which shows all log messages in the log-tab. */ class LoggingWriter extends Handler { public LoggingWriter() { super(); } @Override public void publish(LogRecord r) { try { String s = getFormatter().format(r); Document d = logText.getDocument(); d.insertString(d.getLength(), s, null); if (d.getLength() > MAX_LOG_LEN) { d.remove(0, d.getLength()/2); } } catch (Throwable ex) { ex.printStackTrace(); } } @Override public void flush() { } @Override public void close() throws SecurityException { } } // TODO remove & rename variables // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel aPanel1; private javax.swing.JButton connectBtn1; private javax.swing.JTextField hostConnectText1; private javax.swing.JTable ipTable; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JLabel localInfo1; private javax.swing.JTextArea logText; private javax.swing.JTextArea peerInfo; private javax.swing.JTable peerTable1; private javax.swing.JPanel pnlPeerGraph; // End of variables declaration//GEN-END:variables }
38.30099
236
0.665495
5771933e36925c900df7ff75cd71518755d4daf3
3,454
package com.morange.business.common.service; /** * @author : zhenyun.su * @since : 2018/12/29 */ import com.morange.business.common.entity.ComTypeCode; import com.morange.business.common.entity.TypeCodeId; import com.morange.business.common.repository.ComTypeCodeRepository; import com.morange.business.fit.entity.FitStudent; import com.morange.system.utils.GlobalUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ObjectUtils; import java.time.LocalDateTime; import java.util.List; @Service public class ComTypeCodeService { @Autowired private ComTypeCodeRepository comTypeCodeRepository; @Transactional(readOnly = true) public List<ComTypeCode> findByType(String type) { return comTypeCodeRepository.findByType(type); } @Transactional() public void deleteByType(String type) { List<ComTypeCode> comTypeCodes = this.findByType(type); if (! ObjectUtils.isEmpty(comTypeCodes)) { comTypeCodeRepository.deleteAll(comTypeCodes); } } @Transactional() public ComTypeCode save(ComTypeCode comTypeCode) { return comTypeCodeRepository.save(comTypeCode); } public boolean save(String type, String code) { TypeCodeId typeCodeId = new TypeCodeId(type, code); if (!comTypeCodeRepository.existsById(typeCodeId)){ ComTypeCode comTypeCode = new ComTypeCode(); comTypeCode.setId(typeCodeId); comTypeCode.setName(code); comTypeCode.setDescription(type); comTypeCode.setEnabled(true); comTypeCode.setCreatedBy("test"); comTypeCode.setCreatedDate(LocalDateTime.now()); comTypeCode.setUpdatedBy("test"); comTypeCode.setUpdatedDate(LocalDateTime.now()); comTypeCodeRepository.save(comTypeCode); return true; }else{ return false; } } @Transactional() public int saveAll(List<ComTypeCode> comTypeCodes) { int count = 0; for (ComTypeCode item : comTypeCodes) { comTypeCodeRepository.delete(item); comTypeCodeRepository.save(item); count++; } return count; } @Transactional(readOnly = true) public ComTypeCode getById(String type, String code) { TypeCodeId typeCodeId = new TypeCodeId(type, code); return comTypeCodeRepository.findById(typeCodeId).get(); } @Transactional(readOnly = true) public Boolean existsById(String type, String code) { TypeCodeId typeCodeId = new TypeCodeId(type, code); return comTypeCodeRepository.existsById(typeCodeId); } @Transactional(readOnly = true) public Boolean existsById(TypeCodeId typeCodeId) { return comTypeCodeRepository.existsById(typeCodeId); } @Transactional() public void removeById(String type, String code) { TypeCodeId typeCodeId = new TypeCodeId(type, code); comTypeCodeRepository.deleteById(typeCodeId); } @Transactional() public void deleteById(TypeCodeId typeCodeId ) { comTypeCodeRepository.deleteById(typeCodeId); } @Transactional() public void deleteAll(List<ComTypeCode> comTypeCodes) { comTypeCodeRepository.deleteAll(comTypeCodes); }; @Transactional() public void delete(ComTypeCode comTypeCode) { comTypeCodeRepository.delete(comTypeCode); }; }
30.566372
68
0.71714
1c88cc3b2b27e4faaa2e64df91847aa9b50581a2
508
import java.util.Scanner; public class Blah { static { System.loadLibrary("blah"); } private native String doSomethingWithString(String string); public static void main(String[] args) { Blah blah = new Blah(); Scanner input = new Scanner(System.in); System.out.println("Type some strings, and we'll route them through a JNI library. Ctrl+D to quit, of course."); while (input.hasNextLine()) { System.out.println(blah.doSomethingWithString(input.nextLine())); } } }
26.736842
116
0.687008
db202ed27c8812325a522432e3c6e4be262b4e76
781
package com.github.bingoohuang.springrestclient.utils; import com.github.bingoohuang.asmvalidator.AsmParamsValidatorFactory; import com.github.bingoohuang.asmvalidator.ex.AsmValidateException; import lombok.experimental.UtilityClass; import lombok.val; import org.slf4j.LoggerFactory; @UtilityClass public class AsmValidatorLog { public void validate(Class<?> apiClass, String methodSignature, Object... parametersValues ) { try { AsmParamsValidatorFactory.validate(methodSignature, parametersValues); } catch (AsmValidateException e) { val log = LoggerFactory.getLogger(apiClass); log.warn("validate failed {}", e.getMessage()); throw e; } } }
32.541667
82
0.676056
e1fe68426f36ae10de448093d990957e2f733d50
486
package roles; import actions.AlignmentCop; public abstract class Cop extends Role { public Cop(int p, AlignmentCop.Sanity san) { actions.AlignmentCop cop = new actions.AlignmentCop(p, g -> true, san); registerActionKeywords(cop); } @Override public String roleMessage() { return "You are a cop. Every night, you may determine one target user's alignment. " + "Be warned: you do not know your sanity."; } @Override public String cardFlip() { return "Cop"; } }
21.130435
86
0.707819
af9157103a616496352f12cffa6fe7b767d2328b
7,372
/* * Copyright (c) 2014 zuendorf * * 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 shall be used for Good, not Evil. * * 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 org.sdmlib.test.templates; import org.sdmlib.models.classes.ClassModel; import org.sdmlib.storyboards.Storyboard; import de.uniks.networkparser.graph.Association; import de.uniks.networkparser.graph.Clazz; import de.uniks.networkparser.graph.DataType; public class ModelToTextToModelClassModel { /** * * <p> * Storyboard * <a href='./src/test/java/org/sdmlib/test/templates/ModelToTextToModelClassModel.java' type= * 'text/x-java'>modelToTextToModelClassModel</a> * </p> * <script> var json = { "typ":"class", "nodes":[ { "typ":"node", "id":"ChoiceTemplate" }, { * "typ":"node", "id":"Match", "attributes":[ "endPos : int", "fullText : String", "matchText : * String", "modelObject : Object", "startPos : int" ] }, { "typ":"node", * "id":"PlaceHolderDescription", "attributes":[ "attrName : String", "isKeyAttribute : boolean", * "prefix : String", "textFragment : String", "value : String" ] }, { "typ":"node", * "id":"Template", "attributes":[ "expandedText : String", "listEnd : String", "listSeparator : * String", "listStart : String", "modelClassName : String", "modelObject : Object", "name : * String", "referenceLookup : boolean", "templateText : String" ] } ], "edges":[ { "typ":"assoc", * "source":{ "id":"ChoiceTemplate", "cardinality":"one", "property":"chooser" }, "target":{ * "id":"Template", "cardinality":"many", "property":"choices" } }, { "typ":"generalisation", * "source":{ "id":"ChoiceTemplate", "cardinality":"one", "property":"choicetemplate" }, "target":{ * "id":"Template", "cardinality":"one", "property":"template" } }, { "typ":"assoc", "source":{ * "id":"Match", "cardinality":"many", "property":"matches" }, "target":{ "id":"Template", * "cardinality":"one", "property":"template" } }, { "typ":"assoc", "source":{ "id":"Match", * "cardinality":"many", "property":"matches" }, "target":{ "id":"PlaceHolderDescription", * "cardinality":"one", "property":"placeholder" } }, { "typ":"assoc", "source":{ "id":"Match", * "cardinality":"many", "property":"subMatches" }, "target":{ "id":"Match", "cardinality":"one", * "property":"parentMatch" } }, { "typ":"assoc", "source":{ "id":"PlaceHolderDescription", * "cardinality":"many", "property":"parents" }, "target":{ "id":"Template", "cardinality":"one", * "property":"subTemplate" } }, { "typ":"assoc", "source":{ "id":"PlaceHolderDescription", * "cardinality":"one", "property":"placeholder" }, "target":{ "id":"Match", "cardinality":"many", * "property":"matches" } }, { "typ":"assoc", "source":{ "id":"PlaceHolderDescription", * "cardinality":"many", "property":"placeholders" }, "target":{ "id":"Template", * "cardinality":"many", "property":"owners" } }, { "typ":"assoc", "source":{ "id":"Template", * "cardinality":"many", "property":"choices" }, "target":{ "id":"ChoiceTemplate", * "cardinality":"one", "property":"chooser" } }, { "typ":"assoc", "source":{ "id":"Template", * "cardinality":"many", "property":"owners" }, "target":{ "id":"PlaceHolderDescription", * "cardinality":"many", "property":"placeholders" } }, { "typ":"assoc", "source":{ "id":"Template", * "cardinality":"one", "property":"subTemplate" }, "target":{ "id":"PlaceHolderDescription", * "cardinality":"many", "property":"parents" } }, { "typ":"assoc", "source":{ "id":"Template", * "cardinality":"one", "property":"template" }, "target":{ "id":"Match", "cardinality":"many", * "property":"matches" } }, { "typ":"generalisation", "source":{ "id":"ChoiceTemplate", * "cardinality":"one", "property":"choicetemplate" }, "target":{ "id":"Template", * "cardinality":"one", "property":"template" } } ] } ; new Graph(json, * {"canvasid":"canvasmodelToTextToModelClassModelClassDiagram0", "display":"html", fontsize:10, * bar:false, propertyinfo:false}).layout(100,100); </script> * * @see <a href= * '../../../../../../../doc/modelToTextToModelClassModel.html'>modelToTextToModelClassModel.html</a> */ // @Test public void modelToTextToModelClassModel() { Storyboard story = new Storyboard(); ClassModel model = new ClassModel("org.sdmlib.models.transformations"); Clazz template = model.createClazz("Template") .withAttribute("modelObject", DataType.OBJECT) .withAttribute("templateText", DataType.STRING) .withAttribute("expandedText", DataType.STRING) .withAttribute("modelClassName", DataType.STRING) .withAttribute("listStart", DataType.STRING) .withAttribute("listSeparator", DataType.STRING) .withAttribute("listEnd", DataType.STRING) .withAttribute("referenceLookup", DataType.BOOLEAN) .withAttribute("name", DataType.STRING); Clazz placeholderDescription = model.createClazz("PlaceHolderDescription") .withBidirectional(template, "owners", Association.MANY, "placeholders", Association.MANY) .withAttribute("textFragment", DataType.STRING) .withAttribute("value", DataType.STRING) .withAttribute("attrName", DataType.STRING) .withAttribute("isKeyAttribute", DataType.BOOLEAN) .withAttribute("prefix", DataType.STRING); model.createClazz("ChoiceTemplate") .withSuperClazz(template) .withBidirectional(template, "choices", Association.MANY, "chooser", Association.ONE); Clazz matchClazz = model.createClazz("Match") .withAttribute("startPos", DataType.INT) .withAttribute("endPos", DataType.INT) .withAttribute("fullText", DataType.STRING) .withAttribute("matchText", DataType.STRING); matchClazz.withBidirectional(template, "template", Association.ONE, "matches", Association.MANY); matchClazz.withBidirectional(placeholderDescription, "placeholder", Association.ONE, "matches", Association.MANY); matchClazz.withAttribute("modelObject", DataType.OBJECT); matchClazz.withBidirectional(matchClazz, "subMatches", Association.MANY, "parentMatch", Association.ONE); placeholderDescription.withBidirectional(template, "subTemplate", Association.ONE, "parents", Association.MANY); story.addClassDiagram(model); model.generate("src/main/java"); story.dumpHTML(); } }
58.507937
118
0.669832
9caeec1127bf6ccc6dae2f556c1ec9969f041287
1,349
package br.com.api.dto; import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import br.com.api.model.Usuario; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * Classe de representação(DTO) da entidade {@link Usuario} * * @author Leonardo Araújo */ @NoArgsConstructor @EqualsAndHashCode @JsonInclude(content = Include.NON_NULL) public @Data class UsuarioDTO { @ApiModelProperty(name = "ID de Usuário", required = true) private Long id; @ApiModelProperty(name = "Login de usuário", required = true) private String login; @ApiModelProperty(name = "Senha de usuário", required = true) private String senha; @ApiModelProperty(name = "Pessoa", required = true) private PessoaDTO pessoa; @ApiModelProperty(name = "Data início de cadastro", required = true) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss") private LocalDateTime dataInicio; @ApiModelProperty(name = "Status(Ativo/Inativo) de Usuário", required = true) private Long idStatus; @ApiModelProperty(name = "Perfis de Usuário", required = true) private List<PerfilDTO> perfis; }
28.104167
78
0.770941
d64852145169157de19a84cf431276e399ef2f66
2,254
package pinacolada.effects.affinity; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Interpolation; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import pinacolada.cards.base.PCLAffinity; import pinacolada.effects.PCLEffect; public class FlashAffinityEffect extends PCLEffect { private float x; private float y; private final Texture img; private static final int W = 32; private float scale; private float baseScale; public FlashAffinityEffect(PCLAffinity affinity) { this.baseScale = this.scale = Settings.scale; if (AbstractDungeon.player != null) { this.x = AbstractDungeon.player.hb.cX; this.y = AbstractDungeon.player.hb.cY; } this.img = affinity.GetIcon(); this.duration = 0.7f; this.startingDuration = 0.7f; this.color = Color.WHITE.cpy(); this.renderBehind = false; } public FlashAffinityEffect SetScale(float scale) { this.baseScale = this.scale = scale; return this; } @Override public void update() { super.update(); this.scale = Interpolation.exp5In.apply(baseScale, baseScale * 0.3f, this.duration / this.startingDuration); } @Override public void render(SpriteBatch sb) { sb.setBlendFunction(770, 1); sb.setColor(this.color); if (this.img != null && this.img.getWidth() >= 48) { sb.draw(img, x - 16f, y - 16f, 16f, 16f, 32f, 32f, scale * 12f, scale * 12f, 0f, 0, 0, 64, 64, false, false); sb.draw(img, x - 16f, y - 16f, 16f, 16f, 32f, 32f, scale * 10f, scale * 10f, 0f, 0, 0, 64, 64, false, false); sb.draw(img, x - 16f, y - 16f, 16f, 16f, 32f, 32f, scale * 8f, scale * 8f, 0f, 0, 0, 64, 64, false, false); sb.draw(img, x - 16f, y - 16f, 16f, 16f, 32f, 32f, scale * 7f, scale * 7f, 0f, 0, 0, 64, 64, false, false); } else { this.isDone = true; } sb.setBlendFunction(770, 771); } public void dispose() { } }
29.272727
121
0.610027
cc0d460e0c2589781281b30cbc81514b44fdff03
3,582
package cn.niukid.bim.controller; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.autodesk.client.auth.OAuth2ThreeLegged; import com.autodesk.client.auth.OAuth2TwoLegged; import com.autodesk.client.auth.ThreeLeggedCredentials; import cn.niukid.bim.Config; import cn.niukid.bim.OAuth; import reactor.core.publisher.Mono; @RestController @RequestMapping(value = "/oauth") public class OAuthController { private static final Logger log = LoggerFactory.getLogger(OAuthController.class); private OAuth2ThreeLegged oauth2ThreeLegged; private ThreeLeggedCredentials threeLeggedCredentials; @GetMapping(value = "/getAccessToken") public Mono<Map<String, String>> getAccessToken() { Map<String, String> map = new HashMap<String, String>(); try { OAuth2TwoLegged forgeOAuth = OAuth.getOAuthPublic(); String token = forgeOAuth.getCredentials().getAccessToken(); // this is a timestamp, not the exact value of expires_in, so calculate back // client side will need this. though not necessary long expire_time_from_SDK = forgeOAuth.getCredentials().getExpiresAt(); // because we do not know when the token is got, align to current time // which will be a bit less than what Forge sets (say 3599 seconds). This makes // sense. Long expires_in = (expire_time_from_SDK - DateTime.now().toDate().getTime()) / 1000; // send to client log.info("token="+token); map.put("accessToken", token); map.put("expiresIn", expires_in.toString()); map.put("token_type", "Bearer"); } catch (Exception e) { e.printStackTrace(); map.put("ok", "ko"); map.put("msg", "Exception"); } return Mono.just(map); } public String make3LeggedRequest(List<String> scopes,String redirectUrl) { if(StringUtils.isEmpty(redirectUrl)) { return null; }else { try { redirectUrl = URLEncoder.encode(redirectUrl,"utf-8"); // Initialize the 3-legged OAuth 2.0 client, and optionally set specific scopes. // If you omit scopes, the generated token will have all scope permissions. // Set autoRefresh to `true` to automatically refresh the access token when it expires. // Note that the REDIRECT_URL must match the callback URL you provided when you created the app. oauth2ThreeLegged = new OAuth2ThreeLegged(Config.ClientId, Config.ClientSecret,redirectUrl, scopes, true); // Generate a URL page that asks for permissions for the specified scopes. String oauthUrl = oauth2ThreeLegged.getAuthenticationUrl(); //Redirect the user to authUrl (the user consent page). return oauthUrl; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return null; } @GetMapping(value = "/callback") public void callback(String authorizationCode) { if(oauth2ThreeLegged!=null) { try { threeLeggedCredentials = oauth2ThreeLegged.getAccessToken(authorizationCode); } catch (Exception e) { e.printStackTrace(); } }else { log.warn("oauth2ThreeLegged is null"); } } }
30.615385
111
0.717476
bb3ea9fa1047c37d1bbe4ba7835fcc6548d320f8
1,814
package de.tbressler.waterrower.subscriptions.values; import de.tbressler.waterrower.io.msg.in.DataMemoryMessage; import de.tbressler.waterrower.subscriptions.AbstractMemorySubscription; import de.tbressler.waterrower.subscriptions.Priority; import static de.tbressler.waterrower.io.msg.Memory.SINGLE_MEMORY; import static de.tbressler.waterrower.model.MemoryLocation.ZONE_HR_VAL; import static de.tbressler.waterrower.subscriptions.Priority.MEDIUM; /** * Subscription for the heart rate value (in beats per minute). * * TODO Because of the absence of the optional heart rate (pulse) device this value couldn't be tested so far. * * @author Tobias Bressler * @version 1.0 */ public abstract class HeartRateSubscription extends AbstractMemorySubscription { /* The last heart rate received. */ private int lastHeartRate = -1; /** * Subscription for the heart rate value (in beats per minute). */ public HeartRateSubscription() { this(MEDIUM); } /** * Subscription for the heart rate value (in beats per minute). * * @param priority The priority (recommended MEDIUM). */ public HeartRateSubscription(Priority priority) { super(priority, SINGLE_MEMORY, ZONE_HR_VAL); } @Override protected final void handle(DataMemoryMessage msg) { int heartRate = msg.getValue1(); // If the received heart rate is the same as before, // don't send an update. if (lastHeartRate == heartRate) return; lastHeartRate = heartRate; onHeartRateUpdated(heartRate); } /** * Is called if the value for the heart rate was updated. * * @param heartRate The new heart rate (in bpm). */ abstract protected void onHeartRateUpdated(int heartRate); }
27.907692
110
0.698456
04df2266837d4677a876e25006193312f6fd5787
668
package com.quantxt.sdk.sample; import com.quantxt.sdk.client.QT; import com.quantxt.sdk.progress.Progress; import java.util.List; public class MonitorJobs { private static final String API_KEY = "__APIKEY__"; public static void main(String[] args) { QT.init(API_KEY); List<Progress> progressList = Progress.reader().read(); System.out.println("Running jobs: " + progressList.size()); if (!progressList.isEmpty()) { for (Progress p : progressList) { String id = p.getId(); System.out.println("Job " + id + " " + p.getProgress() +"% completed."); } } } }
26.72
88
0.595808
67ce214cdf5274c9354dfda297739629a7ca7f70
201
public class swapEnds { public int[] swapEnds(int[] nums) { int temp = nums[0]; nums[0] = nums[nums.length-1]; nums[nums.length-1] = temp; return nums; } }
25.125
39
0.517413
c757359a608168887a3edbc34f46e6ee561ec115
1,693
/* * Copyright 2015, The Querydsl Team (http://www.querydsl.com/team) * * 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.querydsl.sql.types; import java.sql.*; import org.joda.time.DateTime; /** * {@code DateTimeType} maps {@linkplain org.joda.time.DateTime} * to {@linkplain java.sql.Timestamp} on the JDBC level * * @author tiwe * */ public class DateTimeType extends AbstractJodaTimeDateTimeType<DateTime> { public DateTimeType() { super(Types.TIMESTAMP); } public DateTimeType(int type) { super(type); } @Override public String getLiteral(DateTime value) { return dateTimeFormatter.print(value); } @Override public Class<DateTime> getReturnedClass() { return DateTime.class; } @Override public DateTime getValue(ResultSet rs, int startIndex) throws SQLException { Timestamp ts = rs.getTimestamp(startIndex); return ts != null ? new DateTime(ts.getTime()) : null; } @Override public void setValue(PreparedStatement st, int startIndex, DateTime value) throws SQLException { st.setTimestamp(startIndex, new Timestamp(value.getMillis())); } }
28.694915
100
0.700532
8656f86fae3cc38a3d66693ce82a9d4b4bbcdc9f
251
package br.com.erudio; public class DebugBasedLogger extends Logger { public DebugBasedLogger(int levels) { this.levels = levels; } @Override protected void displayLogInfo(String msg) { System.out.println("DEBUG LOGGER INFO: " + msg); } }
19.307692
50
0.729084
71d297265510deefd35f783c7755175a335ce550
7,722
/** * 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.hadoop.hdfs; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX; import java.io.IOException; import java.net.URI; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.crypto.CipherSuite; import org.apache.hadoop.crypto.CryptoCodec; import org.apache.hadoop.crypto.CryptoProtocolVersion; import org.apache.hadoop.crypto.key.KeyProvider; import org.apache.hadoop.crypto.key.KeyProviderDelegationTokenExtension; import org.apache.hadoop.crypto.key.KeyProviderTokenIssuer; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.fs.FileEncryptionInfo; import org.apache.hadoop.io.Text; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.util.KMSUtil; /** * Utility class for key provider related methods in hdfs client package. * */ @InterfaceAudience.Private @InterfaceStability.Unstable public final class HdfsKMSUtil { private static final String DFS_KMS_PREFIX = "dfs-kms-"; private static String keyProviderUriKeyName = CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH; private HdfsKMSUtil() { /* Hidden constructor */ } /** * Creates a new KeyProvider from the given Configuration. * * @param conf Configuration * @return new KeyProvider, or null if no provider was found. * @throws IOException if the KeyProvider is improperly specified in * the Configuration */ public static KeyProvider createKeyProvider( final Configuration conf) throws IOException { return KMSUtil.createKeyProvider(conf, keyProviderUriKeyName); } public static Token<?>[] addDelegationTokensForKeyProvider( KeyProviderTokenIssuer kpTokenIssuer, final String renewer, Credentials credentials, URI namenodeUri, Token<?>[] tokens) throws IOException { KeyProvider keyProvider = kpTokenIssuer.getKeyProvider(); if (keyProvider != null) { KeyProviderDelegationTokenExtension keyProviderDelegationTokenExtension = KeyProviderDelegationTokenExtension. createKeyProviderDelegationTokenExtension(keyProvider); Token<?>[] kpTokens = keyProviderDelegationTokenExtension. addDelegationTokens(renewer, credentials); credentials.addSecretKey(getKeyProviderMapKey(namenodeUri), DFSUtilClient.string2Bytes( kpTokenIssuer.getKeyProviderUri().toString())); if (tokens != null && kpTokens != null) { Token<?>[] all = new Token<?>[tokens.length + kpTokens.length]; System.arraycopy(tokens, 0, all, 0, tokens.length); System.arraycopy(kpTokens, 0, all, tokens.length, kpTokens.length); tokens = all; } else { tokens = (tokens != null) ? tokens : kpTokens; } } return tokens; } /** * Obtain the crypto protocol version from the provided FileEncryptionInfo, * checking to see if this version is supported by. * * @param feInfo FileEncryptionInfo * @return CryptoProtocolVersion from the feInfo * @throws IOException if the protocol version is unsupported. */ public static CryptoProtocolVersion getCryptoProtocolVersion( FileEncryptionInfo feInfo) throws IOException { final CryptoProtocolVersion version = feInfo.getCryptoProtocolVersion(); if (!CryptoProtocolVersion.supports(version)) { throw new IOException("Client does not support specified " + "CryptoProtocolVersion " + version.getDescription() + " version " + "number" + version.getVersion()); } return version; } /** * Obtain a CryptoCodec based on the CipherSuite set in a FileEncryptionInfo * and the available CryptoCodecs configured in the Configuration. * * @param conf Configuration * @param feInfo FileEncryptionInfo * @return CryptoCodec * @throws IOException if no suitable CryptoCodec for the CipherSuite is * available. */ public static CryptoCodec getCryptoCodec(Configuration conf, FileEncryptionInfo feInfo) throws IOException { final CipherSuite suite = feInfo.getCipherSuite(); if (suite.equals(CipherSuite.UNKNOWN)) { throw new IOException("NameNode specified unknown CipherSuite with ID " + suite.getUnknownValue() + ", cannot instantiate CryptoCodec."); } final CryptoCodec codec = CryptoCodec.getInstance(conf, suite); if (codec == null) { throw new UnknownCipherSuiteException( "No configuration found for the cipher suite " + suite.getConfigSuffix() + " prefixed with " + HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX + ". Please see the example configuration " + "hadoop.security.crypto.codec.classes.EXAMPLECIPHERSUITE " + "at core-default.xml for details."); } return codec; } /** * The key provider uri is searched in the following order. * 1. If there is a mapping in Credential's secrets map for namenode uri. * 2. From namenode getServerDefaults call. * 3. Finally fallback to local conf. * @return keyProviderUri if found from either of above 3 cases, * null otherwise * @throws IOException */ public static URI getKeyProviderUri(UserGroupInformation ugi, URI namenodeUri, String keyProviderUriStr, Configuration conf) throws IOException { URI keyProviderUri = null; // Lookup the secret in credentials object for namenodeuri. Credentials credentials = ugi.getCredentials(); byte[] keyProviderUriBytes = credentials.getSecretKey(getKeyProviderMapKey(namenodeUri)); if(keyProviderUriBytes != null) { keyProviderUri = URI.create(DFSUtilClient.bytes2String(keyProviderUriBytes)); return keyProviderUri; } if (keyProviderUriStr != null) { if (!keyProviderUriStr.isEmpty()) { keyProviderUri = URI.create(keyProviderUriStr); } return keyProviderUri; } // Last thing is to trust its own conf to be backwards compatible. String keyProviderUriFromConf = conf.getTrimmed( CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH); if (keyProviderUriFromConf != null && !keyProviderUriFromConf.isEmpty()) { keyProviderUri = URI.create(keyProviderUriFromConf); } return keyProviderUri; } /** * Returns a key to map namenode uri to key provider uri. * Tasks will lookup this key to find key Provider. */ public static Text getKeyProviderMapKey(URI namenodeUri) { return new Text(DFS_KMS_PREFIX + namenodeUri.getScheme() +"://" + namenodeUri.getAuthority()); } }
40.429319
113
0.724165
182c0a63ad00410ee5d727a20bb3a57964fdc5f4
563
package com.first.team2052.steamworks.auto.actions; import com.first.team2052.steamworks.subsystems.drive.DriveTrain; public class WaitUntilAngle implements Action { private final double angle; public WaitUntilAngle(double angle){ this.angle = angle; } @Override public void done() { } @Override public boolean isFinished() { return Math.abs(DriveTrain.getInstance().getGyroAngleDegrees() - angle) < 1.5; } @Override public void start() { } @Override public void update() { } }
18.16129
86
0.657194
5ce58d8a8004c347b687314eb234a6433e639ef5
361
package cn.itcast.fruitstore.controller; import cn.itcast.fruitstore.view.AbstractMainFrame; /** * 主界面操作类 */ @SuppressWarnings("serial") public class MainFrameController extends AbstractMainFrame { @Override public void showAdminDialog() { //在该方法中创建管理员界面并显示 //this为父窗口(主界面) true:设置为模态窗口展示 new AdminDialogController(this, true).setVisible(true); } }
24.066667
60
0.775623