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
1e648a72fa9266cdeee04a1fd253bd9097dbe171
5,711
/* * 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.jclouds.openstack.marconi.v1.features; import java.util.List; import javax.inject.Named; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.jclouds.Fallbacks.EmptyListOnNotFoundOr404; import org.jclouds.Fallbacks.FalseOnNotFoundOr404; import org.jclouds.Fallbacks.NullOnNotFoundOr404; import org.jclouds.javax.annotation.Nullable; import org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.marconi.v1.binders.BindIdsToQueryParam; import org.jclouds.openstack.marconi.v1.domain.CreateMessage; import org.jclouds.openstack.marconi.v1.domain.Message; import org.jclouds.openstack.marconi.v1.domain.MessageStream; import org.jclouds.openstack.marconi.v1.domain.MessagesCreated; import org.jclouds.openstack.marconi.v1.functions.ParseMessage; import org.jclouds.openstack.marconi.v1.functions.ParseMessagesCreated; import org.jclouds.openstack.marconi.v1.functions.ParseMessagesToList; import org.jclouds.openstack.marconi.v1.functions.ParseMessagesToStream; import org.jclouds.openstack.marconi.v1.options.StreamMessagesOptions; import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.Fallback; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.binders.BindToJsonPayload; /** * Provides access to Messages via their REST API. */ @SkipEncoding({'/', '='}) @RequestFilters(AuthenticateRequest.class) @Consumes(MediaType.APPLICATION_JSON) @Path("/messages") public interface MessageApi { /** * Create message(s) on a queue. * * @param messages The messages created on the queue. The number of messages allowed in one request are configurable * by your cloud provider. Consult your cloud provider documentation to learn the maximum. */ @Named("message:create") @POST @ResponseParser(ParseMessagesCreated.class) @Fallback(NullOnNotFoundOr404.class) @Nullable MessagesCreated create(@BinderParam(BindToJsonPayload.class) List<CreateMessage> messages); /** * Streams the messages off of a queue. In a very active queue it's possible that you could continuously stream * messages indefinitely. * * @param options Options for streaming messages to your client. */ @Named("message:stream") @GET @ResponseParser(ParseMessagesToStream.class) @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class) MessageStream stream(StreamMessagesOptions... options); /** * Lists specific messages. Unlike the stream method, a client's own messages are always returned in this operation. * * @param ids Specifies the IDs of the messages to list. */ @Named("message:list") @GET @ResponseParser(ParseMessagesToList.class) @Fallback(EmptyListOnNotFoundOr404.class) List<Message> list(@BinderParam(BindIdsToQueryParam.class) Iterable<String> ids); /** * Gets a specific message. Unlike the stream method, a client's own messages are always returned in this operation. * * @param id Specific ID of the message to get. */ @Named("message:get") @GET @Path("/{message_id}") @ResponseParser(ParseMessage.class) @Fallback(NullOnNotFoundOr404.class) @Nullable Message get(@PathParam("message_id") String id); /** * Deletes specific messages. If any of the message IDs are malformed or non-existent, they are ignored. The * remaining valid messages IDs are deleted. * * @param ids Specifies the IDs of the messages to delete. */ @Named("message:delete") @DELETE @Fallback(FalseOnNotFoundOr404.class) boolean delete(@BinderParam(BindIdsToQueryParam.class) Iterable<String> ids); /** * The claimId parameter specifies that the message is deleted only if it has the specified claim ID and that claim * has not expired. This specification is useful for ensuring only one worker processes any given message. When a * worker's claim expires before it can delete a message that it has processed, the worker must roll back any * actions it took based on that message because another worker can now claim and process the same message. * * @param id Specific ID of the message to delete. * @param claimId Specific claim ID of the message to delete. */ @Named("message:delete") @DELETE @Path("/{message_id}") @Fallback(FalseOnNotFoundOr404.class) boolean deleteByClaim(@PathParam("message_id") String id, @QueryParam("claim_id") String claimId); }
41.384058
119
0.755735
ff5d78cc358263eeca547e63b3d78fccfff40676
2,248
package com.composum.sling.platform.staging; import com.composum.sling.platform.testing.testutil.ErrorCollectorAlwaysPrintingFailures; import org.junit.Rule; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.composum.sling.platform.staging.ReleaseNumberCreator.*; import static com.composum.sling.platform.staging.StagingConstants.CURRENT_RELEASE; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; /** Tests for {@link ReleaseNumberCreator}. */ public class ReleaseNumberCreatorTest { @Rule public final ErrorCollectorAlwaysPrintingFailures ec = new ErrorCollectorAlwaysPrintingFailures(); @Test public void bumpNumbers() { String rel = ""; rel = MAJOR.bumpRelease(rel); ec.checkThat(rel, is("r1")); rel = BUGFIX.bumpRelease(rel); ec.checkThat(rel, is("r1.0.1")); rel = MINOR.bumpRelease(rel); ec.checkThat(rel, is("r1.1")); rel = BUGFIX.bumpRelease(rel); ec.checkThat(rel, is("r1.1.1")); rel = MAJOR.bumpRelease(rel); ec.checkThat(rel, is("r2")); rel = MINOR.bumpRelease(rel); ec.checkThat(rel, is("r2.1")); ec.checkThat(MINOR.bumpRelease("quaqua1ququ6BU!"), is("r1.7")); // invalid input doesn't hurt. ec.checkThat(MINOR.bumpRelease("!@#@"), is("r0.1")); } @Test public void firstRelease() { ec.checkThat(MAJOR.bumpRelease(""), is("r1")); ec.checkThat(MINOR.bumpRelease(""), is("r0.1")); ec.checkThat(BUGFIX.bumpRelease(""), is("r0.0.1")); } @Test public void sorting() { List<String> rels = new ArrayList<>(Arrays.asList("r10.9", "r1.2.1", "r3.2.2", "r1.2", "", "r3.10.2", CURRENT_RELEASE, "r", "r3.5")); Collections.sort(rels, COMPARATOR_RELEASES); ec.checkThat(rels, contains("", "r", "r1.2", "r1.2.1", "r3.2.2", "r3.5", "r3.10.2", "r10.9", CURRENT_RELEASE)); ec.checkThat(-1, is(COMPARATOR_RELEASES.compare("r1", "r1.2"))); ec.checkThat(1, is(COMPARATOR_RELEASES.compare("r10.9", "r1.2"))); ec.checkThat(-1, is(COMPARATOR_RELEASES.compare("r1.2", "r10.9"))); } }
36.852459
141
0.645463
04af0724df057f921c6e70f0321a900dccae697f
5,659
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; import com.ctre.phoenix.motorcontrol.NeutralMode; import com.ctre.phoenix.motorcontrol.TalonFXControlMode; import com.ctre.phoenix.motorcontrol.can.TalonFX; import com.ctre.phoenix.motorcontrol.can.*; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.MecanumDrive; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; public class DriveTrainSubsystem extends SubsystemBase { //adapted from Team 6624 //Motors private static TalonFX LEFT_FRONT_DRIVE_MOTOR; private static TalonFX LEFT_BACK_DRIVE_MOTOR; private static TalonFX RIGHT_FRONT_DRIVE_MOTOR; private static TalonFX RIGHT_BACK_DRIVE_MOTOR; //Encoders public static Encoder LEFT_FRONT_DRIVE_ENCODER; public static Encoder LEFT_BACK_DRIVE_ENCODER; public static Encoder RIGHT_FRONT_DRIVE_ENCODER; public static Encoder RIGHT_BACK_DRIVE_ENCODER; // public static MeadianPIDSource DRIVE_ENCODERS; don't know the import public DriveTrainSubsystem(){ //Motors LEFT_FRONT_DRIVE_MOTOR = new TalonFX(Constants.LEFT_FRONT_DRIVE_MOTOR_PORT); LEFT_BACK_DRIVE_MOTOR = new TalonFX(Constants.LEFT_BACK_DRIVE_MOTOR_PORT); RIGHT_FRONT_DRIVE_MOTOR = new TalonFX(Constants.RIGHT_FRONT_DRIVE_MOTOR_PORT); RIGHT_BACK_DRIVE_MOTOR = new TalonFX(Constants.RIGHT_BACK_DRIVE_MOTOR_PORT); //Encoders LEFT_FRONT_DRIVE_ENCODER = new Encoder(Constants.LEFT_FRONT_DRIVE_ENCODER_PIN_A, Constants.LEFT_FRONT_DRIVE_ENCODER_PIN_B); LEFT_BACK_DRIVE_ENCODER = new Encoder(Constants.LEFT_BACK_DRIVE_ENCODER_PIN_A, Constants.LEFT_BACK_DRIVE_ENCODER_PIN_B); RIGHT_FRONT_DRIVE_ENCODER = new Encoder(Constants.RIGHT_FRONT_DRIVE_ENCODER_PIN_A, Constants.RIGHT_FRONT_DRIVE_ENCODER_PIN_B); RIGHT_BACK_DRIVE_ENCODER = new Encoder(Constants.RIGHT_BACK_DRIVE_ENCODER_PIN_A, Constants.RIGHT_BACK_DRIVE_ENCODER_PIN_B); //DRIVE_ENCODERS = new MedianPIDSource(LEFT_FRONT_DRIVE_ENCODER, LEFT_BACK_DRIVE_ENCODER, RIGHT_FRONT_DRIVE_ENCODER, RIGHT_BACK_DRIVE_ENCODER); } public static void setMecanumDrive(double translationAngle, double translationPower, double turnPower){ //A is front left, b is front right, c is back left, d is back right // calculate motor power //Math.sqrt(2) * 0.5 comes from sin(45) and cos(45) (trig is necessary to get the power in mecanum) double ADPower = translationPower * Math.sqrt(2) * 0.5 * (Math.sin(translationAngle) + Math.cos(translationAngle)); double BCPower = translationPower * Math.sqrt(2) * 0.5 * (Math.sin(translationAngle) - Math.cos(translationAngle)); //check if turning power will interfere with normal translation //check ADPower to see if trying to apply turnPower would put motor power over 1.0 or under -1.0 double turningScale = Math.max(Math.abs(ADPower + turnPower), Math.abs(ADPower - turnPower)); //check BCPower to see if trying to apply turnPower would put motor power over 1.0 or under -1.0 turningScale = Math.max(turningScale, Math.max(Math.abs(BCPower + turnPower), Math.abs(BCPower - turnPower))); //adjust turn power scale correctly --- 1.0 is the max power of the motor. if (Math.abs(turningScale) < 1.0){ turningScale = 1.0; } //set the motors, and divide them by turning Scale to make sure none of them go over the top, which would alter the translation angles LEFT_FRONT_DRIVE_MOTOR.set(TalonFXControlMode.PercentOutput, (ADPower - turningScale) / turningScale); LEFT_BACK_DRIVE_MOTOR.set(TalonFXControlMode.PercentOutput, (BCPower - turningScale) / turningScale); RIGHT_FRONT_DRIVE_MOTOR.set(TalonFXControlMode.PercentOutput, (BCPower + turningScale) / turningScale); RIGHT_BACK_DRIVE_MOTOR.set(TalonFXControlMode.PercentOutput, (ADPower + turningScale) / turningScale); } //Deprecated /* private static TalonFX frontLeftMotor = new TalonFX(Constants.FRONT_LEFT_MOTOR_PORT); private static TalonFX rearLeftMotor = new TalonFX(Constants.REAR_LEFT_MOTOR_PORT); private static TalonFX frontRightMotor = new TalonFX(Constants.FRONT_RIGHT_MOTOR_PORT); private static TalonFX rearRightMotor = new TalonFX(Constants.REAR_RIGHT_MOTOR_PORT); public void m_driveCartesian(double ySpeed, double xSpeed, double zRotation){ frontLeftMotor.setNeutralMode(NeutralMode.Brake); rearLeftMotor.setNeutralMode(NeutralMode.Brake); frontRightMotor.setNeutralMode(NeutralMode.Brake); rearRightMotor.setNeutralMode(NeutralMode.Brake); double frontLeftPower = skim(ySpeed + xSpeed + zRotation); double rearLeftPower = skim(ySpeed - xSpeed + zRotation); double frontRightPower = skim(ySpeed - xSpeed - zRotation); double rearRightPower = skim(ySpeed + xSpeed - zRotation); frontLeftMotor.set(TalonFXControlMode.PercentOutput, frontLeftPower); rearLeftMotor.set(TalonFXControlMode.PercentOutput, rearLeftPower); frontRightMotor.set(TalonFXControlMode.PercentOutput, frontRightPower); rearRightMotor.set(TalonFXControlMode.PercentOutput, rearRightPower); } public void DrivetrainSub() { } public double skim(double num){ //This method keeps the power value from being above or below the limits of the motor. //1 and -1 are the upper and lower bounds of the motor. if (num > 1.0) { return 1.0; } else if (num < -1.0) { return -1.0; } else{ return num; } } */ }
42.231343
147
0.775049
c896c7d483dc2c090a264f696c08f6991c2d8fca
1,013
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.github.javarch.jsf; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.github.javarch.jsf.context.FacesContextUtils; @Component public class CurrentLocale { @Autowired private FacesContextUtils context; public Locale getLocale(){ return context.getFacesContext().getViewRoot().getLocale(); } }
28.942857
79
0.779862
192ebf37a7c0b4f5da6689ac83039e6570dd5bc5
213
package org.littlemonkey.qrscanner; public class NativeScannerImpl { public void scanQRCode() { } public void scanBarCode() { } public boolean isSupported() { return false; } }
14.2
35
0.633803
183aa60540d10316832cf5031260232ac76ec50c
3,279
/* * 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.gate.gui.common; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.gate.varfuncs.property.GateProperty; import org.gate.varfuncs.property.StringProperty; import java.io.Serializable; import java.util.*; /** * Use same data structure store parameters to keep compatible with TestElement */ public class DefaultParameters implements Serializable { protected Logger log = LogManager.getLogger(this.getClass()); protected HashMap<String, LinkedList<GateProperty>> defaultParameters = new HashMap(); public LinkedList<GateProperty> getProps(String nameSpace){ return defaultParameters.get(nameSpace); } public HashMap<String, LinkedList<GateProperty>> getDefaultParameters(){ return defaultParameters; } public GateProperty getProp(String scope, String name){ for(GateProperty property : defaultParameters.get(scope)){ if(property.getName().equals(name)){ return property; } } return null; } public void modify(String nameSpace, LinkedList<GateProperty> parameters){ if(!defaultParameters.containsKey(nameSpace)){ defaultParameters.put(nameSpace, new LinkedList<>()); } LinkedList<GateProperty> newDefaultParameters = new LinkedList<>(parameters); ListIterator<GateProperty> listIterator = newDefaultParameters.listIterator(); while(listIterator.hasNext()){ GateProperty newDefaultParameter = listIterator.next(); for(GateProperty defaultParameter : defaultParameters.get(nameSpace)){ if(newDefaultParameter.getName().equals(defaultParameter.getName())){ defaultParameter.setObjectValue(newDefaultParameter.getStringValue()); listIterator.remove(); } } } defaultParameters.get(nameSpace).addAll(newDefaultParameters); newDefaultParameters.clear(); } public void applyDefaultsInNameSpace(LinkedList<GateProperty> gateProperties){ for(GateProperty property : gateProperties){ for(GateProperty defaultProperty: getProps(TestElement.NS_DEFAULT)){ if(property.getName().equals(defaultProperty.getName()) && property.getStringValue().isEmpty()){ property.setObjectValue(defaultProperty.getObjectValue()); } } } } }
40.481481
112
0.698384
690e31ffae48c8fe52fcf11f2d49dad185c486ec
5,208
package me.yimu.wexxar.cache; import com.alibaba.fastjson.JSON; import java.io.IOException; import java.util.ArrayList; import java.util.List; import me.yimu.wexxar.Wexxar; import me.yimu.wexxar.route.Route; import me.yimu.wexxar.route.Routes; import me.yimu.wexxar.utils.LogUtils; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Request; import okhttp3.Response; /** * Created by linwei on 2018/3/4. */ public class FileDownloader { public static final String TAG = FileDownloader.class.getSimpleName(); public static final List<String> mDownloadingProcess = new ArrayList<>(); /** * 下载bundle文件 * * @param url * @param callback */ private static void doDownloadBundleFile(String url, Callback callback) { LogUtils.i(TAG, "url = " + url); Request request = new Request.Builder().url(url) .build(); Wexxar.getOkHttpClient().newCall(request) .enqueue(callback); } /** * 下载bundle文件,然后缓存 * * @param url * @param callback */ public static void prepareBundleFile(final String url, final Callback callback) { FileDownloader.doDownloadBundleFile(url, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { try { if (response.isSuccessful()) { // 1. 存储到本地 boolean result = CacheHelper.getInstance().saveFileCache(url, response.body().bytes()); // 存储失败,则失败 if (!result) { onFailure(call, new IOException("file save fail!")); } else { if (null != callback) { callback.onResponse(call, response); } } } else { onFailure(call, new IOException(String.valueOf(response.code()))); } } catch (Exception e) { e.printStackTrace(); onFailure(call, new IOException("file save fail!")); LogUtils.i(TAG, "prepare bundle fail"); } } @Override public void onFailure(Call call, IOException e) { if (null != callback) { callback.onFailure(call, e); } } }); } public interface DownloadCallback { void onDownloadSuccess(); } /** * 空闲时间下载bundle文件 * // FIXME 考虑并发问题 */ public static void prepareBundleFiles(Routes routes, final DownloadCallback callback) { if (null == routes || routes.isEmpty()) { return; } ArrayList<Route> validRoutes = new ArrayList<>(); validRoutes.addAll(routes.items); // 重新下载 mDownloadingProcess.clear(); int totalSize = validRoutes.size(); // 需要下载的route数量 int newRouteCount = 0; LogUtils.i(TAG, "routes:" + JSON.toJSONString(routes)); LogUtils.i(TAG, "download total count:" + totalSize); for (int i = 0; i < totalSize ; i ++) { final Route tempRoute = validRoutes.get(i); if (CacheHelper.getInstance().findCache(tempRoute.getRemoteFile()) == null) { newRouteCount ++; if (!mDownloadingProcess.contains(tempRoute.getRemoteFile())) { mDownloadingProcess.add(tempRoute.getRemoteFile()); FileDownloader.prepareBundleFile(tempRoute.getRemoteFile(), new Callback() { @Override public void onFailure(Call call, IOException e) { // 如果下载失败,则不移除 LogUtils.i(TAG, "download bundle failed" + tempRoute.getRemoteFile() + e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { mDownloadingProcess.remove(tempRoute.getRemoteFile()); LogUtils.i(TAG, "download bundle success " + tempRoute.getRemoteFile()); // 如果全部文件下载成功,则发送校验成功事件 if (mDownloadingProcess.isEmpty()) { LogUtils.i(TAG, "download bundle complete"); if (callback != null) { callback.onDownloadSuccess(); } } } }); } } else { LogUtils.i(TAG, "download exist " + tempRoute.getRemoteFile()); // 如果所有bundle文件都已经缓存了,也可以更新route if (newRouteCount == 0 && i == totalSize - 1) { if (callback != null) { callback.onDownloadSuccess(); } } } } LogUtils.i(TAG, "download new count:" + newRouteCount); } }
36.41958
115
0.504416
db8cb2c0d5d44bb0f0bf33d1484412db4b29869f
986
package webcrawler; import org.pmw.tinylog.Logger; import webcrawler.digestpage.ProcessPage; /** * Created by Gabe Sargeant on 22/01/17. */ public class WebCrawler { private String URI; private String BASE_URI; WebCrawler(String uri) { URI = uri; if(uri.contains("http://www.")){ BASE_URI = uri.replace("http://www.",""); } else if(uri.contains("http://")){ BASE_URI = uri.replace("http://",""); } else BASE_URI = uri; } public void startCrawl(){ Logger.info("URI ############# = " + BASE_URI); Logger.info(URI); ProcessPage p = new ProcessPage(URI); p.extractLinks(URI); for (int i = 0; i < p.count(); i++){ p.next(); p.run(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } }
20.541667
55
0.483773
885a910c1e09a0339b7d64e970e71ca832dd5d50
44,131
/* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */ package org.geysermc.connector.network.session; import com.github.steveice10.mc.auth.data.GameProfile; import com.github.steveice10.mc.auth.exception.request.AuthPendingException; import com.github.steveice10.mc.auth.exception.request.InvalidCredentialsException; import com.github.steveice10.mc.auth.exception.request.RequestException; import com.github.steveice10.mc.auth.service.AuthenticationService; import com.github.steveice10.mc.auth.service.MojangAuthenticationService; import com.github.steveice10.mc.auth.service.MsaAuthenticationService; import com.github.steveice10.mc.protocol.MinecraftConstants; import com.github.steveice10.mc.protocol.MinecraftProtocol; import com.github.steveice10.mc.protocol.data.SubProtocol; import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode; import com.github.steveice10.mc.protocol.data.game.statistic.Statistic; import com.github.steveice10.mc.protocol.data.game.window.VillagerTrade; import com.github.steveice10.mc.protocol.packet.handshake.client.HandshakePacket; import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionPacket; import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket; import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientTeleportConfirmPacket; import com.github.steveice10.mc.protocol.packet.login.client.LoginPluginResponsePacket; import com.github.steveice10.mc.protocol.packet.login.server.LoginSuccessPacket; import com.github.steveice10.packetlib.BuiltinFlags; import com.github.steveice10.packetlib.Client; import com.github.steveice10.packetlib.event.session.*; import com.github.steveice10.packetlib.packet.Packet; import com.github.steveice10.packetlib.tcp.TcpSessionFactory; import com.nukkitx.math.GenericMath; import com.nukkitx.math.vector.*; import com.nukkitx.protocol.bedrock.BedrockPacket; import com.nukkitx.protocol.bedrock.BedrockServerSession; import com.nukkitx.protocol.bedrock.data.*; import com.nukkitx.protocol.bedrock.data.command.CommandPermission; import com.nukkitx.protocol.bedrock.packet.*; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectMaps; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectIterator; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.geysermc.common.window.CustomFormWindow; import org.geysermc.common.window.FormWindow; import org.geysermc.connector.GeyserConnector; import org.geysermc.connector.command.CommandSender; import org.geysermc.connector.common.AuthType; import org.geysermc.connector.entity.Entity; import org.geysermc.connector.entity.Tickable; import org.geysermc.connector.entity.player.SessionPlayerEntity; import org.geysermc.connector.entity.player.SkullPlayerEntity; import org.geysermc.connector.inventory.PlayerInventory; import org.geysermc.connector.network.remote.RemoteServer; import org.geysermc.connector.network.session.auth.AuthData; import org.geysermc.connector.network.session.auth.BedrockClientData; import org.geysermc.connector.network.session.cache.*; import org.geysermc.connector.network.translators.BiomeTranslator; import org.geysermc.connector.network.translators.EntityIdentifierRegistry; import org.geysermc.connector.network.translators.PacketTranslatorRegistry; import org.geysermc.connector.network.translators.chat.MessageTranslator; import org.geysermc.connector.network.translators.collision.CollisionManager; import org.geysermc.connector.network.translators.inventory.EnchantmentInventoryTranslator; import org.geysermc.connector.network.translators.item.ItemRegistry; import org.geysermc.connector.skin.SkinManager; import org.geysermc.connector.utils.*; import org.geysermc.floodgate.util.BedrockData; import org.geysermc.floodgate.util.EncryptionUtil; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @Getter public class GeyserSession implements CommandSender { private final GeyserConnector connector; private final UpstreamSession upstream; private RemoteServer remoteServer; private Client downstream; @Setter private AuthData authData; @Setter private BedrockClientData clientData; @Deprecated @Setter private boolean microsoftAccount; private final SessionPlayerEntity playerEntity; private PlayerInventory inventory; private AdvancementsCache advancementsCache; private BookEditCache bookEditCache; private ChunkCache chunkCache; private EntityCache entityCache; private EntityEffectCache effectCache; private InventoryCache inventoryCache; private WorldCache worldCache; private WindowCache windowCache; private final Int2ObjectMap<TeleportCache> teleportMap = new Int2ObjectOpenHashMap<>(); /** * Stores session collision */ private final CollisionManager collisionManager; private final Map<Vector3i, SkullPlayerEntity> skullCache = new ConcurrentHashMap<>(); private final Long2ObjectMap<ClientboundMapItemDataPacket> storedMaps = Long2ObjectMaps.synchronize(new Long2ObjectOpenHashMap<>()); /** * A map of Vector3i positions to Java entity IDs. * Used for translating Bedrock block actions to Java entity actions. */ private final Object2LongMap<Vector3i> itemFrameCache = new Object2LongOpenHashMap<>(); @Setter private Vector2i lastChunkPosition = null; private int renderDistance; private boolean loggedIn; private boolean loggingIn; @Setter private boolean spawned; private boolean closed; @Setter private GameMode gameMode = GameMode.SURVIVAL; /** * Keeps track of the world name for respawning. */ @Setter private String worldName = null; private boolean sneaking; @Setter private boolean sprinting; /** * Not updated if cache chunks is enabled. */ @Setter private boolean jumping; /** * The dimension of the player. * As all entities are in the same world, this can be safely applied to all other entities. */ @Setter private String dimension = DimensionUtils.OVERWORLD; @Setter private int breakingBlock; @Setter private Vector3i lastBlockPlacePosition; @Setter private String lastBlockPlacedId; @Setter private boolean interacting; /** * Stores the last position of the block the player interacted with. This can either be a block that the client * placed or an existing block the player interacted with (for example, a chest). <br> * Initialized as (0, 0, 0) so it is always not-null. */ @Setter private Vector3i lastInteractionPosition = Vector3i.ZERO; @Setter private Entity ridingVehicleEntity; @Setter private int craftSlot = 0; @Setter private long lastWindowCloseTime = 0; @Setter private VillagerTrade[] villagerTrades; @Setter private long lastInteractedVillagerEid; /** * Stores the enchantment information the client has received if they are in an enchantment table GUI */ private final EnchantmentInventoryTranslator.EnchantmentSlotData[] enchantmentSlotData = new EnchantmentInventoryTranslator.EnchantmentSlotData[3]; /** * The current attack speed of the player. Used for sending proper cooldown timings. * Setting a default fixes cooldowns not showing up on a fresh world. */ @Setter private double attackSpeed = 4.0d; /** * The time of the last hit. Used to gauge how long the cooldown is taking. * This is a session variable in order to prevent more scheduled threads than necessary. */ @Setter private long lastHitTime; /** * Saves if the client is steering left on a boat. */ @Setter private boolean steeringLeft; /** * Saves if the client is steering right on a boat. */ @Setter private boolean steeringRight; /** * Store the last time the player interacted. Used to fix a right-click spam bug. * See https://github.com/GeyserMC/Geyser/issues/503 for context. */ @Setter private long lastInteractionTime; /** * Stores a future interaction to place a bucket. Will be cancelled if the client instead intended to * interact with a block. */ @Setter private ScheduledFuture<?> bucketScheduledFuture; /** * Used to send a movement packet every three seconds if the player hasn't moved. Prevents timeouts when AFK in certain instances. */ @Setter private long lastMovementTimestamp = System.currentTimeMillis(); /** * Controls whether the daylight cycle gamerule has been sent to the client, so the sun/moon remain motionless. */ private boolean daylightCycle = true; private boolean reducedDebugInfo = false; @Setter private CustomFormWindow settingsForm; /** * The op permission level set by the server */ @Setter private int opPermissionLevel = 0; /** * If the current player can fly */ @Setter private boolean canFly = false; /** * If the current player is flying */ @Setter private boolean flying = false; /** * If the current player is in noclip */ @Setter private boolean noClip = false; /** * If the current player can not interact with the world */ @Setter private boolean worldImmutable = false; /** * Caches current rain status. */ @Setter private boolean raining = false; /** * Caches current thunder status. */ @Setter private boolean thunder = false; /** * Stores the last text inputted into a sign. * * Bedrock sends packets every time you update the sign, Java only wants the final packet. * Until we determine that the user has finished editing, we save the sign's current status. */ @Setter private String lastSignMessage; /** * Stores a map of all statistics sent from the server. * The server only sends new statistics back to us, so in order to show all statistics we need to cache existing ones. */ private final Map<Statistic, Integer> statistics = new HashMap<>(); /** * Whether we're expecting statistics to be sent back to us. */ @Setter private boolean waitingForStatistics = false; @Setter private List<UUID> selectedEmotes = new ArrayList<>(); private final Set<UUID> emotes = new HashSet<>(); /** * The thread that will run every 50 milliseconds - one Minecraft tick. */ private ScheduledFuture<?> tickThread = null; private MinecraftProtocol protocol; public GeyserSession(GeyserConnector connector, BedrockServerSession bedrockServerSession) { this.connector = connector; this.upstream = new UpstreamSession(bedrockServerSession); this.advancementsCache = new AdvancementsCache(this); this.bookEditCache = new BookEditCache(this); this.chunkCache = new ChunkCache(this); this.entityCache = new EntityCache(this); this.effectCache = new EntityEffectCache(); this.inventoryCache = new InventoryCache(this); this.worldCache = new WorldCache(this); this.windowCache = new WindowCache(this); this.collisionManager = new CollisionManager(this); this.playerEntity = new SessionPlayerEntity(this); this.inventory = new PlayerInventory(); this.spawned = false; this.loggedIn = false; this.inventoryCache.getInventories().put(0, inventory); // Make a copy to prevent ConcurrentModificationException final List<GeyserSession> tmpPlayers = new ArrayList<>(connector.getPlayers()); tmpPlayers.forEach(player -> this.emotes.addAll(player.getEmotes())); bedrockServerSession.addDisconnectHandler(disconnectReason -> { InetAddress address = bedrockServerSession.getRealAddress().getAddress(); connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.network.disconnect", address, disconnectReason)); disconnect(disconnectReason.name()); connector.removePlayer(this); }); } public void connect(RemoteServer remoteServer) { startGame(); this.remoteServer = remoteServer; // Set the hardcoded shield ID to the ID we just defined in StartGamePacket upstream.getSession().getHardcodedBlockingId().set(ItemRegistry.SHIELD.getBedrockId()); ChunkUtils.sendEmptyChunks(this, playerEntity.getPosition().toInt(), 0, false); BiomeDefinitionListPacket biomeDefinitionListPacket = new BiomeDefinitionListPacket(); biomeDefinitionListPacket.setDefinitions(BiomeTranslator.BIOMES); upstream.sendPacket(biomeDefinitionListPacket); AvailableEntityIdentifiersPacket entityPacket = new AvailableEntityIdentifiersPacket(); entityPacket.setIdentifiers(EntityIdentifierRegistry.ENTITY_IDENTIFIERS); upstream.sendPacket(entityPacket); CreativeContentPacket creativePacket = new CreativeContentPacket(); creativePacket.setContents(ItemRegistry.CREATIVE_ITEMS); upstream.sendPacket(creativePacket); PlayStatusPacket playStatusPacket = new PlayStatusPacket(); playStatusPacket.setStatus(PlayStatusPacket.Status.PLAYER_SPAWN); upstream.sendPacket(playStatusPacket); UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket(); attributesPacket.setRuntimeEntityId(getPlayerEntity().getGeyserId()); List<AttributeData> attributes = new ArrayList<>(); // Default move speed // Bedrock clients move very fast by default until they get an attribute packet correcting the speed attributes.add(new AttributeData("minecraft:movement", 0.0f, 1024f, 0.1f, 0.1f)); attributesPacket.setAttributes(attributes); upstream.sendPacket(attributesPacket); GameRulesChangedPacket gamerulePacket = new GameRulesChangedPacket(); // Only allow the server to send health information // Setting this to false allows natural regeneration to work false but doesn't break it being true gamerulePacket.getGameRules().add(new GameRuleData<>("naturalregeneration", false)); // Don't let the client modify the inventory on death // Setting this to true allows keep inventory to work if enabled but doesn't break functionality being false gamerulePacket.getGameRules().add(new GameRuleData<>("keepinventory", true)); // Ensure client doesn't try and do anything funky; the server handles this for us gamerulePacket.getGameRules().add(new GameRuleData<>("spawnradius", 0)); upstream.sendPacket(gamerulePacket); } public void login() { if (connector.getAuthType() != AuthType.ONLINE) { if (connector.getAuthType() == AuthType.OFFLINE) { connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.auth.login.offline")); } else { connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.auth.login.floodgate")); } authenticate(authData.getName()); } } public void authenticate(String username) { authenticate(username, ""); } public void authenticate(String username, String password) { if (loggedIn) { connector.getLogger().severe(LanguageUtils.getLocaleStringLog("geyser.auth.already_loggedin", username)); return; } loggingIn = true; // new thread so clients don't timeout new Thread(() -> { try { if (password != null && !password.isEmpty()) { AuthenticationService authenticationService; if (microsoftAccount) { authenticationService = new MsaAuthenticationService(GeyserConnector.OAUTH_CLIENT_ID); } else { authenticationService = new MojangAuthenticationService(); } authenticationService.setUsername(username); authenticationService.setPassword(password); authenticationService.login(); protocol = new MinecraftProtocol(authenticationService); } else { protocol = new MinecraftProtocol(username); } connectDownstream(); } catch (InvalidCredentialsException | IllegalArgumentException e) { connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.auth.login.invalid", username)); disconnect(LanguageUtils.getPlayerLocaleString("geyser.auth.login.invalid.kick", getClientData().getLanguageCode())); } catch (RequestException ex) { ex.printStackTrace(); } }).start(); } /** * Present a form window to the user asking to log in with another web browser */ public void authenticateWithMicrosoftCode() { if (loggedIn) { connector.getLogger().severe(LanguageUtils.getLocaleStringLog("geyser.auth.already_loggedin", getAuthData().getName())); return; } loggingIn = true; // new thread so clients don't timeout new Thread(() -> { try { MsaAuthenticationService msaAuthenticationService = new MsaAuthenticationService(GeyserConnector.OAUTH_CLIENT_ID); MsaAuthenticationService.MsCodeResponse response = msaAuthenticationService.getAuthCode(); LoginEncryptionUtils.showMicrosoftCodeWindow(this, response); // This just looks cool SetTimePacket packet = new SetTimePacket(); packet.setTime(16000); sendUpstreamPacket(packet); // Wait for the code to validate attemptCodeAuthentication(msaAuthenticationService); } catch (InvalidCredentialsException | IllegalArgumentException e) { connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.auth.login.invalid", getAuthData().getName())); disconnect(LanguageUtils.getPlayerLocaleString("geyser.auth.login.invalid.kick", getClientData().getLanguageCode())); } catch (RequestException ex) { ex.printStackTrace(); } }).start(); } /** * Poll every second to see if the user has successfully signed in */ private void attemptCodeAuthentication(MsaAuthenticationService msaAuthenticationService) { if (loggedIn || closed) { return; } try { msaAuthenticationService.login(); protocol = new MinecraftProtocol(msaAuthenticationService); connectDownstream(); } catch (RequestException e) { if (!(e instanceof AuthPendingException)) { e.printStackTrace(); } else { // Wait one second before trying again connector.getGeneralThreadPool().schedule(() -> attemptCodeAuthentication(msaAuthenticationService), 1, TimeUnit.SECONDS); } } } /** * After getting whatever credentials needed, we attempt to join the Java server. */ private void connectDownstream() { boolean floodgate = connector.getAuthType() == AuthType.FLOODGATE; final PublicKey publicKey; if (floodgate) { PublicKey key = null; try { key = EncryptionUtil.getKeyFromFile( connector.getConfig().getFloodgateKeyPath(), PublicKey.class ); } catch (IOException | InvalidKeySpecException | NoSuchAlgorithmException e) { connector.getLogger().error(LanguageUtils.getLocaleStringLog("geyser.auth.floodgate.bad_key"), e); } publicKey = key; } else publicKey = null; if (publicKey != null) { connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.auth.floodgate.loaded_key")); } // Start ticking tickThread = connector.getGeneralThreadPool().scheduleAtFixedRate(this::tick, 50, 50, TimeUnit.MILLISECONDS); downstream = new Client(remoteServer.getAddress(), remoteServer.getPort(), protocol, new TcpSessionFactory()); if (connector.getConfig().getRemote().isUseProxyProtocol()) { downstream.getSession().setFlag(BuiltinFlags.ENABLE_CLIENT_PROXY_PROTOCOL, true); downstream.getSession().setFlag(BuiltinFlags.CLIENT_PROXIED_ADDRESS, upstream.getAddress()); } if (connector.getConfig().isForwardPlayerPing()) { // Let Geyser handle sending the keep alive downstream.getSession().setFlag(MinecraftConstants.AUTOMATIC_KEEP_ALIVE_MANAGEMENT, false); } downstream.getSession().addListener(new SessionAdapter() { @Override public void packetSending(PacketSendingEvent event) { //todo move this somewhere else if (event.getPacket() instanceof HandshakePacket && floodgate) { String encrypted = ""; try { encrypted = EncryptionUtil.encryptBedrockData(publicKey, new BedrockData( clientData.getGameVersion(), authData.getName(), authData.getXboxUUID(), clientData.getDeviceOS().ordinal(), clientData.getLanguageCode(), clientData.getCurrentInputMode().ordinal(), upstream.getAddress().getAddress().getHostAddress() )); } catch (Exception e) { connector.getLogger().error(LanguageUtils.getLocaleStringLog("geyser.auth.floodgate.encrypt_fail"), e); } HandshakePacket handshakePacket = event.getPacket(); event.setPacket(new HandshakePacket( handshakePacket.getProtocolVersion(), handshakePacket.getHostname() + '\0' + BedrockData.FLOODGATE_IDENTIFIER + '\0' + encrypted, handshakePacket.getPort(), handshakePacket.getIntent() )); } } @Override public void connected(ConnectedEvent event) { loggingIn = false; loggedIn = true; if (protocol.getProfile() == null) { // Java account is offline disconnect(LanguageUtils.getPlayerLocaleString("geyser.network.remote.invalid_account", clientData.getLanguageCode())); return; } connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.network.remote.connect", authData.getName(), protocol.getProfile().getName(), remoteServer.getAddress())); playerEntity.setUuid(protocol.getProfile().getId()); playerEntity.setUsername(protocol.getProfile().getName()); String locale = clientData.getLanguageCode(); // Let the user know there locale may take some time to download // as it has to be extracted from a JAR if (locale.toLowerCase().equals("en_us") && !LocaleUtils.LOCALE_MAPPINGS.containsKey("en_us")) { // This should probably be left hardcoded as it will only show for en_us clients sendMessage("Loading your locale (en_us); if this isn't already downloaded, this may take some time"); } // Download and load the language for the player LocaleUtils.downloadAndLoadLocale(locale); } @Override public void disconnected(DisconnectedEvent event) { loggingIn = false; loggedIn = false; connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.network.remote.disconnect", authData.getName(), remoteServer.getAddress(), event.getReason())); if (event.getCause() != null) { event.getCause().printStackTrace(); } upstream.disconnect(MessageTranslator.convertMessageLenient(event.getReason())); } @Override public void packetReceived(PacketReceivedEvent event) { if (!closed) { // Required, or else Floodgate players break with Bukkit chunk caching if (event.getPacket() instanceof LoginSuccessPacket) { GameProfile profile = ((LoginSuccessPacket) event.getPacket()).getProfile(); playerEntity.setUsername(profile.getName()); playerEntity.setUuid(profile.getId()); // Check if they are not using a linked account if (connector.getAuthType() == AuthType.OFFLINE || playerEntity.getUuid().getMostSignificantBits() == 0) { SkinManager.handleBedrockSkin(playerEntity, clientData); } } PacketTranslatorRegistry.JAVA_TRANSLATOR.translate(event.getPacket().getClass(), event.getPacket(), GeyserSession.this); } } @Override public void packetError(PacketErrorEvent event) { connector.getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.network.downstream_error", event.getCause().getMessage())); if (connector.getConfig().isDebugMode()) event.getCause().printStackTrace(); event.setSuppress(true); } }); if (!daylightCycle) { setDaylightCycle(true); } downstream.getSession().connect(); connector.addPlayer(this); } public void disconnect(String reason) { if (!closed) { loggedIn = false; if (downstream != null && downstream.getSession() != null) { downstream.getSession().disconnect(reason); } if (upstream != null && !upstream.isClosed()) { connector.getPlayers().remove(this); upstream.disconnect(reason); } } if (tickThread != null) { tickThread.cancel(true); } this.advancementsCache = null; this.bookEditCache = null; this.chunkCache = null; this.entityCache = null; this.effectCache = null; this.worldCache = null; this.inventoryCache = null; this.windowCache = null; closed = true; } public void close() { disconnect(LanguageUtils.getPlayerLocaleString("geyser.network.close", getClientData().getLanguageCode())); } /** * Called every 50 milliseconds - one Minecraft tick. */ public void tick() { // Check to see if the player's position needs updating - a position update should be sent once every 3 seconds if (spawned && (System.currentTimeMillis() - lastMovementTimestamp) > 3000) { // Recalculate in case something else changed position Vector3d position = collisionManager.adjustBedrockPosition(playerEntity.getPosition(), playerEntity.isOnGround()); // A null return value cancels the packet if (position != null) { ClientPlayerPositionPacket packet = new ClientPlayerPositionPacket(playerEntity.isOnGround(), position.getX(), position.getY(), position.getZ()); sendDownstreamPacket(packet); } lastMovementTimestamp = System.currentTimeMillis(); } for (Tickable entity : entityCache.getTickableEntities()) { entity.tick(this); } } public void setAuthenticationData(AuthData authData) { this.authData = authData; } public void setSneaking(boolean sneaking) { this.sneaking = sneaking; collisionManager.updatePlayerBoundingBox(); collisionManager.updateScaffoldingFlags(); } @Override public String getName() { return authData.getName(); } @Override public void sendMessage(String message) { TextPacket textPacket = new TextPacket(); textPacket.setPlatformChatId(""); textPacket.setSourceName(""); textPacket.setXuid(""); textPacket.setType(TextPacket.Type.CHAT); textPacket.setNeedsTranslation(false); textPacket.setMessage(message); upstream.sendPacket(textPacket); } @Override public boolean isConsole() { return false; } @Override public String getLocale() { return clientData.getLanguageCode(); } public void sendForm(FormWindow window, int id) { windowCache.showWindow(window, id); } public void setRenderDistance(int renderDistance) { renderDistance = GenericMath.ceil(++renderDistance * MathUtils.SQRT_OF_TWO); //square to circle this.renderDistance = renderDistance; ChunkRadiusUpdatedPacket chunkRadiusUpdatedPacket = new ChunkRadiusUpdatedPacket(); chunkRadiusUpdatedPacket.setRadius(renderDistance); upstream.sendPacket(chunkRadiusUpdatedPacket); } public InetSocketAddress getSocketAddress() { return this.upstream.getAddress(); } public void sendForm(FormWindow window) { windowCache.showWindow(window); } private void startGame() { StartGamePacket startGamePacket = new StartGamePacket(); startGamePacket.setUniqueEntityId(playerEntity.getGeyserId()); startGamePacket.setRuntimeEntityId(playerEntity.getGeyserId()); startGamePacket.setPlayerGameType(GameType.SURVIVAL); startGamePacket.setPlayerPosition(Vector3f.from(0, 69, 0)); startGamePacket.setRotation(Vector2f.from(1, 1)); startGamePacket.setSeed(-1); startGamePacket.setDimensionId(DimensionUtils.javaToBedrock(dimension)); startGamePacket.setGeneratorId(1); startGamePacket.setLevelGameType(GameType.SURVIVAL); startGamePacket.setDifficulty(1); startGamePacket.setDefaultSpawn(Vector3i.ZERO); startGamePacket.setAchievementsDisabled(!connector.getConfig().isXboxAchievementsEnabled()); startGamePacket.setCurrentTick(-1); startGamePacket.setEduEditionOffers(0); startGamePacket.setEduFeaturesEnabled(false); startGamePacket.setRainLevel(0); startGamePacket.setLightningLevel(0); startGamePacket.setMultiplayerGame(true); startGamePacket.setBroadcastingToLan(true); startGamePacket.getGamerules().add(new GameRuleData<>("showcoordinates", connector.getConfig().isShowCoordinates())); startGamePacket.setPlatformBroadcastMode(GamePublishSetting.PUBLIC); startGamePacket.setXblBroadcastMode(GamePublishSetting.PUBLIC); startGamePacket.setCommandsEnabled(!connector.getConfig().isXboxAchievementsEnabled()); startGamePacket.setTexturePacksRequired(false); startGamePacket.setBonusChestEnabled(false); startGamePacket.setStartingWithMap(false); startGamePacket.setTrustingPlayers(true); startGamePacket.setDefaultPlayerPermission(PlayerPermission.MEMBER); startGamePacket.setServerChunkTickRange(4); startGamePacket.setBehaviorPackLocked(false); startGamePacket.setResourcePackLocked(false); startGamePacket.setFromLockedWorldTemplate(false); startGamePacket.setUsingMsaGamertagsOnly(false); startGamePacket.setFromWorldTemplate(false); startGamePacket.setWorldTemplateOptionLocked(false); String serverName = connector.getConfig().getBedrock().getServerName(); startGamePacket.setLevelId(serverName); startGamePacket.setLevelName(serverName); startGamePacket.setPremiumWorldTemplateId("00000000-0000-0000-0000-000000000000"); // startGamePacket.setCurrentTick(0); startGamePacket.setEnchantmentSeed(0); startGamePacket.setMultiplayerCorrelationId(""); startGamePacket.setItemEntries(ItemRegistry.ITEMS); startGamePacket.setVanillaVersion("*"); startGamePacket.setAuthoritativeMovementMode(AuthoritativeMovementMode.CLIENT); // can be removed once 1.16.200 support is dropped SyncedPlayerMovementSettings settings = new SyncedPlayerMovementSettings(); settings.setMovementMode(AuthoritativeMovementMode.CLIENT); settings.setRewindHistorySize(0); settings.setServerAuthoritativeBlockBreaking(false); startGamePacket.setPlayerMovementSettings(settings); upstream.sendPacket(startGamePacket); } public void addTeleport(TeleportCache teleportCache) { teleportMap.put(teleportCache.getTeleportConfirmId(), teleportCache); ObjectIterator<Int2ObjectMap.Entry<TeleportCache>> it = teleportMap.int2ObjectEntrySet().iterator(); // Remove any teleports with a higher number - maybe this is a world change that reset the ID to 0? while (it.hasNext()) { Int2ObjectMap.Entry<TeleportCache> entry = it.next(); int nextID = entry.getValue().getTeleportConfirmId(); if (nextID > teleportCache.getTeleportConfirmId()) { it.remove(); } } } public boolean confirmTeleport(Vector3d position) { if (teleportMap.size() == 0) { return true; } int teleportID = -1; for (Int2ObjectMap.Entry<TeleportCache> entry : teleportMap.int2ObjectEntrySet()) { if (entry.getValue().canConfirm(position)) { if (entry.getValue().getTeleportConfirmId() > teleportID) { teleportID = entry.getValue().getTeleportConfirmId(); } } } ObjectIterator<Int2ObjectMap.Entry<TeleportCache>> it = teleportMap.int2ObjectEntrySet().iterator(); if (teleportID != -1) { // Confirm the current teleport and any earlier ones while (it.hasNext()) { TeleportCache entry = it.next().getValue(); int nextID = entry.getTeleportConfirmId(); if (nextID <= teleportID) { ClientTeleportConfirmPacket teleportConfirmPacket = new ClientTeleportConfirmPacket(nextID); sendDownstreamPacket(teleportConfirmPacket); // Servers (especially ones like Hypixel) expect exact coordinates given back to them. ClientPlayerPositionRotationPacket positionPacket = new ClientPlayerPositionRotationPacket(playerEntity.isOnGround(), entry.getX(), entry.getY(), entry.getZ(), entry.getYaw(), entry.getPitch()); sendDownstreamPacket(positionPacket); it.remove(); connector.getLogger().debug("Confirmed teleport " + nextID); } } } if (teleportMap.size() > 0) { int resendID = -1; for (Int2ObjectMap.Entry<TeleportCache> entry : teleportMap.int2ObjectEntrySet()) { TeleportCache teleport = entry.getValue(); teleport.incrementUnconfirmedFor(); if (teleport.shouldResend()) { if (teleport.getTeleportConfirmId() >= resendID) { resendID = teleport.getTeleportConfirmId(); } } } if (resendID != -1) { connector.getLogger().debug("Resending teleport " + resendID); TeleportCache teleport = teleportMap.get(resendID); getPlayerEntity().moveAbsolute(this, Vector3f.from(teleport.getX(), teleport.getY(), teleport.getZ()), teleport.getYaw(), teleport.getPitch(), playerEntity.isOnGround(), true); } } return true; } /** * Queue a packet to be sent to player. * * @param packet the bedrock packet from the NukkitX protocol lib */ public void sendUpstreamPacket(BedrockPacket packet) { if (upstream != null) { upstream.sendPacket(packet); } else { connector.getLogger().debug("Tried to send upstream packet " + packet.getClass().getSimpleName() + " but the session was null"); } } /** * Send a packet immediately to the player. * * @param packet the bedrock packet from the NukkitX protocol lib */ public void sendUpstreamPacketImmediately(BedrockPacket packet) { if (upstream != null) { upstream.sendPacketImmediately(packet); } else { connector.getLogger().debug("Tried to send upstream packet " + packet.getClass().getSimpleName() + " immediately but the session was null"); } } /** * Send a packet to the remote server. * * @param packet the java edition packet from MCProtocolLib */ public void sendDownstreamPacket(Packet packet) { if (downstream != null && downstream.getSession() != null && (protocol.getSubProtocol().equals(SubProtocol.GAME) || packet.getClass() == LoginPluginResponsePacket.class)) { downstream.getSession().send(packet); } else { connector.getLogger().debug("Tried to send downstream packet " + packet.getClass().getSimpleName() + " before connected to the server"); } } /** * Update the cached value for the reduced debug info gamerule. * This also toggles the coordinates display * * @param value The new value for reducedDebugInfo */ public void setReducedDebugInfo(boolean value) { worldCache.setShowCoordinates(!value); reducedDebugInfo = value; } /** * Changes the daylight cycle gamerule on the client * This is used in the login screen along-side normal usage * * @param doCycle If the cycle should continue */ public void setDaylightCycle(boolean doCycle) { sendGameRule("dodaylightcycle", doCycle); // Save the value so we don't have to constantly send a daylight cycle gamerule update this.daylightCycle = doCycle; } /** * Send a gamerule value to the client * * @param gameRule The gamerule to send * @param value The value of the gamerule */ public void sendGameRule(String gameRule, Object value) { GameRulesChangedPacket gameRulesChangedPacket = new GameRulesChangedPacket(); gameRulesChangedPacket.getGameRules().add(new GameRuleData<>(gameRule, value)); upstream.sendPacket(gameRulesChangedPacket); } /** * Checks if the given session's player has a permission * * @param permission The permission node to check * @return true if the player has the requested permission, false if not */ public Boolean hasPermission(String permission) { return connector.getWorldManager().hasPermission(this, permission); } /** * Send an AdventureSettingsPacket to the client with the latest flags */ public void sendAdventureSettings() { AdventureSettingsPacket adventureSettingsPacket = new AdventureSettingsPacket(); adventureSettingsPacket.setUniqueEntityId(playerEntity.getGeyserId()); // Set command permission if OP permission level is high enough // This allows mobile players access to a GUI for doing commands. The commands there do not change above OPERATOR // and all commands there are accessible with OP permission level 2 adventureSettingsPacket.setCommandPermission(opPermissionLevel >= 2 ? CommandPermission.OPERATOR : CommandPermission.NORMAL); // Required to make command blocks destroyable adventureSettingsPacket.setPlayerPermission(opPermissionLevel >= 2 ? PlayerPermission.OPERATOR : PlayerPermission.MEMBER); // Update the noClip and worldImmutable values based on the current gamemode noClip = gameMode == GameMode.SPECTATOR; worldImmutable = gameMode == GameMode.ADVENTURE || gameMode == GameMode.SPECTATOR; Set<AdventureSetting> flags = new HashSet<>(); if (canFly) { flags.add(AdventureSetting.MAY_FLY); } if (flying) { flags.add(AdventureSetting.FLYING); } if (worldImmutable) { flags.add(AdventureSetting.WORLD_IMMUTABLE); } if (noClip) { flags.add(AdventureSetting.NO_CLIP); } flags.add(AdventureSetting.AUTO_JUMP); adventureSettingsPacket.getSettings().addAll(flags); sendUpstreamPacket(adventureSettingsPacket); } /** * Used for updating statistic values since we only get changes from the server * * @param statistics Updated statistics values */ public void updateStatistics(@NonNull Map<Statistic, Integer> statistics) { this.statistics.putAll(statistics); } public void refreshEmotes(List<UUID> emotes) { this.selectedEmotes = emotes; this.emotes.addAll(emotes); for (GeyserSession player : connector.getPlayers()) { List<UUID> pieces = new ArrayList<>(); for (UUID piece : emotes) { if (!player.getEmotes().contains(piece)) { pieces.add(piece); } player.getEmotes().add(piece); } EmoteListPacket emoteList = new EmoteListPacket(); emoteList.setRuntimeEntityId(player.getPlayerEntity().getGeyserId()); emoteList.getPieceIds().addAll(pieces); player.sendUpstreamPacket(emoteList); } } }
40.899907
190
0.66604
996daf0feca9133e94dd7ca374dc4094f3d79545
414
/* * All source is copyrighted by Slenderware */ package com.slender.app.factory; import com.slender.domain.UserProject; public class UserProjectFactory { public UserProject getUserProject(int userId, int porjectId){ UserProject userProject = new UserProject(); userProject.setProjectId(porjectId); userProject.setUserId(userId); return userProject; } }
25.875
66
0.693237
3a5ec38fcdc4ab8bb0514d78ea7a7871fa3e043a
151
package com.trio.breakFast.dao; import com.trio.breakFast.model.Questionnaire; public interface QuestionnaireDao extends BaseDao<Questionnaire> { }
18.875
66
0.821192
902e5f03ae235ccff4d1d5702ca90ca4e4bd34f9
5,342
package org.ripple.bouncycastle.crypto.tls; import java.io.IOException; import org.ripple.bouncycastle.crypto.Mac; import org.ripple.bouncycastle.crypto.engines.ChaChaEngine; import org.ripple.bouncycastle.crypto.generators.Poly1305KeyGenerator; import org.ripple.bouncycastle.crypto.macs.Poly1305; import org.ripple.bouncycastle.crypto.params.KeyParameter; import org.ripple.bouncycastle.crypto.params.ParametersWithIV; import org.ripple.bouncycastle.util.Arrays; import org.ripple.bouncycastle.util.Pack; public class Chacha20Poly1305 implements TlsCipher { protected TlsContext context; protected ChaChaEngine encryptCipher; protected ChaChaEngine decryptCipher; public Chacha20Poly1305(TlsContext context) throws IOException { if (!TlsUtils.isTLSv12(context)) { throw new TlsFatalAlert(AlertDescription.internal_error); } this.context = context; byte[] key_block = TlsUtils.calculateKeyBlock(context, 64); KeyParameter client_write_key = new KeyParameter(key_block, 0, 32); KeyParameter server_write_key = new KeyParameter(key_block, 32, 32); this.encryptCipher = new ChaChaEngine(20); this.decryptCipher = new ChaChaEngine(20); KeyParameter encryptKey, decryptKey; if (context.isServer()) { encryptKey = server_write_key; decryptKey = client_write_key; } else { encryptKey = client_write_key; decryptKey = server_write_key; } byte[] dummyNonce = new byte[8]; this.encryptCipher.init(true, new ParametersWithIV(encryptKey, dummyNonce)); this.decryptCipher.init(false, new ParametersWithIV(decryptKey, dummyNonce)); } public int getPlaintextLimit(int ciphertextLimit) { return ciphertextLimit - 16; } public byte[] encodePlaintext(long seqNo, short type, byte[] plaintext, int offset, int len) throws IOException { int ciphertextLength = len + 16; KeyParameter macKey = initRecordMAC(encryptCipher, true, seqNo); byte[] output = new byte[ciphertextLength]; encryptCipher.processBytes(plaintext, offset, len, output, 0); byte[] additionalData = getAdditionalData(seqNo, type, len); byte[] mac = calculateRecordMAC(macKey, additionalData, output, 0, len); System.arraycopy(mac, 0, output, len, mac.length); return output; } public byte[] decodeCiphertext(long seqNo, short type, byte[] ciphertext, int offset, int len) throws IOException { if (getPlaintextLimit(len) < 0) { throw new TlsFatalAlert(AlertDescription.decode_error); } int plaintextLength = len - 16; byte[] receivedMAC = Arrays.copyOfRange(ciphertext, offset + plaintextLength, offset + len); KeyParameter macKey = initRecordMAC(decryptCipher, false, seqNo); byte[] additionalData = getAdditionalData(seqNo, type, plaintextLength); byte[] calculatedMAC = calculateRecordMAC(macKey, additionalData, ciphertext, offset, plaintextLength); if (!Arrays.constantTimeAreEqual(calculatedMAC, receivedMAC)) { throw new TlsFatalAlert(AlertDescription.bad_record_mac); } byte[] output = new byte[plaintextLength]; decryptCipher.processBytes(ciphertext, offset, plaintextLength, output, 0); return output; } protected KeyParameter initRecordMAC(ChaChaEngine cipher, boolean forEncryption, long seqNo) { byte[] nonce = new byte[8]; TlsUtils.writeUint64(seqNo, nonce, 0); cipher.init(forEncryption, new ParametersWithIV(null, nonce)); byte[] firstBlock = new byte[64]; cipher.processBytes(firstBlock, 0, firstBlock.length, firstBlock, 0); // NOTE: The BC implementation puts 'r' after 'k' System.arraycopy(firstBlock, 0, firstBlock, 32, 16); KeyParameter macKey = new KeyParameter(firstBlock, 16, 32); Poly1305KeyGenerator.clamp(macKey.getKey()); return macKey; } protected byte[] calculateRecordMAC(KeyParameter macKey, byte[] additionalData, byte[] buf, int off, int len) { Mac mac = new Poly1305(); mac.init(macKey); updateRecordMAC(mac, additionalData, 0, additionalData.length); updateRecordMAC(mac, buf, off, len); byte[] output = new byte[mac.getMacSize()]; mac.doFinal(output, 0); return output; } protected void updateRecordMAC(Mac mac, byte[] buf, int off, int len) { mac.update(buf, off, len); byte[] longLen = Pack.longToLittleEndian(len & 0xFFFFFFFFL); mac.update(longLen, 0, longLen.length); } protected byte[] getAdditionalData(long seqNo, short type, int len) throws IOException { /* * additional_data = seq_num + TLSCompressed.type + TLSCompressed.version + * TLSCompressed.length */ byte[] additional_data = new byte[13]; TlsUtils.writeUint64(seqNo, additional_data, 0); TlsUtils.writeUint8(type, additional_data, 8); TlsUtils.writeVersion(context.getServerVersion(), additional_data, 9); TlsUtils.writeUint16(len, additional_data, 11); return additional_data; } }
34.025478
117
0.672969
3a787b97936ae18f69680f83cbc0f9d7e737d1c7
1,126
package com.ilad.teamwork; import org.openqa.selenium.WebElement; import io.appium.java_client.android.AndroidDriver; public class ListFilter extends AbstractTeamWork { public ListFilter(AndroidDriver<WebElement> driver) { super(driver); } /** * @deprecated not fully implemented * @param typeOfTaskLists * @return */ public AbstractListTypes chooseTaskListsType(TaskListsFilter typeOfTaskLists) { WebElement element = driver.findElementByXPath("//android.widget.TextView" + "[@text='" + typeOfTaskLists.getTaskListsFilterValue() + "']"); driver.tap(1, element, 100); switch (typeOfTaskLists) { case ACTIVE_TASK_LIST_FILTER: return new ActiveTaskListsPage(driver); case COMPETED_TASK_LISTS: return new CompletedTaskListsPage(driver); default: return null; } } public enum TaskListsFilter { COMPETED_TASK_LISTS("Completed Task Lists"), ACTIVE_TASK_LIST_FILTER("Active Task Lists"); private final String value; private TaskListsFilter(final String value) { this.value = value; } public String getTaskListsFilterValue() { return value; } } }
22.979592
80
0.738011
0c265a493141a557c22b30a6957984fc8d23a56c
781
package br.com.ecommerce.mercadolivre.service; import br.com.ecommerce.mercadolivre.consumer.NotaFiscal; import br.com.ecommerce.mercadolivre.domain.model.Compra; import br.com.ecommerce.mercadolivre.service.EventosCompraSucesso; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; /** * Carga intrínseca máxima permitida - 7 * Carga intrínseca da classe - 3 */ @Service // +1 public class NotaFiscalImpl implements EventosCompraSucesso { @Autowired // +1 private NotaFiscal notaFiscal; @Override // +1 public void processa(Compra compra) { notaFiscal.processa(Map.of("compraId", compra.getId(), "compradorId", compra.compradorId())); } }
24.40625
66
0.736236
023a8bcdabd9cf3c16a203c422b3dbd2fc64e7a8
1,378
package io.github.simplycmd.terracraft.items; import io.github.simplycmd.terracraft.items.util.BaseItem; import io.github.simplycmd.terracraft.items.util.Value; import io.github.simplycmd.terracraft.registry.EntityRegistry; import io.github.simplycmd.terracraft.entities.grenade.GrenadeEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.world.World; public class GrenadeThrowableItem extends Item implements BaseItem { public GrenadeThrowableItem(Settings settings) { super(settings); } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity playerEntity, Hand hand) { GrenadeEntity grenade = new GrenadeEntity(EntityRegistry.GRENADE, world); grenade.updatePosition(playerEntity.getX(), playerEntity.getY() + 2, playerEntity.getZ()); grenade.setProperties(playerEntity, playerEntity.getPitch(), playerEntity.getYaw(), 0.0F); world.spawnEntity(grenade); return TypedActionResult.success(playerEntity.getStackInHand(hand)); } @Override public Value getBuyValue() { return new Value(0, 0, 0, 75); } @Override public Value getSellValue() { return new Value(0, 0, 0, 15); } }
36.263158
98
0.748186
5361462eff99c3e55bd35bd92d11029bd7efce3b
1,341
/** * Copyright 2019 The JoyQueue Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.chubao.joyqueue.handler.routing.command.topic; import io.chubao.joyqueue.handler.routing.command.NsrCommandSupport; import io.chubao.joyqueue.model.domain.Namespace; import io.chubao.joyqueue.model.query.QNamespace; import io.chubao.joyqueue.service.NamespaceService; import com.jd.laf.web.vertx.annotation.Path; import com.jd.laf.web.vertx.response.Response; import com.jd.laf.web.vertx.response.Responses; /** * 命名空间 处理器 * Created by chenyanying3 on 2018-11-14. */ public class NamespaceCommand extends NsrCommandSupport<Namespace, NamespaceService, QNamespace> { @Path("findAll") public Response findAll() throws Exception { return Responses.success(service.findByQuery(new QNamespace())); } }
35.289474
98
0.762118
9362d7afbcfecaf6e238136f906e88f681a4437f
460
package hw; /* * 讓使用者輸入一正整數n,計算1*(1+1) + 2*(2+1) + 3*(3+1) + … + n*(n+1)並輸出結果。 */ import java.util.Scanner; public class hw05_104021074 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); System.out.println("請輸入n:"); int n = scn.nextInt(); int sum = 0 ; int i ; for(i =1 ; i <=n; i++){ int a= sum; sum = i*(i+1); sum = sum +a; }System.out.println("總和為:"+sum); } }
20
64
0.576087
8550b9a5526a67b13b8c64020e497650f66b71c9
1,441
package wafflestomper.logbot.util; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; public class ConfigManager { private Configuration config; public boolean logChests = true; public boolean logMinedBlocks = true; public boolean onlyLogOres = true; public boolean logSpawners = true; public boolean logToDB = true; public boolean logToTextFiles = false; public void preInit(FMLPreInitializationEvent event){ this.config = new Configuration(event.getSuggestedConfigurationFile()); this.config.load(); this.logChests = this.config.get("input", "log_chest_contents", true, "Log the contents of any chests you open").getBoolean(true); this.logMinedBlocks = this.config.get("input", "log_mined_blocks", true, "Log the positions of blocks you mine").getBoolean(true); this.onlyLogOres = this.config.get("input", "only_log_ores", true, "Only log mined ores (ignore all other blocks)").getBoolean(true); this.logSpawners = this.config.get("input", "log_mob_spawners", true, "Log the positions of any detected mob spawners").getBoolean(true); this.logToDB = this.config.get("output", "output_to_db", true, "SQLite database output").getBoolean(true); this.logToTextFiles = this.config.get("output", "output_to_textfiles", false, "Text file output").getBoolean(false); this.config.save(); } }
45.03125
142
0.741846
eb6828c39a554a329af79057d37f1f47d46afb84
1,338
package lk.usj.OPD_Management.java.common.tool; import javafx.event.ActionEvent; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; public final class ButtonFireForEnterSetter { public static void setGlobalEventHandler(Pane root) { new Thread(() -> setGlobalEventHandlerOnPrivate(root)).start(); } private static void setGlobalEventHandlerOnPrivate(Pane root) { for (Node node : root.getChildren()) { if (node instanceof Pane) setGlobalEventHandlerOnPrivate((Pane) node); if (node instanceof Button) { node.addEventHandler(KeyEvent.KEY_PRESSED, ev -> { if (ev.getCode() == KeyCode.ENTER) { ((Button) node).fire(); ev.consume(); } }); } if (node instanceof DatePicker) { node.addEventHandler(KeyEvent.KEY_PRESSED, ev -> { if (ev.getCode() == KeyCode.ENTER) { node.fireEvent(new ActionEvent()); ev.consume(); } }); } } } }
31.857143
71
0.556054
ff803b30d1012ee277581bd8d6bfde82ae0012e8
2,120
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package service; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Produces; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.simple.JSONObject; /** * REST Web Service * * @author Nikos */ @Path("login/{username}/{pass}")//Τo URI path template εκεί όπου αποκρίνεται το web service public class Login { @Context private UriInfo context; /** * Creates a new instance of Login */ public Login() { } /** * Retrieves representation of an instance of service.WSLogin * * @param username * @param pass * * @return an instance of java.lang.String */ @GET//Επεξεργάζεται αιτήσεις με την μέθοδο get @Produces(MediaType.APPLICATION_JSON)//Επιστρέφει στον πελάτη αποτέλεσμα σε json μορφή //Συνάρτηση που επιστρέφει αντικείμενο απόκρισης(Response) με ορίσματα το όνομα χρήστη και τον κωδικό public Response getResponse(@PathParam("username") String username, @PathParam("pass") String pass) { String resp;//String μεταβλητή για την εκχώρηση σε αυτό το String ταυτοποίησης JSONObject response = new JSONObject();//Δημιουργία JSON αντικειμένου DBCheck ch = DBCheck.getInstance();//Δημιουργία instance της κλάσης DBCheck resp = ch.search(username, pass); //εκχώρηση στην μεταβλητή StringID της συνάρτησης search response.put(resp, username);//Εκχώρηση στο αντικείμενο την τιμή(value) username με όνομα το StringID(name/value) //Επιστροφή αντικειμένου απόκρισης(Response χρησιμοποιώντας την κλάση ResponseBuilder) //με entity το αντικέιμενο JSON σε String τύπο return Response.ok().entity(response.toString()).build();//Δημιουργία απόκρισης με status ok }//end-getString }
32.121212
122
0.693396
19094f31377c7dd9a531a14752066d58310914b7
3,741
package seedu.address.ui; import java.util.logging.Logger; import javafx.animation.Animation; import javafx.animation.FadeTransition; import javafx.animation.KeyFrame; import javafx.animation.PauseTransition; import javafx.animation.Timeline; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.util.Duration; import seedu.address.commons.core.LogsCenter; /** * Controller for the Welcome Window */ public class WelcomeWindow extends UiPart<Stage> { private static final Logger logger = LogsCenter.getLogger(WelcomeWindow.class); private static final String FXML = "WelcomeWindow.fxml"; private final String tagLine = "TYPE. EXPLORE. CONNECT. "; private final double delayTime = (tagLine.length() * 5) + 100; private final Image appLogoImage = new Image(this.getClass().getResourceAsStream("/images/logo.png")); @FXML private Label appTagLine; @FXML private ImageView appLogo; /** * Creates a new WelcomeWindow. */ public WelcomeWindow() { super(FXML, new Stage()); } /** * Helps in Creating a WelcomeWindow. */ public void start(MainWindow mainWindow) { // To show the welcome window logger.fine("Showing Welcome Window (App has started)"); getRoot().initStyle(StageStyle.UNDECORATED); getRoot().show(); getRoot().centerOnScreen(); getRoot().setAlwaysOnTop(true); appLogo.setImage(appLogoImage); displayAnimatedText(tagLine, delayTime); // To add the fading effect on the app logo. fadeTransition(); // To close the WelcomeWindow after a specified amount of time. close(mainWindow); } /** * Handles the closing of the WelcomeWindow created, and * launching of the MainWindow. */ public void close(MainWindow mainWindow) { PauseTransition delay = new PauseTransition(Duration.millis(delayTime * tagLine.length() + 100)); delay.setOnFinished(event -> { getRoot().close(); mainWindow.show(); }); delay.play(); } /** * Handles the fading in effect of the picture (here app logo) * in the WelcomeWindow. */ public void fadeTransition() { FadeTransition fadeOut = new FadeTransition(Duration.millis(4200), appLogo); fadeOut.setFromValue(0.0); fadeOut.setToValue(1.0); fadeOut.play(); } /** * Handles the animation effect of characters in the WelcomeWindow. * The characters of the text passed are printed one by one after * a certain amount of delay. * * @param textToDisplay The text to be displayed on the WelcomeWindow stage. * @param delayTime The delay after which each character is to be printed. */ // Solution below adapted from https://stackoverflow.com/a/33648481 public void displayAnimatedText(String textToDisplay, double delayTime) { IntegerProperty i = new SimpleIntegerProperty(0); Timeline timeline = new Timeline(); KeyFrame keyFrame = new KeyFrame(Duration.millis(delayTime), event -> { if (i.get() > textToDisplay.length()) { timeline.stop(); } else { appTagLine.setText(textToDisplay.substring(0, i.get())); i.set(i.get() + 1); } }); timeline.getKeyFrames().add(keyFrame); timeline.setCycleCount(Animation.INDEFINITE); timeline.play(); } }
31.70339
106
0.662122
3226a4f17cf1f8e13cc6cccd374c06a07c457236
600
package com.github.paulzappia; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.block.SlabBlock; public class StainedSandstoneBlockSlab extends SlabBlock { public StainedSandstoneBlockSlab(Settings settings) { super(FabricBlockSettings.copyOf(Blocks.SANDSTONE_SLAB).breakByTool(FabricToolTags.PICKAXES));//.strength(0.8F)); } @Override protected Block asBlock() { return super.asBlock(); } }
37.5
121
0.791667
029149026f5c74356e4409c484a405f2c6069db2
322
package com.harium.suneidesis.chat.output; import java.io.IOException; public interface Output { void print(String sentence); void print(String sentence, OutputContext context); void produceFile(String path, String description) throws IOException; void produceFile(byte[] data, String description); }
23
73
0.76087
ef9e81817ce16df2bf48826839b0f3c7d4731bcc
2,538
package com.cms.scaffold.micro.sys.controller; import com.cms.scaffold.common.base.BaseController; import com.cms.scaffold.common.builder.Builder; import com.cms.scaffold.common.response.ResponseModel; import com.cms.scaffold.micro.sys.ao.SysMenuAO; import com.cms.scaffold.micro.sys.api.SysMenuApi; import com.cms.scaffold.micro.sys.bo.SysMenuBO; import com.cms.scaffold.micro.sys.domain.SysMenu; import com.cms.scaffold.micro.sys.service.SysMenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author zhang * 菜单资源微服务接口 * 接口地址在API中声明 * 接口与实现分离 */ @RestController public class SysMenuController extends BaseController implements SysMenuApi { @Autowired SysMenuService sysMenuService; @Override public ResponseModel<List<SysMenuBO>> listMenuByPid(Long pid) { List<SysMenu> sysMenuList = sysMenuService.selectByPid(pid); List<SysMenuBO> bo = Builder.buildList(sysMenuList, SysMenuBO.class); return successData(bo); } /** * @param id 主键 * @return 根据主键查询 */ @Override public ResponseModel<SysMenuBO> selectById(Long id) { final SysMenu sysMenu = sysMenuService.selectById(id); return successData(Builder.build(sysMenu, SysMenuBO.class)); } @Override public ResponseModel<List<SysMenuBO>> findAll() { List<SysMenu> sysMenus = sysMenuService.findList(new SysMenu()); return successData(Builder.buildList(sysMenus, SysMenuBO.class)); } @Override public ResponseModel<List<SysMenuBO>> findByOperateId(Long id) { final List<SysMenu> sysMenu = sysMenuService.findByOperateId(id); return successData(Builder.buildList(sysMenu, SysMenuBO.class)); } @Override public ResponseModel<List<SysMenuBO>> findByPidAndOperateId(Long pId, Long operateId) { final List<SysMenu> sysMenus = sysMenuService.findByPidAndOperateId(pId, operateId); return successData(Builder.buildList(sysMenus, SysMenuBO.class)); } @Override public ResponseModel saveOrUpdate(@RequestBody SysMenuAO ao) { SysMenu menu = Builder.build(ao, SysMenu.class); sysMenuService.saveOrUpdate(menu); return success(); } @Override public ResponseModel<String> findFatherIds(Long id) { String pIds = sysMenuService.findFatherIds(id); return successData(pIds); } }
32.961039
92
0.729708
852bd0d3d9377fd115d5980d98722dd591880767
9,004
/* * Copyright 2020 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.couchbase.repository.query; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.reactivestreams.Publisher; import org.springframework.data.couchbase.core.CouchbaseOperations; import org.springframework.data.couchbase.core.ExecutableFindByQueryOperation; import org.springframework.data.couchbase.core.query.Query; import org.springframework.data.mapping.model.EntityInstantiators; import org.springframework.data.repository.core.EntityMetadata; import org.springframework.data.repository.query.ParameterAccessor; import org.springframework.data.repository.query.ParametersParameterAccessor; import org.springframework.data.repository.query.QueryMethodEvaluationContextProvider; import org.springframework.data.repository.query.RepositoryQuery; import org.springframework.data.repository.query.ResultProcessor; import org.springframework.data.util.ClassTypeInformation; import org.springframework.data.util.TypeInformation; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * {@link RepositoryQuery} implementation for Couchbase. CouchbaseOperationsType is either CouchbaseOperations or * ReactiveCouchbaseOperations * * @author Michael Reiche * @since 4.1 */ public abstract class AbstractCouchbaseQueryBase<CouchbaseOperationsType> implements RepositoryQuery { private final CouchbaseQueryMethod method; private final CouchbaseOperationsType operations; private final EntityInstantiators instantiators; private final ExecutableFindByQueryOperation.ExecutableFindByQuery<?> findOperationWithProjection; private final SpelExpressionParser expressionParser; private final QueryMethodEvaluationContextProvider evaluationContextProvider; /** * Creates a new {@link AbstractCouchbaseQuery} from the given {@link ReactiveCouchbaseQueryMethod} and * {@link org.springframework.data.couchbase.core.CouchbaseOperations}. * * @param method must not be {@literal null}. * @param operations must not be {@literal null}. * @param expressionParser must not be {@literal null}. * @param evaluationContextProvider must not be {@literal null}. */ public AbstractCouchbaseQueryBase(CouchbaseQueryMethod method, CouchbaseOperationsType operations, SpelExpressionParser expressionParser, QueryMethodEvaluationContextProvider evaluationContextProvider) { Assert.notNull(method, "CouchbaseQueryMethod must not be null!"); Assert.notNull(operations, "ReactiveCouchbaseOperations must not be null!"); Assert.notNull(expressionParser, "SpelExpressionParser must not be null!"); Assert.notNull(evaluationContextProvider, "QueryMethodEvaluationContextProvider must not be null!"); this.method = method; this.operations = operations; this.instantiators = new EntityInstantiators(); this.expressionParser = expressionParser; this.evaluationContextProvider = evaluationContextProvider; EntityMetadata<?> metadata = method.getEntityInformation(); Class<?> type = metadata.getJavaType(); this.findOperationWithProjection = operations instanceof CouchbaseOperations ? ((CouchbaseOperations) operations).findByQuery(type) : null; // not yet implemented for Reactive } /* * (non-Javadoc) * @see org.springframework.data.repository.query.RepositoryQuery#getQueryMethod() */ public CouchbaseQueryMethod getQueryMethod() { return method; }; /* * (non-Javadoc) */ public CouchbaseOperationsType getOperations() { return operations; } /* * (non-Javadoc) */ EntityInstantiators getInstantiators() { return instantiators; } /** * Execute the query with the provided parameters * * @see org.springframework.data.repository.query.RepositoryQuery#execute(java.lang.Object[]) */ public Object execute(Object[] parameters) { return method.hasReactiveWrapperParameter() ? executeDeferred(parameters) : execute(new ReactiveCouchbaseParameterAccessor(getQueryMethod(), parameters)); } private Object executeDeferred(Object[] parameters) { ReactiveCouchbaseParameterAccessor parameterAccessor = new ReactiveCouchbaseParameterAccessor(method, parameters); if (getQueryMethod().isCollectionQuery()) { return Flux.defer(() -> (Publisher<Object>) execute(parameterAccessor)); } return Mono.defer(() -> (Mono<Object>) execute(parameterAccessor)); } private Object execute(ParametersParameterAccessor parameterAccessor) { TypeInformation<?> returnType = ClassTypeInformation .from(method.getResultProcessor().getReturnedType().getReturnedType()); ResultProcessor processor = method.getResultProcessor().withDynamicProjection(parameterAccessor); Class<?> typeToRead = processor.getReturnedType().getTypeToRead(); if (typeToRead == null && returnType.getComponentType() != null) { typeToRead = returnType.getComponentType().getType(); } return doExecute(getQueryMethod(), processor, parameterAccessor, typeToRead); } /** * Execute the {@link RepositoryQuery} of the given method with the parameters provided by the * {@link ParametersParameterAccessor accessor} * * @param method the {@link ReactiveCouchbaseQueryMethod} invoked. Never {@literal null}. * @param processor {@link ResultProcessor} for post procession. Never {@literal null}. * @param accessor for providing invocation arguments. Never {@literal null}. * @param typeToRead the desired component target type. Can be {@literal null}. */ abstract protected Object doExecute(CouchbaseQueryMethod method, ResultProcessor processor, ParametersParameterAccessor accessor, @Nullable Class<?> typeToRead); /** * Add a scan consistency from {@link org.springframework.data.couchbase.repository.ScanConsistency} to the given * {@link Query} if present. * * @param query the {@link Query} to potentially apply the sort to. * @return the query with potential scan consistency applied. * @since 4.1 */ Query applyAnnotatedConsistencyIfPresent(Query query) { if (!method.hasScanConsistencyAnnotation()) { return query; } return query.scanConsistency(method.getScanConsistencyAnnotation().query()); } /** * Creates a {@link Query} instance using the given {@link ParametersParameterAccessor}. Will delegate to * {@link #createQuery(ParametersParameterAccessor)} by default but allows customization of the count query to be * triggered. * * @param accessor must not be {@literal null}. * @return */ protected abstract Query createCountQuery(ParametersParameterAccessor accessor); /** * Creates a {@link Query} instance using the given {@link ParameterAccessor} * * @param accessor must not be {@literal null}. * @return */ protected abstract Query createQuery(ParametersParameterAccessor accessor); /* * (non-Javadoc) * @see org.springframework.data.couchbase.repository.query.AbstractReactiveCouchbaseQuery#isCountQuery() */ protected boolean isCountQuery() { return getQueryMethod().isCountQuery(); } /* * (non-Javadoc) * @see org.springframework.data.couchbase.repository.query.AbstractReactiveCouchbaseQuery#isExistsQuery() */ protected boolean isExistsQuery() { return getQueryMethod().isExistsQuery(); } /* * (non-Javadoc) * @see org.springframework.data.couchbase.repository.query.AbstractReactiveCouchbaseQuery#isDeleteQuery() */ protected boolean isDeleteQuery() { return getQueryMethod().isDeleteQuery(); } /** * Return whether the query is tailable * * @return */ boolean isTailable(CouchbaseQueryMethod method) { return false; // method.getTailableAnnotation() != null; // Not yet implemented } /** * Return whether the query has an explicit limit set. * * @return */ protected abstract boolean isLimiting(); /** * Return whether there are ambiguous projection flags * * @return */ static boolean hasAmbiguousProjectionFlags(boolean isCountQuery, boolean isExistsQuery, boolean isDeleteQuery) { return multipleOf(isCountQuery, isExistsQuery, isDeleteQuery); } /** * Count the number of {@literal true} values. * * @param values * @return are there more than one of these true? */ static boolean multipleOf(boolean... values) { int count = 0; for (boolean value : values) { if (value) { if (count != 0) { return true; } count++; } } return false; } }
36.160643
116
0.768547
76518975b7184bca67082bbefcb34d81b71b2c96
4,154
package utn.frba.mobile.experienciaapp.models; import android.net.Uri; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import retrofit2.Call; import utn.frba.mobile.experienciaapp.lib.ws.ResponseWS; import utn.frba.mobile.experienciaapp.lib.ws.WSRetrofit; public class Turista extends ModeloGenerico{ @SerializedName("id") @Expose private int id; @SerializedName("email") @Expose private String email; @SerializedName("login_token") @Expose private String loginToken; @SerializedName("login_type") @Expose private String loginType; @SerializedName("firebase_token") @Expose private String firebaseToken; @SerializedName("last_longitud") @Expose private Double lastLongitud; @SerializedName("last_latitud") @Expose private Double lastLatitud; @SerializedName("last_geo_update") @Expose private String lastGeoUpdate; @SerializedName("last_request") @Expose private String lastRequest; private Uri imageUrl; public static Call<ResponseWS> SignIn(Turista turista){ //TODO: Validacion de turista seteado String l_long = ""; String l_lat = ""; if(turista.getLastLongitud() != null) l_long = turista.getLastLongitud().toString(); if(turista.getLastLatitud() != null) l_lat = turista.getLastLatitud().toString(); return WSRetrofit.getInstance().signInTurista( WSRetrofit.APARTADO, WSRetrofit.KEY, WSRetrofit.SIGN_IN_TURISTA, turista.getEmail(), turista.firebaseToken, l_long, l_lat ); } public static Call<ResponseWS> loginTurista(Turista turista){ //TODO: Validacion de turista seteado String l_long = ""; String l_lat = ""; if(turista.getLastLongitud() != null) l_long = turista.getLastLongitud().toString(); if(turista.getLastLatitud() != null) l_lat = turista.getLastLatitud().toString(); return WSRetrofit.getInstance().loginTurista( WSRetrofit.APARTADO, WSRetrofit.KEY, WSRetrofit.LOGIN_TURISTA, turista.getEmail(), turista.firebaseToken ); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLoginToken() { return loginToken; } public void setLoginToken(String loginToken) { this.loginToken = loginToken; } public String getLoginType() { return loginType; } public void setLoginType(String loginType) { this.loginType = loginType; } public String getFirebaseToken() { return firebaseToken; } public void setFirebaseToken(String firebaseToken) { this.firebaseToken = firebaseToken; } public Double getLastLongitud() { return lastLongitud; } public void setLastLongitud(Double lastLongitud) { this.lastLongitud = lastLongitud; } public Double getLastLatitud() { return lastLatitud; } public void setLastLatitud(Double lastLatitud) { this.lastLatitud = lastLatitud; } public String getLastGeoUpdate() { return lastGeoUpdate; } public void setLastGeoUpdate(String lastGeoUpdate) { this.lastGeoUpdate = lastGeoUpdate; } public String getLastRequest() { return lastRequest; } public void setLastRequest(String lastRequest) { this.lastRequest = lastRequest; } public Uri getImageUrl() { return imageUrl; } public void setImageUrl(Uri imageUrl) { this.imageUrl = imageUrl; } }
25.484663
66
0.60207
a09401a9ae2a742e630c58acfb25ab6530da0132
361
package com.atishay.app.testNg; import com.atishay.app.BaseTest; import org.testng.ITestResult; import org.testng.TestListenerAdapter; /** * Created by Atishay on 6/7/2015. */ public class Listener extends TestListenerAdapter { @Override public void onTestFailure(ITestResult result) { BaseTest.takeScreenshot(result.getTestName()); } }
22.5625
54
0.745152
7533e3e7cdeb7fe09550e6869e6716a971a0d9d8
4,112
package ru.ilnyrdiplom.bestedu.web.controllers; import lombok.RequiredArgsConstructor; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; import ru.ilnyrdiplom.bestedu.facade.exceptions.EntityNotFoundException; import ru.ilnyrdiplom.bestedu.facade.exceptions.WrongAccessDisciplineStatusException; import ru.ilnyrdiplom.bestedu.facade.model.AccessDisciplineFacade; import ru.ilnyrdiplom.bestedu.facade.model.enums.AccessDisciplineStatus; import ru.ilnyrdiplom.bestedu.facade.model.enums.Role; import ru.ilnyrdiplom.bestedu.facade.services.AccessDisciplineServiceFacade; import ru.ilnyrdiplom.bestedu.web.contracts.responses.ApiResponse; import ru.ilnyrdiplom.bestedu.web.model.TokenPrincipal; import java.util.List; @RestController @RequestMapping( produces = MediaType.APPLICATION_JSON_VALUE) @RequiredArgsConstructor public class AccessDisciplineController { private final AccessDisciplineServiceFacade accessDisciplineService; @Secured({Role.TEACHER, Role.STUDENT}) @PostMapping("/disciplines/{disciplineId}/access-discipline/") public ResponseEntity<ApiResponse<AccessDisciplineFacade>> createRequestAccessDiscipline( @AuthenticationPrincipal TokenPrincipal tokenPrincipal, @PathVariable int disciplineId ) throws WrongAccessDisciplineStatusException, EntityNotFoundException { AccessDisciplineFacade accessDiscipline = accessDisciplineService .createRequestAccessDiscipline(tokenPrincipal.getAccountIdentity(), () -> disciplineId); return ApiResponse.success(accessDiscipline); } @Secured(Role.TEACHER) @PutMapping("/disciplines/{disciplineId}/access-discipline/{accessDisciplineId}/accept/") public ResponseEntity<ApiResponse<AccessDisciplineFacade>> acceptAccessDiscipline(@AuthenticationPrincipal TokenPrincipal tokenPrincipal, @PathVariable int disciplineId, @PathVariable int accessDisciplineId ) throws WrongAccessDisciplineStatusException, EntityNotFoundException { AccessDisciplineFacade accessDiscipline = accessDisciplineService .acceptAccessDiscipline(tokenPrincipal.getAccountIdentity(), () -> disciplineId, () -> accessDisciplineId); return ApiResponse.success(accessDiscipline); } @Secured(Role.TEACHER) @PutMapping("/disciplines/{disciplineId}/access-discipline/{accessDisciplineId}/reject/") public ResponseEntity<ApiResponse<AccessDisciplineFacade>> rejectAccessDiscipline(@AuthenticationPrincipal TokenPrincipal tokenPrincipal, @PathVariable int disciplineId, @PathVariable int accessDisciplineId ) throws EntityNotFoundException { AccessDisciplineFacade accessDiscipline = accessDisciplineService .rejectAccessDiscipline(tokenPrincipal.getAccountIdentity(), () -> disciplineId, () -> accessDisciplineId); return ApiResponse.success(accessDiscipline); } @Secured({Role.TEACHER}) @GetMapping("/access-discipline/") public ResponseEntity<ApiResponse<List<? extends AccessDisciplineFacade>>> getAllByTeacher( @AuthenticationPrincipal TokenPrincipal tokenPrincipal, @RequestParam(required = false) Integer disciplineId, @RequestParam(required = false) AccessDisciplineStatus status ) throws EntityNotFoundException { List<? extends AccessDisciplineFacade> accessDisciplines = accessDisciplineService .getAccessDisciplines(tokenPrincipal.getAccountIdentity(), () -> disciplineId, status); return ApiResponse.success(accessDisciplines); } }
56.328767
141
0.728599
985ae71af7984b7722686c2be5a4bf914b0ca1ba
4,060
package com.wxdgut.chap4; import java.util.Stack; /** * @author Administrator * @program: leetcodeStudy * @date 2021-11-21 17:22:40 * <p> * 42. 接雨水 难度:困难 * 链接:https://leetcode-cn.com/problems/trapping-rain-water * <p> * 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图, * 计算按此排列的柱子,下雨之后能接多少雨水。 * <p> * 示例: * 输入:height = [0,1,0,2,1,0,1,3,2,1,2,1] 输出:6 * 解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图, * 在这种情况下,可以接 6 个单位的雨水。 * <p> * height = [4,2,0,3,2,5] 输出:9 */ public class TrappingRainWater { // public int trap(int[] height) { // /** // * 方法1:动态规划 1ms // * 时间复杂度:O(n) 空间复杂度:O(n) // * 在暴力方法中,我们仅仅为了找到最大值每次都要向左和向右扫描一次。 // * 但是我们可以提前存储这个值。因此,可以通过动态编程解决。 // * 找到数组中从下标 i=1 开始从左往右每次两两比较得出的最高条形块高度left_max // * 找到数组中从下标 i=size - 1 开始从右往左每次两两比较得出的最高条形块高度right_max // * 每列的容水量 = Math.min(left_max[i], right_max[i]) - height[i] // * // * height [0,1,0,2,1,0,1,3,2,1,2,1] // * left_max [0,1,1,2,2,2,2,3,3,3,3,3] // * right_max [3,3,3,3,3,3,3,3,2,2,2,1] // */ // if (height == null || height.length == 0) return 0; // int ans = 0; // int size = height.length; // int[] left_max = new int[size]; // int[] right_max = new int[size]; // left_max[0] = height[0]; // right_max[size - 1] = height[size - 1]; // for (int i = 1; i < size; i++) { // left_max[i] = Math.max(height[i], left_max[i - 1]); // } // for (int i = size - 2; i >= 0; i--) { // right_max[i] = Math.max(height[i], right_max[i + 1]); // } // for (int i = 1; i < size - 1; i++) { // ans += Math.min(left_max[i], right_max[i]) - height[i]; // } // return ans; // } // public int trap(int[] height) { // /** // * 方法2:单调栈 2ms // * 时间复杂度:O(n) 空间复杂度:O(n) // * 我们可以不用像动态规划那样存储最大高度,而是用栈来跟踪可能储水的最长的条形块。 // * 在遍历数组时维护一个栈,使用栈就可以在一次遍历内完成计算。 // * 如果当前的条形块小于或等于栈顶的条形块,将条形块的索引入栈, // * 即当前的条形块被栈中的前一个条形块界定。 // * 如果发现一个条形块长于栈顶,则可以确定栈顶的条形块被当前条形块和栈的前一个条形块界定, // * 弹出栈顶元素并且累加答案到 ans // */ // if (height == null) return 0; // Stack<Integer> stack = new Stack<>(); // int i = 0, ans = 0; // while (i < height.length) { // if (stack.isEmpty() || height[i] <= height[stack.peek()]) { // stack.push(i++); //维护一个单调栈,存的是元素下标 // } else { // int top = stack.pop(); // if (stack.isEmpty()) continue; // int distance = i - stack.peek() - 1; // int bound_height = Math.min(height[stack.peek()], height[i]) - height[top]; // ans += distance * bound_height; // } // } // return ans; // } // public int trap(int[] height) { // /** // * 方法3:双指针(指针对撞) 0ms // * 时间复杂度:O(n) 空间复杂度:O(n) // * 和方法1 相比,我们不从左和从右分开计算,我们想办法一次完成遍历。 // * 每一次 i 和 j 指针向中间移动的过程,都能确定一个位置的存水量。 // */ // int i = 0; // int j = height.length - 1; // int ans = 0; // int left_max = 0; // int right_max = 0; // while (i <= j) { // left_max = Math.max(left_max, height[i]); // right_max = Math.max(right_max, height[j]); // if (left_max < right_max) { // ans += (left_max - height[i]); // i++; // } else { // ans += (right_max - height[j]); // j--; // } // } // return ans; // } public int trap(int[] height) { //方法4:方法3的精简 int i = 0; int j = height.length - 1; int ans = 0; int left_max = 0; int right_max = 0; while (i <= j) { left_max = Math.max(left_max, height[i]); right_max = Math.max(right_max, height[j]); if (left_max < right_max)ans += (left_max - height[i++]); else ans += (right_max - height[j--]); } return ans; } }
31.71875
93
0.468966
ceeb201001e8ef10256838ba954e0a6219bd5698
2,100
package org.sasm.tree; import org.sasm.MethodVisitor; import java.util.Map; /** * A node that represents a field instruction. A field instruction is an * instruction that loads or stores the value of a field of an object. * * @author Eric Bruneton */ public class FieldInsnNode extends AbstractInsnNode { /** * The internal name of the field's owner class (see * {@link org.sasm.Type#getInternalName() getInternalName}). */ public String owner; /** * The field's name. */ public String name; /** * The field's descriptor (see {@link org.sasm.Type}). */ public String desc; /** * Constructs a new {@link FieldInsnNode}. * * @param opcode * the opcode of the type instruction to be constructed. This * opcode must be GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD. * @param owner * the internal name of the field's owner class (see * {@link org.sasm.Type#getInternalName() * getInternalName}). * @param name * the field's name. * @param desc * the field's descriptor (see {@link org.sasm.Type}). */ public FieldInsnNode(int opcode, String owner, String name, String desc) { super(opcode); this.owner = owner; this.name = name; this.desc = desc; } /** * Sets the opcode of this instruction. * * @param opcode * the new instruction opcode. This opcode must be GETSTATIC, * PUTSTATIC, GETFIELD or PUTFIELD. */ public void setOpcode(int opcode) { this.opcode = opcode; } @Override public int getType() { return FIELD_INSN; } @Override public void accept(MethodVisitor mv) { mv.visitFieldInsn(opcode, owner, name, desc); acceptAnnotations(mv); } @Override public AbstractInsnNode clone(Map<LabelNode, LabelNode> labels) { return new FieldInsnNode(opcode, owner, name, desc).cloneAnnotations(this); } }
26.25
83
0.592381
c560f2287628ea61dd899552b00d51c6829e7c3c
2,143
package com.example.canvasdemo.netrequest; import android.os.Handler; import android.os.Message; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class GetRequest { private volatile static GetRequest instance; private GetRequest(){} public static GetRequest getInstance(){ if(instance == null){ synchronized (GetRequest.class){ if(instance == null){ instance = new GetRequest(); } } } return instance; } public void sendGetNetRequest(String mUrl, Handler handler) { new Thread(() -> { try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); connection.connect(); InputStream in = connection.getInputStream(); String responseData = StreamToString(in); Message message = new Message(); message.obj = responseData; handler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } }).start(); } public String StreamToString(InputStream in) { StringBuilder sb = new StringBuilder(); String oneline; BufferedReader reader = new BufferedReader(new InputStreamReader(in)); try { while ((oneline = reader.readLine()) != null) { sb.append(oneline).append('\n'); } } catch (Exception e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
30.614286
89
0.534298
f0c08cd16651abbb4251d44f49098301372701b4
7,761
package seedu.address.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_ANDY; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BETTY; import static seedu.address.model.Model.PREDICATE_SHOW_ALL_HEALTHWORKERS; import static seedu.address.testutil.TypicalHealthWorkers.ANDY; import static seedu.address.testutil.TypicalHealthWorkers.BETTY; import static seedu.address.testutil.TypicalHealthWorkers.PANIEL; import static seedu.address.testutil.TypicalHealthWorkers.getTypicalHealthWorkerBook; import static seedu.address.testutil.TypicalRequests.ALICE_REQUEST; import static seedu.address.testutil.TypicalRequests.BENSON_REQUEST; import static seedu.address.testutil.TypicalRequests.getTypicalRequestBook; import java.nio.file.Paths; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.commons.core.GuiSettings; import seedu.address.model.person.exceptions.DuplicatePersonException; import seedu.address.model.person.exceptions.PersonNotFoundException; import seedu.address.testutil.Assert; import seedu.address.testutil.HealthWorkerBookBuilder; import seedu.address.testutil.RequestBookBuilder; import seedu.address.testutil.RequestBuilder; public class ModelManagerTest { @Rule public ExpectedException thrown = ExpectedException.none(); private ModelManager modelManager = new ModelManager(); @Test public void constructor() { assertEquals(new UserPrefs(), modelManager.getUserPrefs()); assertEquals(new GuiSettings(), modelManager.getGuiSettings()); } @Test public void setUserPrefs_nullUserPrefs_throwsNullPointerException() { thrown.expect(NullPointerException.class); modelManager.setUserPrefs(null); } @Test public void setUserPrefs_validUserPrefs_copiesUserPrefs() { UserPrefs userPrefs = new UserPrefs(); userPrefs.setAddressBookFilePath(Paths.get("address/book/file/path")); userPrefs.setGuiSettings(new GuiSettings(1, 2, 3, 4)); modelManager.setUserPrefs(userPrefs); assertEquals(userPrefs, modelManager.getUserPrefs()); // Modifying userPrefs should not modify modelManager's userPrefs UserPrefs oldUserPrefs = new UserPrefs(userPrefs); userPrefs.setAddressBookFilePath(Paths.get("new/address/book/file/path")); assertEquals(oldUserPrefs, modelManager.getUserPrefs()); } @Test public void setGuiSettings_nullGuiSettings_throwsNullPointerException() { thrown.expect(NullPointerException.class); modelManager.setGuiSettings(null); } @Test public void setGuiSettings_validGuiSettings_setsGuiSettings() { GuiSettings guiSettings = new GuiSettings(1, 2, 3, 4); modelManager.setGuiSettings(guiSettings); assertEquals(guiSettings, modelManager.getGuiSettings()); } // Added tests for added supporting operations on UniqueHealthWorkerList // @author: Lookaz @Test public void addHealthWorker() { // add null health worker Assert.assertThrows(NullPointerException.class, () -> modelManager .addHealthWorker(null)); // health worker already in addressbook modelManager.addHealthWorker(ANDY); Assert.assertThrows(DuplicatePersonException.class, () -> modelManager.addHealthWorker(ANDY)); } @Test public void hasHealthWorker() { // null health worker Assert.assertThrows(NullPointerException.class, () -> modelManager .hasHealthWorker(null)); // health worker does not exist -> return false assertFalse(modelManager.hasHealthWorker(ANDY)); // health worker exists -> return true modelManager.addHealthWorker(ANDY); assertTrue(modelManager.hasHealthWorker(ANDY)); } @Test public void deleteHealthWorker() { // null health worker Assert.assertThrows(NullPointerException.class, () -> modelManager .deleteHealthWorker(null)); // delete non existent person Assert.assertThrows(PersonNotFoundException.class, () -> modelManager .deleteHealthWorker(ANDY)); } @Test public void setHealthWorker() { // setting null health worker modelManager.addHealthWorker(ANDY); Assert.assertThrows(NullPointerException.class, () -> modelManager .setHealthWorker(ANDY, null)); Assert.assertThrows(NullPointerException.class, () -> modelManager .setHealthWorker(null, ANDY)); // setting non existent health worker Assert.assertThrows(PersonNotFoundException.class, () -> modelManager .setHealthWorker(BETTY, ANDY)); // setting to duplicate health worker modelManager.addHealthWorker(BETTY); Assert.assertThrows(DuplicatePersonException.class, () -> modelManager.setHealthWorker(BETTY, ANDY)); } // ====================================================================== @Test public void equals() { HealthWorkerBook healthWorkerBook = new HealthWorkerBookBuilder().withHealthWorker(ANDY) .withHealthWorker(BETTY).build(); RequestBook requestBook = new RequestBookBuilder().withRequest(ALICE_REQUEST).build(); UserPrefs userPrefs = new UserPrefs(); // same values -> returns true modelManager = new ModelManager(healthWorkerBook, requestBook, userPrefs); ModelManager modelManagerCopy = new ModelManager(healthWorkerBook, requestBook, userPrefs); assertTrue(modelManager.equals(modelManagerCopy)); // same object -> returns true assertTrue(modelManager.equals(modelManager)); // null -> returns false assertFalse(modelManager.equals(null)); // different types -> returns false assertFalse(modelManager.equals(5)); // different addressBook -> returns false assertFalse(modelManager.equals(new ModelManager(new HealthWorkerBook(), requestBook, userPrefs))); // different filteredList -> returns false // modelManager.updateFilteredHealthWorkerList(x -> x.getName().contains("Andy")); // assertFalse(modelManager.equals(new ModelManager(healthWorkerBook, requestBook, userPrefs))); // resets modelManager to initial state for upcoming tests modelManager.updateFilteredHealthWorkerList(PREDICATE_SHOW_ALL_HEALTHWORKERS); // different userPrefs -> returns false UserPrefs differentUserPrefs = new UserPrefs(); differentUserPrefs.setAddressBookFilePath(Paths.get("differentFilePath")); assertFalse(modelManager.equals(new ModelManager(healthWorkerBook, requestBook, differentUserPrefs))); } @Test public void isAssigned() { modelManager = new ModelManager(getTypicalHealthWorkerBook(), getTypicalRequestBook(), new UserPrefs()); // unassigned request assertFalse(modelManager.isAssigned(PANIEL.getName().toString())); // assigned request modelManager.updateRequest(ALICE_REQUEST, new RequestBuilder(ALICE_REQUEST).withHealthWorker(VALID_NAME_ANDY) .withStatus("ONGOING").build()); assertTrue(modelManager.isAssigned(VALID_NAME_ANDY)); // completed request modelManager.updateRequest(BENSON_REQUEST, new RequestBuilder(BENSON_REQUEST).withHealthWorker(VALID_NAME_BETTY) .withStatus("COMPLETED").build()); assertFalse(modelManager.isAssigned(VALID_NAME_BETTY)); } }
40.212435
120
0.711764
c2f2d324dbfe7a43f1e070a93bab999676c9a55e
9,974
package Others; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @Date: 14/03/2010 * @author Bui Quoc Chinh */ public class test { /** * Regconizing keywords (protein, rel word, preps) and determining whether the input sentence is qualify for extracting relation. * input : Sentence with protein name replaced by predefined keyword such * as PROTEINx or sentence with tag for protein name. * output: Simplified sentence with a list of keywords and relation words */ public test() { p = Pattern.compile("PROTEIN\\d{1,2}"); initRelList("PPIs_tool/Rel_Word.txt"); initRel_POS("PPIs_tool/Rel_Pos.txt"); for (String st : preps) { prepHash.put(st, st); } for (String st : to_be) { tobeHash.put(st, st); } } /** * Init component for input sentence. The following components are initilized: * keywords: determine the positions of proteins in the sentence, the number of proteins * relation words: indentify the relation words, theirs position in the sentence, number of * @param txt * @return */ public String initText(String text) { // reset counter values rels.clear(); keycount = 0; relcount = 0; is_a = 0; hasPattern = false; text = preprocess(text); List<String> prs = getProteins(text); keycount = prs.size() ; words = text.split(",\\s|;\\s|:\\s|\\s|\\."); for (int i = 0; i < words.length; i++) { if (relList.containsKey(words[i].toLowerCase())) { relcount++; rels.add(words[i]); // list of rels }else if(tobeHash.containsKey(words[i].toLowerCase())){ is_a++ ; } } return text; } private int getPIndex(String pname){ int i= pname.length()-1 ; while (Character.isDigit(pname.charAt(i))){ i--; } return Integer.parseInt(pname.substring(i+1)); } private List<String> getProteins(String s){ List<String> list = new ArrayList<String>(); m = p.matcher(s); while (m.find()) { list.add(m.group()); // creating a list of proteins from text ; } return list ; } /** * Removing text inside parentheses if not containing Proteins */ public String removeComment(String txt) { StringBuilder sb = new StringBuilder(txt); int i = 0; int[] openP = new int[15]; int index = -1; String sub; // remove () alterHash.clear(); List<String> alter = new ArrayList<String>(); while (i < sb.length()) { if (sb.charAt(i) == '(') { openP[++index] = i; } else { if (sb.charAt(i) == ')') { int k = i + 1; if (index >= 0) { sub = sb.substring(openP[index], k); alter= getProteins(sub); if (alter.size()==0) { sb = sb.replace(openP[index], k, ""); i = openP[index]; }else { // have proteins, now create a list // check whether this list belongs to the protein closed to this list int pidx = getPIndex(alter.get(0)); if(pidx >0){ String pr1 ="PROTEIN"+(pidx-1); int idx1, idx2 ; idx1 = txt.indexOf(pr1); idx2 = txt.indexOf(sub); if(idx2 - idx1 < 15 && idx2 - idx1 >= 0){ alterHash.put(pr1, alter); } } } index--; } } } i++; } // remove [] i = 0; openP = new int[15]; index = -1; while (i < sb.length()) { if (sb.charAt(i) == '[') { openP[++index] = i; } else { if (sb.charAt(i) == ']') { int k = i + 1; if (index >= 0) { sub = sb.substring(openP[index], k); if (!sub.contains("PROTEIN") && sub.length()>=6) { sb = sb.replace(openP[index], k, ""); i = openP[index]; } index--; } } } i++; } return sb.toString().trim(); } public String removeChar(String txt) { txt = txt.replaceAll("\\s{2,}", " "); txt = txt.replaceAll("^(([A-Z])+\\s){0,}([A-Z])+:\\s", ""); return txt; } /** * Check whether this sentence is qualify to extract PPI. * A sentence is qualify if it contains at least 2 protein and one relation word * @return: true */ public boolean isQualify() { return ((keycount >= 2 && relcount >= 1) || (hasPattern && keycount >= 2) || (is_a>0 && keycount>=2)); } // Removing and cleaning text public String preprocess(String txt) { pList.clear(); mc = pt.matcher(txt); String s; while (mc.find()) { s = mc.group(0); sl = s.split("-"); if (sl.length == 2) { if (relList.containsKey(sl[1].toLowerCase()) && sl[0].contains("PROTEIN")) { pList.add(sl); hasPattern = true; } } else { if (sl[0].contains("PROTEIN") || relList.containsKey(sl[0].toLowerCase())) { txt = txt.replace(s, sl[0]); } } } txt = removeComment(txt); txt = removeChar(txt); return txt.trim(); } public static void main(String[] r) { test sen = new test(); String txt ="The sterol-independent regulatory element (SIRE) of the PROTEIN0 (PROTEIN1) promoter mediates PROTEIN2-induced transcription of the PROTEIN3-cuttao gene through a cholesterol-independent pathway"; sen.Test(txt); } public Hashtable<String, List<String>> getAlterHash(){ return alterHash ; } public String getPOS(String txt){ txt = initText(txt); String pos ; for(String s:rels){ pos = relPOS.get(s.toLowerCase()); if(pos!=null){ txt = txt.replace(" "+s+" ", " "+pos+" "); } } return txt ; } public void Test(String txt) { txt = initText(txt); System.out.println("Text "+txt); } public void initRelList(String filename) { BufferedReader in = null; String[] term = null; String txt = ""; try { in = new BufferedReader(new FileReader(filename)); try { while (true) { txt = in.readLine(); if (txt == null) { break; } else { if (!relList.containsKey(txt)) { relList.put(txt, txt); } } } } finally { in.close(); } } catch (Exception e) { System.out.println("Text: " + txt); System.out.println("Length " + term.length); e.printStackTrace(); } } public void initRel_POS(String filename) { BufferedReader in = null; String[] term = null; String txt = ""; try { in = new BufferedReader(new FileReader(filename)); try { while (true) { txt = in.readLine(); if (txt == null) { break; } else { term = txt.split("_"); if (!relPOS.containsKey(term[0])) { relPOS.put(term[0], txt); } } } } finally { in.close(); } } catch (Exception e) { System.out.println("Text: " + txt); System.out.println("Length " + term.length); e.printStackTrace(); } } private String[] words; private List<String> rels = new ArrayList<String>(); public Hashtable<String, String> relList = new Hashtable<String, String>(450); public Hashtable<String, String> relPOS = new Hashtable<String, String>(450); public final String[] preps = {"of", "with", "to", "between", "and", "or", "by", "for", "through"}; public Hashtable<String, String> prepHash = new Hashtable<String, String>(); public Hashtable<String, String> tobeHash = new Hashtable<String, String>(); public int keycount = 0; // number of keywords public int relcount = 0; // number of relations words public int is_a =0; private Pattern p; private Matcher m; private Pattern pt = Pattern.compile("(\\w{2,})?(-\\w{2,})|(PROTEIN\\d{1,2}-)|\\(PROTEIN\\d{1,2}\\)-"); private Matcher mc; private String sl[]; public boolean hasPattern = false; public List<String[]> pList = new ArrayList<String[]>(); // store pattern public Hashtable<String, List<String>> alterHash = new Hashtable<String, List<String>>(); public String to_be[] = {"is", "are"};//,"being","be","was","were"}; }
34.393103
217
0.468017
9e9cc18fded7e5dbe15045a957f158abd1c0cdb7
957
package com.abdoul.groovy.service; import java.lang.System; @kotlin.Metadata(mv = {1, 4, 0}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\u0016\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0010 \n\u0002\u0018\u0002\n\u0002\b\u0002\bf\u0018\u00002\u00020\u0001J\u0017\u0010\u0002\u001a\b\u0012\u0004\u0012\u00020\u00040\u0003H\u00a7@\u00f8\u0001\u0000\u00a2\u0006\u0002\u0010\u0005\u0082\u0002\u0004\n\u0002\b\u0019\u00a8\u0006\u0006"}, d2 = {"Lcom/abdoul/groovy/service/PlaylistAPI;", "", "fetchAllPlaylists", "", "Lcom/abdoul/groovy/model/PlaylistRaw;", "(Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", "app_debug"}) public abstract interface PlaylistAPI { @org.jetbrains.annotations.Nullable() @retrofit2.http.GET(value = "playlists") public abstract java.lang.Object fetchAllPlaylists(@org.jetbrains.annotations.NotNull() kotlin.coroutines.Continuation<? super java.util.List<com.abdoul.groovy.model.PlaylistRaw>> p0); }
79.75
568
0.748171
32c25e9678c8e2900a86d9a88d1ac859879f3c6d
2,631
package io.github.kusaanko; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.InstanceCreator; import com.google.gson.annotations.Expose; import java.io.*; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; public class Profile { public Path profileFile; @Expose public HashMap<String, ArrayList<String>> mcAddToJar; @Expose public ArrayList<String> mcAddToJarTurn; @Expose public String version; @Expose public int profile_version; public Profile(HashMap<String, ArrayList<String>> addToJar, ArrayList<String> turn, Path profileFile, String version) { this.mcAddToJar = addToJar; this.mcAddToJarTurn = turn; this.profileFile = profileFile; this.version = version; this.profile_version = 2; } public void save() { try{ profile_version = 2; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(profileFile), StandardCharsets.UTF_8)); Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .setPrettyPrinting() .create(); bw.write(gson.toJson(this)); bw.close(); }catch (IOException e) { e.printStackTrace(); } } public void add(String path) { this.mcAddToJar.put(path, new ArrayList<>()); this.mcAddToJarTurn.add(path); } public void remove(String path) { this.mcAddToJar.remove(path); this.mcAddToJarTurn.remove(path); } public String getVersionName() { return this.profileFile.getFileName().toString().substring(0, this.profileFile.getFileName().toString().lastIndexOf(".")); } private static String ver; public static Profile load(Path profileFile) { if(Files.exists(profileFile)) { try { BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(profileFile), StandardCharsets.UTF_8)); Gson gson = new GsonBuilder() .registerTypeAdapter(Path.class, new PathInstanceCreator()) .create(); Profile profile = gson.fromJson(br, Profile.class); profile.profileFile = profileFile; br.close(); return profile; } catch (IOException e) { e.printStackTrace(); } } return null; } }
32.085366
137
0.618396
cfc29d1657ac2ef797041843ecd13db53d35bf22
2,953
/* * $Id$ * * $Log$ * Revision 1.1 2008/04/04 18:21:10 cvs * Added legacy code to repository * * Revision 1.2 2004/08/30 14:50:32 mjmaloney * Javadocs * * Revision 1.1 2003/12/20 00:32:51 mjmaloney * Implemented TimeoutInputStream. * */ package ilex.util; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.IOException; /** This class extends BufferedInputStream by adding a timeout capability. The read methods will block up to the specified amount of time waiting for the requested number of bytes. */ public class TimeoutInputStream extends BufferedInputStream { /** Timeout limit set by constructor or setTimeoutMsec(). Default=5000. */ protected long timeoutmsec; /** Sleeps this amount of time in a loop waiting for data. Default = 50. */ protected long sleepPeriod; private boolean isClosed; /** * Constructs stream with default timeout period == 5000L (5 sec). * @param in underlying input stream * @param bufsize buffer size */ public TimeoutInputStream( InputStream in, int bufsize ) { this(in, bufsize, 5000L); } /** * @param in underlying input stream * @param bufsize buffer size * @param timeoutmsec the timeout in msec */ public TimeoutInputStream( InputStream in, int bufsize, long timeoutmsec ) { super(in, bufsize); this.timeoutmsec = timeoutmsec; this.sleepPeriod = 50; isClosed = false; } /** * @return timeout in msec */ public long getTimeoutMsec( ) { return timeoutmsec; } /** * Sets the timeout. * @param ms the timeout in msec */ public void setTimeoutMsec( long ms ) { timeoutmsec = ms; } /** * @return the sleep period in msec */ public long getSleepPeriod( ) { return sleepPeriod; } /** * Sets the sleep period (time to wait between IO attempts). * @param sp the period in msec. */ public void setSleepPeriod( long sp ) { sleepPeriod = sp; } /** * Follows general contract for read method but adds timeout functionality. */ public int read( ) throws IOException { byte b[] = new byte[0]; int r = read(b, 0, 1); return (int)b[0]; } /** * Follows general contract for read method, but if requested number of * bytes is not available within specified timeout period, * throws IOException. */ public int read( byte[] b, int off, int len ) throws IOException { long start = System.currentTimeMillis(); while(available() < len && System.currentTimeMillis() - start < timeoutmsec && !isClosed) { try { Thread.sleep(sleepPeriod); } catch(InterruptedException ex) {} } if (isClosed) throw new IOException("Read failed because stream closed."); int avail = available(); if (avail >= len) return super.read(b, off, len); else throw new IOException("Read operation timed out waiting for " + len + " bytes, avail=" + avail + "."); } /** * Follows general contract for close() */ public void close( ) throws IOException { isClosed = true; super.close(); } }
23.436508
76
0.688791
2ccd034d91bf63062e8fa26d341d025ea19bc84c
49,889
package com.centurylink.mdw.service.data.user; import com.centurylink.mdw.cache.CachingException; import com.centurylink.mdw.constant.OwnerType; import com.centurylink.mdw.dataaccess.DataAccessException; import com.centurylink.mdw.dataaccess.db.CommonDataAccess; import com.centurylink.mdw.model.event.EventLog; import com.centurylink.mdw.model.user.Role; import com.centurylink.mdw.model.user.User; import com.centurylink.mdw.model.user.UserAction; import com.centurylink.mdw.model.user.Workgroup; import org.apache.commons.lang.StringUtils; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; public class UserDataAccess extends CommonDataAccess { protected String USER_SELECT_FIELDS = "u.USER_INFO_ID, u.CUID, u.NAME, u.END_DATE, u.COMMENTS"; public List<User> queryUsers(String whereCondition, boolean withGroups, int startIndex, int endIndex, String sortOn) throws DataAccessException { try { db.openConnection(); List<User> users = new ArrayList<User>(); if (startIndex >= 0) { if (sortOn == null) sortOn = "CUID"; String[] fields = { "USER_INFO_ID", "CUID", "NAME", "END_DATE", "COMMENTS" }; List<String[]> result = super.queryRows("USER_INFO", fields, whereCondition, sortOn, startIndex, endIndex); for (String[] one : result) { String name = one[2] != null ? one[2] : one[4]; User user = new User(); user.setId(new Long(one[0])); user.setCuid(one[1]); user.setName(name); user.setEndDate(one[3]); users.add(user); } } else { String sql = "select " + USER_SELECT_FIELDS + " from USER_INFO u"; if (whereCondition != null) sql = sql + " where " + whereCondition; sql += sortOn == null ? " order by CUID" : (" order by " + sortOn); ResultSet rs = db.runSelect(sql); while (rs.next()) { users.add(createUserInfoFromResultSet(rs)); } } if (withGroups) { for (User user : users) { loadGroupsRolesForUser(user); } } return users; } catch (SQLException ex) { throw new DataAccessException(-1, "Failed to load users", ex); } catch (CachingException e) { throw new DataAccessException(-1, "Failed to load site admin group", e); } finally { db.closeConnection(); } } protected Long getNextId(String sequenceName) throws SQLException { String query = "select " + sequenceName + ".NEXTVAL from DUAL"; ResultSet rs = db.runSelect(query); rs.next(); return new Long(rs.getString(1)); } public Long saveUser(User user) throws DataAccessException { try { db.openConnection(); Long id = user.getId(); // check if the user is in deleted user-info list String sql = "select USER_INFO_ID from USER_INFO u where u.CUID=? AND END_DATE is not NULL"; ResultSet rs = db.runSelect(sql, user.getCuid()); if (rs.next()) { id = rs.getLong(1); } if (id == null || id.longValue() <= 0L) { id = db.isMySQL() ? null : getNextId("MDW_COMMON_ID_SEQ"); String query = "insert into USER_INFO" + " (USER_INFO_ID, CUID, CREATE_DT, CREATE_USR, NAME)" + " values (?, ?, " + now() + ", ?, ?)"; Object[] args = new Object[4]; args[0] = id; args[1] = user.getCuid(); args[2] = "MDW Engine"; args[3] = user.getName(); if (db.isMySQL()) id = db.runInsertReturnId(query, args); else db.runUpdate(query, args); } else { String query = "update USER_INFO set CUID=?, NAME=?,END_DATE=? where USER_INFO_ID=?"; Object[] args = new Object[4]; args[0] = user.getCuid(); args[1] = user.getName(); args[2] = null; args[3] = id; db.runUpdate(query, args); } db.commit(); return id; } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to save user", ex); } finally { db.closeConnection(); } } public User getUser(Long userId) throws DataAccessException { try { db.openConnection(); String sql = "select " + USER_SELECT_FIELDS + " from USER_INFO u where u.USER_INFO_ID=?"; ResultSet rs = db.runSelect(sql, userId); if (rs.next()) { User user = createUserInfoFromResultSet(rs); loadGroupsRolesForUser(user); loadAttributesForUser(user); return user; } else return null; } catch (Exception ex) { throw new DataAccessException(-1, "Failed to get user", ex); } finally { db.closeConnection(); } } public User getUser(String userName) throws DataAccessException { try { User user = null; db.openConnection(); String sql = "select " + USER_SELECT_FIELDS + " from USER_INFO u where lower(u.CUID)=?"; sql += " and END_DATE is null"; ResultSet rs = db.runSelect(sql, userName.toLowerCase()); if (rs.next()) { user = createUserInfoFromResultSet(rs); } if (user != null) { loadGroupsRolesForUser(user); loadAttributesForUser(user); } return user; } catch(Exception ex){ throw new DataAccessException(-1, "Failed to get user: " + userName, ex); } finally { db.closeConnection(); } } private void loadUsersRolesForGroup(String groupName, List<User> users) throws SQLException { if (groupName.equals(Workgroup.COMMON_GROUP)) { // load global roles for the common group // we translate the old names to new ones String sql = "select u.CUID, r.USER_ROLE_NAME " + "from USER_INFO u, USER_ROLE r, USER_GROUP_MAPPING ugm, USER_GROUP g, USER_ROLE_MAPPING urm " + "where g.GROUP_NAME=? " + "and ugm.USER_GROUP_ID=g.USER_GROUP_ID " + "and ugm.USER_INFO_ID=u.USER_INFO_ID " + "and ugm.COMMENTS is null " + "and urm.USER_ROLE_MAPPING_OWNER='" + OwnerType.USER + "' " + "and urm.USER_ROLE_MAPPING_OWNER_ID=u.USER_INFO_ID " + "and urm.USER_ROLE_ID=r.USER_ROLE_ID"; ResultSet rs = db.runSelect(sql, groupName); while (rs.next()) { String cuid = rs.getString(1); String role = rs.getString(2); for (User user : users) { if (cuid.equals(user.getCuid())) { user.addRoleForGroup(groupName, role); break; } } } } else { // load roles for the users in the group String sql = "select u.CUID, r.USER_ROLE_NAME " + "from USER_INFO u, USER_GROUP g, USER_GROUP_MAPPING ugm, USER_ROLE r, USER_ROLE_MAPPING ugrm " + "where g.GROUP_NAME = ?" + " and ugm.USER_GROUP_ID = g.USER_GROUP_ID" + " and ugm.USER_INFO_ID = u.USER_INFO_ID" + " and ugrm.USER_ROLE_MAPPING_OWNER='" + OwnerType.USER_GROUP_MAP + "'" + " and ugrm.USER_ROLE_MAPPING_OWNER_ID = ugm.USER_GROUP_MAPPING_ID" + " and ugrm.USER_ROLE_ID = r.USER_ROLE_ID"; ResultSet rs = db.runSelect(sql, groupName); while (rs.next()) { String cuid = rs.getString(1); String role = rs.getString(2); for (User user : users) { if (cuid.equals(user.getCuid())) { user.addRoleForGroup(groupName, role); break; } } } } } public List<User> getUsersForGroup(String groupName, boolean loadRoles) throws DataAccessException { try { db.openConnection(); List<User> users = new ArrayList<User>(); String sql = "select " + USER_SELECT_FIELDS + " from USER_INFO u, USER_GROUP_MAPPING ugm, USER_GROUP ug " + "where u.END_DATE is null " + " and u.USER_INFO_ID = ugm.USER_INFO_ID" + " and ugm.USER_GROUP_ID = ug.USER_GROUP_ID" + " and ug.GROUP_NAME = ? " + "order by u.CUID"; ResultSet rs = db.runSelect(sql, groupName); while (rs.next()) { users.add(createUserInfoFromResultSet(rs)); } if (loadRoles) this.loadUsersRolesForGroup(groupName, users); return users; } catch (SQLException ex) { throw new DataAccessException(-1, "Failed to load users", ex); } finally { db.closeConnection(); } } public Workgroup getGroup(String groupName) throws DataAccessException { try { Workgroup group = null; db.openConnection(); String sql = "select USER_GROUP_ID, COMMENTS, PARENT_GROUP_ID, END_DATE " + " from USER_GROUP where GROUP_NAME=? and END_DATE is null"; ResultSet rs = db.runSelect(sql, groupName); if (rs.next()) { Long id = rs.getLong(1); String comments = rs.getString(2); group = new Workgroup(id, groupName, comments); long pid = rs.getLong(3); group.setEndDate(rs.getString(4)); if (pid > 0L) { rs = db.runSelect("select GROUP_NAME from USER_GROUP where USER_GROUP_ID=?", pid); if (rs.next()) group.setParentGroup(rs.getString(1)); } } if (group != null) loadAttributesForGroup(group); return group; } catch (Exception ex) { throw new DataAccessException(-1, "Failed to get user group", ex); } finally { db.closeConnection(); } } public Workgroup getGroup(Long groupId) throws DataAccessException { try { Workgroup group = null; db.openConnection(); String sql = "select GROUP_NAME, COMMENTS, PARENT_GROUP_ID, END_DATE " + " from USER_GROUP where USER_GROUP_ID=?"; ResultSet rs = db.runSelect(sql, groupId); if (rs.next()) { String groupName = rs.getString(1); String comments = rs.getString(2); group = new Workgroup(groupId, groupName, comments); long pid = rs.getLong(3); if (pid > 0L) { rs = db.runSelect(sql, pid); if (rs.next()) group.setParentGroup(rs.getString(1)); } group.setEndDate(rs.getString(4)); } if (group != null) loadAttributesForGroup(group); return group; } catch (Exception ex) { throw new DataAccessException(-1, "Failed to get user group", ex); } finally { db.closeConnection(); } } public List<Role> getAllRoles() throws DataAccessException { try { db.openConnection(); List<Role> roles = new ArrayList<Role>(); String sql = "select USER_ROLE_ID, USER_ROLE_NAME, COMMENTS from USER_ROLE order by USER_ROLE_NAME"; ResultSet rs = db.runSelect(sql); while (rs.next()) { Role role = new Role(); role.setId(rs.getLong(1)); role.setName(rs.getString(2)); role.setDescription(rs.getString(3)); roles.add(role); } return roles; } catch (Exception ex) { throw new DataAccessException(-1, "Failed to get all user roles", ex); } finally { db.closeConnection(); } } public Role getRole(String roleName) throws DataAccessException { try { db.openConnection(); String sql = "select USER_ROLE_ID, COMMENTS " + " from USER_ROLE where USER_ROLE_NAME=?"; ResultSet rs = db.runSelect(sql, roleName); if (rs.next()) { Role role = new Role(); role.setId(rs.getLong(1)); role.setName(roleName); role.setDescription(rs.getString(2)); return role; } else return null; } catch (Exception ex) { throw new DataAccessException(-1, "Failed to get user role: " + roleName, ex); } finally { db.closeConnection(); } } public Role getRole(Long roleId) throws DataAccessException { try { db.openConnection(); String sql = "select USER_ROLE_NAME, COMMENTS " + " from USER_ROLE where USER_ROLE_ID=?"; ResultSet rs = db.runSelect(sql, roleId); if (rs.next()) { Role role = new Role(); role.setId(roleId); role.setName(rs.getString(1)); role.setDescription(rs.getString(2)); return role; } else return null; } catch (Exception ex) { throw new DataAccessException(-1, "Failed to get user role", ex); } finally { db.closeConnection(); } } public List<String> getRolesForGroup(Long groupId) throws DataAccessException { try { List<String> roles = new ArrayList<String>(); db.openConnection(); String sql = "select ur.USER_ROLE_ID, ur.USER_ROLE_NAME, ur.COMMENTS " + "from USER_GROUP ug, USER_ROLE ur, USER_ROLE_MAPPING urm " + "where ug.USER_GROUP_ID = ? " + " and urm.USER_ROLE_MAPPING_OWNER = 'USER_GROUP'" + " and urm.USER_ROLE_MAPPING_OWNER_ID = ug.USER_GROUP_ID" + " and urm.USER_ROLE_ID = ur.USER_ROLE_ID "; ResultSet rs = db.runSelect(sql, groupId); while (rs.next()) { roles.add(rs.getString(2)); } return roles; } catch (Exception ex) { throw new DataAccessException(-1, "Failed to get user role", ex); } finally { db.closeConnection(); } } public List<Role> getRolesForAction(Long taskActionId) throws DataAccessException { try { List<Role> roles = new ArrayList<Role>(); db.openConnection(); String sql = "select ur.USER_ROLE_ID, ur.USER_ROLE_NAME, ur.COMMENTS " + "from USER_ROLE ur, TASK_ACTN_USR_ROLE_MAPP taurm " + "where taurm.TASK_ACTION_ID = ?" + " and ur.USER_ROLE_ID = taurm.USER_ROLE_ID " + "order by ur.USER_ROLE_NAME"; ResultSet rs = db.runSelect(sql, taskActionId); while (rs.next()) { Role role = new Role(); role.setId(rs.getLong(1)); role.setName(rs.getString(2)); role.setDescription(rs.getString(3)); roles.add(role); } return roles; } catch (Exception ex) { throw new DataAccessException(-1, "Failed to get roles for task action", ex); } finally { db.closeConnection(); } } public List<User> getUsersForRole(String roleName) throws DataAccessException { try { db.openConnection(); List<User> users = new ArrayList<User>(); String sql = "select " + USER_SELECT_FIELDS + " from USER_INFO u, USER_ROLE_MAPPING urm, USER_ROLE ur " + " where u.END_DATE is null and " + " u.USER_INFO_ID = urm.USER_ROLE_MAPPING_OWNER_ID" + " and urm.USER_ROLE_MAPPING_OWNER='USER'" + " and urm.USER_ROLE_ID = ur.USER_ROLE_ID" + " and ur.USER_ROLE_NAME = ? " + "order by u.CUID"; ResultSet rs = db.runSelect(sql, roleName); while (rs.next()) { users.add(createUserInfoFromResultSet(rs)); } return users; } catch (SQLException ex) { throw new DataAccessException(-1, "Failed to load users for role", ex); } finally { db.closeConnection(); } } public Long saveGroup(Workgroup group) throws DataAccessException { try { db.openConnection(); Long id = group.getId(); Long parentId; if (group.getParentGroup() != null) { ResultSet rs = db.runSelect( "select USER_GROUP_ID from USER_GROUP where GROUP_NAME=?", group.getParentGroup()); if (rs.next()) parentId = rs.getLong(1); else parentId = null; } else parentId = null; // check if the group was in the deleted group list ResultSet rs = db.runSelect( "select USER_GROUP_ID,GROUP_NAME from USER_GROUP where END_DATE IS NOT NULL AND GROUP_NAME=?", group.getName()); if (rs.next()) { id = rs.getLong(1); } if (id == null || id.longValue() <= 0L) { id = db.isMySQL() ? null : getNextId("MDW_COMMON_ID_SEQ"); String query = "insert into USER_GROUP" + " (USER_GROUP_ID, GROUP_NAME, CREATE_DT, CREATE_USR, COMMENTS, PARENT_GROUP_ID)" + " values (?, ?, " + now() + ", ?, ?, ?)"; Object[] args = new Object[5]; args[0] = id; args[1] = group.getName(); args[2] = "MDW Engine"; args[3] = group.getDescription(); args[4] = parentId; if (db.isMySQL()) id = db.runInsertReturnId(query, args); else db.runUpdate(query, args); } else { String query = "update USER_GROUP set GROUP_NAME=?, COMMENTS=?, PARENT_GROUP_ID=?,END_DATE=? where USER_GROUP_ID=?"; Object[] args = new Object[5]; args[0] = group.getName(); args[1] = group.getDescription(); args[2] = parentId; args[3] = null; args[4] = id; db.runUpdate(query, args); } db.commit(); return id; } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to save group", ex); } finally { db.closeConnection(); } } public void deleteUser(Long userId) throws DataAccessException { try { db.openConnection(); // delete user-group mapping String query = "delete from USER_GROUP_MAPPING where USER_INFO_ID=?"; db.runUpdate(query, userId); // delete user-role mapping query = "delete from USER_ROLE_MAPPING where USER_ROLE_MAPPING_OWNER='USER'" + " and USER_ROLE_MAPPING_OWNER_ID=?"; db.runUpdate(query, userId); // delete user attributes query = "delete from ATTRIBUTE where ATTRIBUTE_OWNER='USER' and ATTRIBUTE_OWNER_ID=?"; db.runUpdate(query, userId); // end-date user itself query = "update USER_INFO set END_DATE=" + now() + " where USER_INFO_ID=?"; db.runUpdate(query, userId); db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to delete user", ex); } finally { db.closeConnection(); } } public void deleteGroup(Long groupId) throws DataAccessException { try { db.openConnection(); String query = ""; // delete user-group to role mapping query = "delete from USER_ROLE_MAPPING where USER_ROLE_MAPPING_OWNER='" + OwnerType.USER_GROUP_MAP + "'" + " and USER_ROLE_MAPPING_OWNER_ID in (select USER_GROUP_MAPPING_ID " + " from USER_GROUP_MAPPING where USER_GROUP_ID=?)"; db.runUpdate(query, groupId); // delete user-group mapping query = "delete from USER_GROUP_MAPPING where USER_GROUP_ID=?"; db.runUpdate(query, groupId); // delete group-role mapping (backward compatibility code) query = "delete from USER_ROLE_MAPPING where USER_ROLE_MAPPING_OWNER='USER_GROUP'" + " and USER_ROLE_MAPPING_OWNER_ID=?"; db.runUpdate(query, groupId); // delete group attributes query = "delete from ATTRIBUTE where ATTRIBUTE_OWNER='" + OwnerType.USER_GROUP + "' and ATTRIBUTE_OWNER_ID=?"; db.runUpdate(query, groupId); // end-date the group itself query = "update USER_GROUP set END_DATE=" + now() + " where USER_GROUP_ID=?"; db.runUpdate(query, groupId); db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to delete group", ex); } finally { db.closeConnection(); } } public void deleteRole(Long roleId) throws DataAccessException { try { db.openConnection(); // delete user-role and group-role mapping String query = "delete from USER_ROLE_MAPPING where USER_ROLE_ID=?"; db.runUpdate(query, roleId); // delete the role itself query = "delete from USER_ROLE where USER_ROLE_ID=?"; db.runUpdate(query, roleId); db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to delete role", ex); } finally { db.closeConnection(); } } public Long saveRole(Role role) throws DataAccessException { try { db.openConnection(); Long id = role.getId(); if (id == null || id.longValue() <= 0L) { id = db.isMySQL() ? null : getNextId("MDW_COMMON_ID_SEQ"); String query = "insert into USER_ROLE" + " (USER_ROLE_ID, USER_ROLE_NAME, CREATE_DT, CREATE_USR, COMMENTS)" + " values (?, ?, " + now() + ", ?, ?)"; Object[] args = new Object[4]; args[0] = id; args[1] = role.getName(); args[2] = "MDW Engine"; args[3] = role.getDescription(); if (db.isMySQL()) id = db.runInsertReturnId(query, args); else db.runUpdate(query, args); } else { String query = "update USER_ROLE set USER_ROLE_NAME=?, COMMENTS=? where USER_ROLE_ID=?"; Object[] args = new Object[3]; args[0] = role.getName(); args[1] = role.getDescription(); args[2] = id; db.runUpdate(query, args); } db.commit(); return id; } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to save role", ex); } finally { db.closeConnection(); } } private void updateMembersByName(Long id, String[] members, String selectQuery, String deleteQuery, String findQuery, String insertQuery, String errmsg) throws DataAccessException { try { db.openConnection(); ResultSet rs = db.runSelect(selectQuery, id); List<String> existing = new ArrayList<String>(); HashMap<String, Long> existingIds = new HashMap<String, Long>(); while (rs.next()) { Long mid = rs.getLong(1); String mname = rs.getString(2); existing.add(mname); existingIds.put(mname, mid); } Object[] args = new Object[2]; args[0] = id; for (String e : existing) { boolean found = false; for (String m : members) { if (m.equals(e)) { found = true; break; } } if (!found) { args[1] = existingIds.get(e); db.runUpdate(deleteQuery, args); } } for (String m : members) { boolean found = false; for (String e : existing) { if (m.equals(e)) { found = true; break; } } if (!found) { rs = db.runSelect(findQuery, m); if (rs.next()) { args[1] = rs.getLong(1); db.runUpdate(insertQuery, args); } else { throw new Exception("Cannot find " + m); } } } db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, errmsg, ex); } finally { db.closeConnection(); } } public void updateRolesForUser(Long userId, Long groupId, String[] roles) throws DataAccessException { if (groupId.equals(Workgroup.COMMON_GROUP_ID)) { String selectQuery = "select ur.USER_ROLE_ID, ur.USER_ROLE_NAME " + "from USER_INFO u, USER_ROLE ur, USER_ROLE_MAPPING urm " + "where u.USER_INFO_ID = ? " + " and urm.USER_ROLE_MAPPING_OWNER = 'USER'" + " and urm.USER_ROLE_MAPPING_OWNER_ID = u.USER_INFO_ID" + " and urm.USER_ROLE_ID = ur.USER_ROLE_ID"; String deleteQuery = "delete from USER_ROLE_MAPPING where USER_ROLE_MAPPING_OWNER='USER'" + " and USER_ROLE_MAPPING_OWNER_ID=? and USER_ROLE_ID=?"; String findQuery = "select USER_ROLE_ID from USER_ROLE where USER_ROLE_NAME=?"; String insertQuery = "insert into USER_ROLE_MAPPING" + " (USER_ROLE_MAPPING_ID, USER_ROLE_MAPPING_OWNER, USER_ROLE_MAPPING_OWNER_ID," + " CREATE_DT,CREATE_USR,USER_ROLE_ID) values (" + (db.isMySQL() ? "null" : "MDW_COMMON_ID_SEQ.NEXTVAL") + ",'USER',?," + now() + ",'MDW',?)"; String errmsg = "Failed to update roles for user"; updateMembersByName(userId, roles, selectQuery, deleteQuery, findQuery, insertQuery, errmsg); } else { Long ugmId; try { db.openConnection(); String sql = "select USER_GROUP_MAPPING_ID " + "from USER_GROUP_MAPPING where USER_INFO_ID = ? and USER_GROUP_ID=?"; Object[] args = new Object[2]; args[0] = userId; args[1] = groupId; ResultSet rs = db.runSelect(sql, args); if (rs.next()) { ugmId = rs.getLong(1); sql = "update USER_GROUP_MAPPING set COMMENTS='Converted' where USER_GROUP_MAPPING_ID=?"; db.runUpdate(sql, ugmId); } else throw new Exception("User-group mapping does not exist"); } catch (Exception ex) { throw new DataAccessException(-1, "Failed to find user-group mapping", ex); } finally { db.closeConnection(); } String selectQuery = "select r.USER_ROLE_ID, r.USER_ROLE_NAME " + "from USER_ROLE r, USER_GROUP_MAPPING ugm, USER_ROLE_MAPPING urm " + "where ugm.USER_GROUP_MAPPING_ID = ? " + " and urm.USER_ROLE_MAPPING_OWNER = '" + OwnerType.USER_GROUP_MAP + "'" + " and urm.USER_ROLE_MAPPING_OWNER_ID = ugm.USER_GROUP_MAPPING_ID" + " and urm.USER_ROLE_ID = r.USER_ROLE_ID"; String deleteQuery = "delete from USER_ROLE_MAPPING where" + " USER_ROLE_MAPPING_OWNER='" + OwnerType.USER_GROUP_MAP + "'" + " and USER_ROLE_MAPPING_OWNER_ID=? and USER_ROLE_ID=?"; String findQuery = "select USER_ROLE_ID from USER_ROLE where USER_ROLE_NAME=?"; String insertQuery = "insert into USER_ROLE_MAPPING" + " (USER_ROLE_MAPPING_ID, USER_ROLE_MAPPING_OWNER, USER_ROLE_MAPPING_OWNER_ID," + " CREATE_DT,CREATE_USR,USER_ROLE_ID) values (" + (db.isMySQL() ? "null" : "MDW_COMMON_ID_SEQ.NEXTVAL") + ",'" + OwnerType.USER_GROUP_MAP + "',?," + now() + ",'MDW',?)"; String errmsg = "Failed to update roles for user"; updateMembersByName(ugmId, roles, selectQuery, deleteQuery, findQuery, insertQuery, errmsg); } } public void updateGroupsForUser(Long userId, String[] groups) throws DataAccessException { String selectQuery = "select ug.USER_GROUP_ID, ug.GROUP_NAME " + "from USER_INFO u, USER_GROUP ug, USER_GROUP_MAPPING ugm " + "where u.USER_INFO_ID = ? " + " and ugm.USER_INFO_ID = u.USER_INFO_ID" + " and ugm.USER_GROUP_ID = ug.USER_GROUP_ID"; String deleteQuery = "delete from USER_GROUP_MAPPING where USER_INFO_ID=? and USER_GROUP_ID=?"; String findQuery = "select USER_GROUP_ID from USER_GROUP where GROUP_NAME=?"; String insertQuery = "insert into USER_GROUP_MAPPING" + " (USER_GROUP_MAPPING_ID, USER_INFO_ID," + " CREATE_DT,CREATE_USR,USER_GROUP_ID,COMMENTS) values (" + (db.isMySQL() ? "null" : "MDW_COMMON_ID_SEQ.NEXTVAL") + ",?," + now() + ",'MDW',?,'Converted')"; String errmsg = "Failed to update groups for user"; updateMembersByName(userId, groups, selectQuery, deleteQuery, findQuery, insertQuery, errmsg); } public void addUserToGroup(String cuid, String group) throws DataAccessException { String query = "insert into USER_GROUP_MAPPING" + " (USER_GROUP_MAPPING_ID, USER_INFO_ID," + " CREATE_USR, CREATE_DT, USER_GROUP_ID) values (" + (db.isMySQL() ? "null" : "MDW_COMMON_ID_SEQ.NEXTVAL") + ", " + "(select distinct user_info_id from USER_INFO where cuid = ? and END_DATE is NULL), 'MDW', " + now() + ", " + "(select user_group_id from USER_GROUP where group_name = ?))"; try { db.openConnection(); db.runUpdate(query, new Object[]{cuid, group}); db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to add user " + cuid + " to group " + group, ex); } finally { db.closeConnection(); } } public void removeUserFromGroup(String cuid, String group) throws DataAccessException { String query = "delete from USER_GROUP_MAPPING " + " where user_info_id = (select distinct user_info_id from USER_INFO where cuid = '" + cuid + "' and END_DATE is NULL)" + " and user_group_id = (select user_group_id from USER_GROUP where group_name = '" + group + "')"; try { db.openConnection(); db.runUpdate(query); db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to remove user " + cuid + " from group " + group, ex); } finally { db.closeConnection(); } } public void addUserToRole(String cuid, String role) throws DataAccessException { String query = "insert into USER_ROLE_MAPPING " + " (USER_ROLE_MAPPING_ID, USER_ROLE_MAPPING_OWNER, USER_ROLE_MAPPING_OWNER_ID," + " CREATE_DT,CREATE_USR,USER_ROLE_ID) values (" + (db.isMySQL() ? "null" : "MDW_COMMON_ID_SEQ.NEXTVAL") + ",'USER', " + "(select distinct user_info_id from USER_INFO where cuid = ? and END_DATE is NULL)," + now() + ",'MDW'," + "(select user_role_id from USER_ROLE where user_role_name = ?))"; try { db.openConnection(); db.runUpdate(query, new Object[]{cuid, role}); db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to add user " + cuid + " to role " + role, ex); } finally { db.closeConnection(); } } public void removeUserFromRole(String cuid, String role) throws DataAccessException { // delete user-role mapping String query = "delete from USER_ROLE_MAPPING " + " where USER_ROLE_MAPPING_OWNER_ID= (select distinct user_info_id from USER_INFO where cuid = '" + cuid + "' and END_DATE is NULL ) " + " and user_role_id = (select user_role_id from USER_ROLE where user_role_name = '" + role + "')"; try { db.openConnection(); db.runUpdate(query); db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to remove user " + cuid + " from role " + role, ex); } finally { db.closeConnection(); } } public void updateUsersForGroup(Long groupId, Long[] users) throws DataAccessException { String selectQuery = "select u.USER_INFO_ID " + "from USER_INFO u, USER_GROUP ug, USER_GROUP_MAPPING ugm " + "where ug.USER_GROUP_ID = ? " + " and ugm.USER_INFO_ID = u.USER_INFO_ID" + " and ugm.USER_GROUP_ID = ug.USER_GROUP_ID"; String deleteQuery = "delete from USER_GROUP_MAPPING where USER_GROUP_ID=? " + " and USER_INFO_ID=?"; String insertQuery = "insert into USER_GROUP_MAPPING" + " (USER_GROUP_MAPPING_ID, USER_GROUP_ID, USER_INFO_ID," + " CREATE_DT,CREATE_USR,COMMENTS) values (" + (db.isMySQL() ? "null" : "MDW_COMMON_ID_SEQ.NEXTVAL") + ",?,?," + now() + ",'MDW','Converted')"; String errmsg = "Failed to update users for group"; this.updateMembersById(groupId, users, selectQuery, deleteQuery, insertQuery, errmsg); } public void updateUsersForGroup(Long groupId, String[] users) throws DataAccessException { String selectQuery = "select u.USER_INFO_ID, u.CUID " + "from USER_INFO u, USER_GROUP ug, USER_GROUP_MAPPING ugm " + "where ug.USER_GROUP_ID = ? " + " and ugm.USER_INFO_ID = u.USER_INFO_ID" + " and ugm.USER_GROUP_ID = ug.USER_GROUP_ID"; String deleteQuery = "delete from USER_GROUP_MAPPING where USER_GROUP_ID=? and USER_INFO_ID=?"; String findQuery = "select USER_INFO_ID from USER_INFO where CUID=?"; String insertQuery = "insert into USER_GROUP_MAPPING" + " (USER_GROUP_MAPPING_ID, USER_GROUP_ID," + " CREATE_DT,CREATE_USR,USER_INFO_ID,COMMENTS) values (" + (db.isMySQL() ? "null" : "MDW_COMMON_ID_SEQ.NEXTVAL") + ",?," + now() + ",'MDW',?,'Converted')"; String errmsg = "Failed to update groups for user"; updateMembersByName(groupId, users, selectQuery, deleteQuery, findQuery, insertQuery, errmsg); } public void updateUserAttributes(Long userId, Map<String,String> attributes) throws DataAccessException { try { db.openConnection(); String deleteQuery = "delete from ATTRIBUTE where " + " ATTRIBUTE_OWNER='" + OwnerType.USER + "' and ATTRIBUTE_OWNER_ID=?"; db.runUpdate(deleteQuery, userId); if (attributes != null && !attributes.isEmpty()) { addAttributes0(OwnerType.USER, userId, attributes); } db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to update user attributes for userId: " + userId, ex); } finally { db.closeConnection(); } } public void updateGroupAttributes(Long groupId, Map<String, String> attributes) throws DataAccessException { try { db.openConnection(); String deleteQuery = "delete from ATTRIBUTE where " + " ATTRIBUTE_OWNER='" + OwnerType.USER_GROUP + "' and ATTRIBUTE_OWNER_ID=? "; db.runUpdate(deleteQuery, groupId); if (attributes != null && !attributes.isEmpty()) { addAttributes0(OwnerType.USER_GROUP, groupId, attributes); } db.commit(); } catch (Exception ex) { db.rollback(); throw new DataAccessException(-1, "Failed to update user attributes for userId: " + groupId, ex); } finally { db.closeConnection(); } } public List<String> getUserAttributeNames() throws DataAccessException { try { db.openConnection(); List<String> attrs = new ArrayList<String>(); String query = "select distinct attribute_name from ATTRIBUTE " + "where attribute_owner = 'USER' " + "order by lower(attribute_name)"; ResultSet rs = db.runSelect(query); while (rs.next()) attrs.add(rs.getString("attribute_name")); return attrs; } catch (Exception e) { throw new DataAccessException(0, "failed to get user attribute names", e); } finally { db.closeConnection(); } } public List<String> getGroupAttributeNames() throws DataAccessException { try { db.openConnection(); List<String> attrs = new ArrayList<String>(); String query = "select distinct attribute_name from ATTRIBUTE " + "where attribute_owner = '" + OwnerType.USER_GROUP + "' " + "order by lower(attribute_name)"; ResultSet rs = db.runSelect(query); while (rs.next()) attrs.add(rs.getString("attribute_name")); return attrs; } catch (Exception e) { throw new DataAccessException(0, "failed to get group attribute names", e); } finally { db.closeConnection(); } } protected User createUserInfoFromResultSet(ResultSet rs) throws SQLException { User user = new User(); user.setId(rs.getLong(1)); user.setCuid(rs.getString(2)); String name = rs.getString(3); if (name==null) name = rs.getString(5); // Set Cuid as name to handle migrated users from MDW4 to 5 // and comment is missing in user_info table if (StringUtils.isBlank(name)) name = rs.getString(2); user.setEndDate(rs.getString(4)); user.setName(name); user.parseName(); return user; } protected void loadGroupsRolesForUser(User user) throws SQLException, CachingException { // load groups String sql = "select g.USER_GROUP_ID, g.GROUP_NAME, g.COMMENTS, ug.COMMENTS " + "from USER_GROUP_MAPPING ug, USER_GROUP g " + "where ug.USER_GROUP_ID = g.USER_GROUP_ID and ug.USER_INFO_ID = ? "; sql += "order by lower(g.GROUP_NAME)"; ResultSet rs = db.runSelect(sql, user.getId()); ArrayList<Workgroup> groups = new ArrayList<Workgroup>(); Map<String,Boolean> rolesConverted = new HashMap<String,Boolean>(); while (rs.next()) { Long groupId = rs.getLong(1); String groupName = rs.getString(2); String comment = rs.getString(3); String converted = rs.getString(4); Workgroup group = new Workgroup(groupId, groupName, comment); rolesConverted.put(groupName, "Converted".equalsIgnoreCase(converted)); groups.add(group); } // load roles for the groups other than the shared sql = "select r.USER_ROLE_NAME, ug.USER_GROUP_ID " + "from USER_GROUP_MAPPING ug, USER_ROLE r, USER_ROLE_MAPPING ugr " + "where ug.USER_INFO_ID = ? " + " and ugr.USER_ROLE_MAPPING_OWNER='" + OwnerType.USER_GROUP_MAP + "'" + " and ugr.USER_ROLE_MAPPING_OWNER_ID = ug.USER_GROUP_MAPPING_ID" + " and ugr.USER_ROLE_ID = r.USER_ROLE_ID"; rs = db.runSelect(sql, user.getId()); while (rs.next()) { Long groupId = rs.getLong(2); for (Workgroup group : groups) { if (group.getId().equals(groupId)) { List<String> roles = group.getRoles(); if (roles==null) { roles = new ArrayList<String>(); group.setRoles(roles); } roles.add(rs.getString(1)); break; } } } // load roles for the shared group sql = "select r.USER_ROLE_NAME " + "from USER_INFO u, USER_ROLE r, USER_ROLE_MAPPING ur " + "where u.CUID = ?" + " and ((u.USER_INFO_ID = ur.USER_ROLE_MAPPING_OWNER_ID" + " and ur.USER_ROLE_MAPPING_OWNER = '" + OwnerType.USER + "'" + " and r.USER_ROLE_ID = ur.USER_ROLE_ID)" + " or (ur.USER_ROLE_MAPPING_OWNER = '" + OwnerType.USER_GROUP + "'" + " and ur.USER_ROLE_MAPPING_OWNER_ID in " + " (select ug.USER_GROUP_ID from USER_GROUP_MAPPING ug" + " where ug.USER_INFO_ID = u.USER_INFO_ID" + " and r.USER_ROLE_ID = ur.USER_ROLE_ID))) " + "order by r.USER_ROLE_NAME"; rs = db.runSelect(sql, user.getCuid()); List<String> sharedRoles = new ArrayList<String>(); while (rs.next()) { String roleName = rs.getString(1); if (!sharedRoles.contains(roleName)) sharedRoles.add(roleName); } Workgroup sharedGroup = new Workgroup(Workgroup.COMMON_GROUP_ID, Workgroup.COMMON_GROUP, null); sharedGroup.setRoles(sharedRoles); groups.add(sharedGroup); // set groups to user Collections.sort(groups); user.setGroups(groups); } protected void loadAttributesForUser(User user) throws SQLException, CachingException { // load attributes for user String sql = "select DISTINCT att1.attribute_name, att1.attribute_value from ATTRIBUTE att1 " + " where att1.attribute_owner = '" + OwnerType.USER + "' and att1.attribute_owner_id = ?" + " UNION " + " select DISTINCT att2.attribute_name, '' from ATTRIBUTE att2 " + " where att2.attribute_owner = '" + OwnerType.USER + "' and att2.attribute_owner_id != ? " + " and att2.attribute_name not in (select att3.attribute_name from ATTRIBUTE att3" + " where att3.attribute_owner = '" + OwnerType.USER + "' and att3.attribute_Owner_id = ? )"; ResultSet rs = db.runSelect(sql, new Object[]{user.getId(), user.getId(), user.getId()}); while (rs.next()) { user.setAttribute(rs.getString("attribute_name"), rs.getString("attribute_value")); } } protected void loadAttributesForGroup(Workgroup group) throws SQLException, CachingException { // load attributes for workgroup String sql = "select DISTINCT att1.attribute_name, att1.attribute_value from ATTRIBUTE att1 " + " where att1.attribute_owner = '" + OwnerType.USER_GROUP + "' and att1.attribute_owner_id = ?" + " UNION " + " select DISTINCT att2.attribute_name, '' from ATTRIBUTE att2 " + " where att2.attribute_owner = '" + OwnerType.USER_GROUP + "' and att2.attribute_owner_id != ?" + " and att2.attribute_name not in (select att3.attribute_name from ATTRIBUTE att3" + " where att3.attribute_owner = '" + OwnerType.USER_GROUP + "' and att3.attribute_Owner_id = ? )"; ResultSet rs = db.runSelect(sql, new Object[]{group.getId(), group.getId(), group.getId()}); while (rs.next()) group.setAttribute(rs.getString("attribute_name"), rs.getString("attribute_value")); } public List<Workgroup> getAllGroups(boolean includeDeleted) throws DataAccessException { try { List<Workgroup> groups = new ArrayList<Workgroup>(); db.openConnection(); String sql = "select USER_GROUP_ID, GROUP_NAME, COMMENTS, PARENT_GROUP_ID, END_DATE from USER_GROUP"; if (!includeDeleted) sql = sql + " where END_DATE is null"; sql += " order by GROUP_NAME"; ResultSet rs = db.runSelect(sql); Map<Long,String> nameMap = new HashMap<Long,String>(); while (rs.next()) { Long groupId = rs.getLong(1); String groupName = rs.getString(2); String comments = rs.getString(3); Workgroup group = new Workgroup(groupId, groupName, comments); long pid = rs.getLong(4); if (pid>0L) group.setParentGroup(Long.toString(pid)); group.setEndDate(rs.getString(5)); nameMap.put(groupId, groupName); groups.add(group); } for (Workgroup group : groups) { loadAttributesForGroup(group); if (group.getParentGroup()!=null) { Long pid = new Long(group.getParentGroup()); group.setParentGroup(nameMap.get(pid)); } } return groups; } catch(Exception ex){ throw new DataAccessException(-1, "Failed to get user group", ex); } finally { db.closeConnection(); } } public void auditLogUserAction(UserAction userAction) throws DataAccessException { try { db.openConnection(); Long id = db.isMySQL()?null:this.getNextId("EVENT_LOG_ID_SEQ"); String query = "insert into EVENT_LOG " + "(EVENT_LOG_ID, EVENT_NAME, EVENT_CATEGORY, EVENT_SUB_CATEGORY, " + "EVENT_SOURCE, EVENT_LOG_OWNER, EVENT_LOG_OWNER_ID, CREATE_USR, CREATE_DT, COMMENTS, STATUS_CD) " + "values (?, ?, ?, ?, ?, ?, ?, ?, " + nowPrecision() + ", ?, '1')"; Object[] args = new Object[9]; args[0] = id; args[1] = userAction.getAction().toString(); args[2] = EventLog.CATEGORY_AUDIT; args[3] = "User Action"; args[4] = userAction.getSource(); args[5] = userAction.getEntity().toString(); args[6] = userAction.getEntityId(); args[7] = userAction.getUser(); args[8] = userAction.getDescription(); db.runUpdate(query, args); db.commit(); } catch (SQLException ex) { throw new DataAccessException(-1, "failed to insert audit log", ex); } finally { db.closeConnection(); } } }
42.713185
132
0.52685
2b4102e2f19a910173ef472b7fce763b3e711a60
556
package it.polito.ai.lab3.repo.entities; import java.util.*; import javax.persistence.*; @Entity public class BusLine { @Id private String line; private String description; @ManyToMany @JoinTable(name = "BusLineStop", joinColumns = { @JoinColumn(name = "lineId") }, inverseJoinColumns = {@JoinColumn(name = "stopId") }) private List<BusStop> stops = new ArrayList<BusStop>(); public String getLine() { return line; } public String getDescription() { return description; } public List<BusStop> getStops() { return stops; } }
16.848485
56
0.69964
e08a94d99a60a28e5fc4ce4cad18921f0bc1f42a
1,105
package cn.hust.entity; import com.baomidou.mybatisplus.annotation.*; import java.time.LocalDateTime; import java.io.Serializable; import java.util.Date; import lombok.*; /** * <p> * * </p> * * @author zz * @since 2021-04-12 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor @TableName("tb_operation_log") public class OperationLog { /** * 日志id */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 操作模块 */ private String optModule; /** * 操作路径 */ private String optUrl; /** * 操作类型 */ private String optType; /** * 操作方法 */ private String optMethod; /** * 操作描述 */ private String optDesc; /** * 请求方式 */ private String requestMethod; /** * 请求参数 */ private String requestParam; /** * 返回数据 */ private String responseData; /** * 用户id */ private Integer userId; /** * 用户昵称 */ private String nickname; /** * 用户登录ip */ private String ipAddr; /** * ip来源 */ private String ipSource; /** * 创建时间 */ private Date createTime; }
11.391753
45
0.577376
a1b3cb6b3fdab173fa2503035104ce571724a1b1
8,580
package cn.hikyson.godeye.core.internal.modules.viewcanary; import android.app.Activity; import android.content.res.Resources; import android.graphics.Rect; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import cn.hikyson.godeye.core.internal.Install; import cn.hikyson.godeye.core.internal.ProduceableSubject; import cn.hikyson.godeye.core.utils.ActivityStackUtil; import cn.hikyson.godeye.core.utils.L; import io.reactivex.subjects.ReplaySubject; import io.reactivex.subjects.Subject; public class ViewCanary extends ProduceableSubject<ViewIssueInfo> implements Install<ViewCanaryContext> { private ViewCanaryContext config; private boolean mInstalled = false; @Override public synchronized void install(ViewCanaryContext config) { if (mInstalled) { L.d("ViewCanary already installed, ignore."); return; } this.config = config; mInstalled = true; L.d("ViewCanary installed."); } @Override public synchronized void uninstall() { if (!mInstalled) { L.d("ViewCanary already uninstalled, ignore."); return; } mInstalled = false; L.d("ViewCanary uninstalled."); } @Override public boolean isInstalled() { return mInstalled; } @Override public ViewCanaryContext config() { return config; } @Override protected Subject<ViewIssueInfo> createSubject() { return ReplaySubject.create(); } public void inspect() { Activity activity = ActivityStackUtil.getTopActivity(); if (activity == null) { return; } ViewGroup root = (ViewGroup) activity.getWindow().getDecorView(); Map<View, Integer> depthMap = new HashMap<>(); List<View> allViews = new ArrayList<>(); // allViews should include decor view for inspecting overdraw. However, there is no need for depth inspection to include decor view allViews.add(root); recursiveLoopChildren(root, depthMap, allViews); Map<Rect, Set<Object>> overDrawMap = checkOverDraw(allViews); ViewIssueInfo info = new ViewIssueInfo(); int[] resolution = getResolution(); info.activityName = activity.getClass().getName(); info.timestamp = System.currentTimeMillis(); info.maxDepth = config.maxDepth(); info.screenWidth = resolution[0]; info.screenHeight = resolution[1]; for (Map.Entry<View, Integer> entry : depthMap.entrySet()) { if (entry.getKey() instanceof ViewGroup) { continue; } info.views.add(getViewInfo(entry.getKey(), entry.getValue())); } for (Map.Entry<Rect, Set<Object>> entry : overDrawMap.entrySet()) { ViewIssueInfo.OverDrawArea overDrawArea = new ViewIssueInfo.OverDrawArea(); overDrawArea.rect = entry.getKey(); overDrawArea.overDrawTimes = getOverDrawTimes(entry.getValue()) - 1; info.overDrawAreas.add(overDrawArea); } produce(info); } private int getOverDrawTimes(Set<Object> objects) { int overdrawTimes = 0; for (Object object : objects) { if (object instanceof View) { overdrawTimes += ViewBgUtil.getLayer((View) object); } else { overdrawTimes++; } } return overdrawTimes; } private Map<Rect, Set<Object>> checkOverDraw(List<View> allViews) { Map<Rect, Set<Object>> map = new HashMap<>(); for (int i = 0; i < allViews.size(); i++) { View view = allViews.get(i); for (int j = i + 1; j < allViews.size(); j++) { View other = allViews.get(j); int viewLayer = ViewBgUtil.getLayer(view); int otherLayer = ViewBgUtil.getLayer(other); if (view == other || viewLayer == 0 || otherLayer == 0) { continue; } Rect r1 = new Rect(); Rect r2 = new Rect(); getViewRect(view, r1); getViewRect(other, r2); if (!Rect.intersects(r1, r2)) { continue; } Rect overDraw = calculateOverDraw(r1, r2); Set<Object> set; if (map.containsKey(overDraw)) { set = map.get(overDraw); } else { set = new HashSet<>(); } set.add(view); set.add(other); map.put(overDraw, set); } } Map<Rect, Set<Object>> rest = new HashMap<>(); for (Map.Entry<Rect, Set<Object>> entry : map.entrySet()) { Rect rect = entry.getKey(); for (Map.Entry<Rect, Set<Object>> otherEntry : map.entrySet()) { Rect otherRect = otherEntry.getKey(); if (rect == otherRect || !Rect.intersects(rect, otherRect)) { continue; } Rect overDraw = calculateOverDraw(rect, otherRect); if (map.containsKey(overDraw)) { continue; } Set<Object> set; if (rest.containsKey(overDraw)) { set = rest.get(overDraw); } else { set = new HashSet<>(); } set.add(otherRect); rest.put(overDraw, set); } } map.putAll(rest); return map; } private Rect calculateOverDraw(Rect r1, Rect r2) { Rect overDrawArea = new Rect(); overDrawArea.left = Math.max(r1.left, r2.left); overDrawArea.right = Math.min(r1.right, r2.right); overDrawArea.bottom = Math.min(r1.bottom, r2.bottom); overDrawArea.top = Math.max(r1.top, r2.top); return overDrawArea; } private ViewIssueInfo.ViewInfo getViewInfo(View view, int depth) { ViewIssueInfo.ViewInfo viewInfo = new ViewIssueInfo.ViewInfo(); viewInfo.className = view.getClass().getName(); viewInfo.id = getId(view); Rect rect = new Rect(); getViewRect(view, rect); viewInfo.rect = rect; viewInfo.depth = depth; if (view instanceof TextView) { CharSequence charSequence = ((TextView) view).getText(); if (!TextUtils.isEmpty(charSequence)) { viewInfo.text = charSequence.toString(); viewInfo.textSize = ((TextView) view).getTextSize(); } viewInfo.hasBackground = ViewBgUtil.getLayer(view) > 1; } else { viewInfo.hasBackground = ViewBgUtil.getLayer(view) > 0; } viewInfo.isViewGroup = view instanceof ViewGroup; return viewInfo; } private static void getViewRect(View view, Rect rect) { int[] location = new int[2]; view.getLocationOnScreen(location); rect.left = location[0]; rect.top = location[1]; rect.bottom = rect.top + view.getHeight(); rect.right = rect.left + view.getWidth(); } public static String getId(View view) { return String.valueOf(view.getId()); } private void recursiveLoopChildren(ViewGroup parent, Map<View, Integer> map, List<View> allViews) { for (int i = 0; i < parent.getChildCount(); i++) { final View child = parent.getChildAt(i); if (child == null || child.getVisibility() != View.VISIBLE) { continue; } allViews.add(child); Integer integer = map.get((View) child.getParent()); if (integer == null) { // 最外层view map.put(child, 1); } else { // 子view map.put(child, integer + 1); } if (child instanceof ViewGroup) { recursiveLoopChildren((ViewGroup) child, map, allViews); } } } private int[] getResolution() { int[] resolution = new int[2]; resolution[0] = Resources.getSystem().getDisplayMetrics().widthPixels; resolution[1] = Resources.getSystem().getDisplayMetrics().heightPixels; return resolution; } }
35.020408
139
0.566434
77847e9b0ccd382bb11933efb4b7a656a08468bc
1,585
package com.lunagameserve.kineticform.twitter; import com.lunagameserve.kineticform.model.BallPredicate; /** * Created by sixstring982 on 4/2/16. */ public enum TwitterCommand { CENTER(new BallPredicate() { public int delta(int x, int y, int w, int h) { if ((x == w / 2 || x == w / 2 + 1) && (y == h / 2 || y == h / 2 + 1)) { return 1; } else { return 0; } } }), EDGE(new BallPredicate() { public int delta(int x, int y, int w, int h) { if (x == 0 || y == 0 || x == w - 1 || y == h - 1) { return 5; } else { return 0; } } }), SUBTRACT(new BallPredicate() { public int delta(int x, int y, int w, int h) { if (x > w / 2 && y > w / 2) { return 1; } else { return 0; } } }), WEDGE(new BallPredicate() { public int delta(int x, int y, int w, int h) { return x + 1; } }), CORNER(new BallPredicate() { public int delta(int x, int y, int w, int h) { return x + y + 1; } }); BallPredicate predicate; TwitterCommand(BallPredicate predicate) { this.predicate = predicate; } public BallPredicate getPredicate() { return predicate; } public boolean isInvokedBy(String newTweet) { return newTweet.toLowerCase().contains('#' + toString().toLowerCase()); } }
25.15873
79
0.457413
c7735c406eea0cc4b1d8d593d0c6d8cca0e8a4ca
690
package org.dnal.compiler.nrule; import org.dnal.core.DValue; import org.dnal.core.nrule.NRule; import org.dnal.core.nrule.NRuleContext; import org.dnal.core.nrule.virtual.VirtualInt; //struct member pseudo-len len(firstName) public class LenRule extends Custom1Rule<VirtualInt> { public static final String NAME = "len"; public NRule opRule; public LenRule(String name, VirtualInt arg1) { super(name, arg1); } @Override protected boolean onEval(DValue dval, NRuleContext ctx) { boolean b = opRule.eval(dval, ctx); return b; } @Override protected String generateRuleText() { return opRule.getRuleText(); } }
23.793103
61
0.688406
cfde02ce545b5e0db97fe6b41a3ee2a1f2e984b6
266
package com.kyc.snap.store; public interface Store { String storeBlob(byte[] blob); byte[] getBlob(String id); String storeObject(Object object); void updateObject(String id, Object newObject); <T> T getObject(String id, Class<T> clazz); }
17.733333
51
0.684211
a3323937c6ec10665f86c40011e2555b2a8f2183
2,243
/* * <!-- * ~ Copyright 2015-2017 OpenCB * ~ * ~ 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.opencb.biodata.tools.alignment.iterators; import ga4gh.Reads; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMRecordIterator; import org.opencb.biodata.tools.alignment.converters.SAMRecordToProtoReadAlignmentConverter; import org.opencb.biodata.tools.alignment.filters.AlignmentFilters; /** * Created by pfurio on 25/10/16. */ public class SAMRecordToProtoReadAlignmentBamIterator extends BamIterator<Reads.ReadAlignment> { private SAMRecordToProtoReadAlignmentConverter protoReadAlignmentConverter; public SAMRecordToProtoReadAlignmentBamIterator(SAMRecordIterator samRecordIterator) { this(samRecordIterator, null); } public SAMRecordToProtoReadAlignmentBamIterator(SAMRecordIterator samRecordIterator, AlignmentFilters<SAMRecord> filters) { this(samRecordIterator, filters, true); protoReadAlignmentConverter = new SAMRecordToProtoReadAlignmentConverter(); } public SAMRecordToProtoReadAlignmentBamIterator(SAMRecordIterator samRecordIterator, AlignmentFilters<SAMRecord> filters, boolean binQualities) { super(samRecordIterator, filters); protoReadAlignmentConverter = new SAMRecordToProtoReadAlignmentConverter(binQualities); } @Override public boolean hasNext() { return prevNext != null; } @Override public Reads.ReadAlignment next() { Reads.ReadAlignment readAlignment = protoReadAlignmentConverter.to(prevNext); findNextMatch(); return readAlignment; } }
35.603175
127
0.727151
ca98d974582f00d1d7d64f59eaed3f16170ecd8c
1,710
package org.trianacode.shiwaall.collection; // TODO: Auto-generated Javadoc /** * The Class CollectionElement. * * @param <C> the generic type * @author Andrew Harrison * @version 1.0.0 Jul 15, 2010 */ public class CollectionElement<C> { /** The content. */ protected C content; /** * Instantiates a new collection element. * * @param content the content */ public CollectionElement(C content) { this.content = content; } /** * Instantiates a new collection element. */ public CollectionElement() { } /** * Gets the content. * * @return the content */ public C getContent() { return content; } /** * Sets the content. * * @param content the new content */ public void setContent(C content) { this.content = content; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return "Collection Element content:" + content; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CollectionElement)) { return false; } CollectionElement that = (CollectionElement) o; if (content != null ? !content.equals(that.content) : that.content != null) { return false; } return true; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return content != null ? content.hashCode() : 0; } }
19.883721
85
0.551462
836aea67a17cd877c9aece95df13b05923f54952
8,087
package word_search_solver; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; public class WordSearchSolver { static char[][] grid; static int words_found = 0; public static void main(String[] args) throws IOException { int word_count = 0; String puzzle_fname = "puzzle-simpsons.txt"; String words_fname = "words-simpsons.txt"; Path currentPath = Paths.get(System.getProperty("user.dir")); Path puzzleFilePath = Paths.get(currentPath.toString(), "text", puzzle_fname); Path wordsFilePath = Paths.get(currentPath.toString(), "text", words_fname); ArrayList<String> puzzle = FileIO.readTextFileAsList(puzzleFilePath.toString()); ArrayList<String> words_text = FileIO.readTextFileAsList(wordsFilePath.toString()); ArrayList<Word> words = new ArrayList<Word>(); // Store words in Word objects for (String w : words_text) { //Remove spaces for names like SIDESHOW BOB words.add(new Word(w.replaceAll("\\s+", ""))); } grid = new char[puzzle.size()][puzzle.size()]; // char[][] grid = new char[puzzle.size()][puzzle.size()]; word_count = words.size(); String text = ""; // Populate the 2d array for (int y = 0; y < puzzle.size(); y++) { for (int x = 0; x < puzzle.size(); x++) { grid[y][x] = puzzle.get(y).charAt(x); } } // Get columns for (int y = 0; y < puzzle.size(); y++) { for (int x = 0; x < puzzle.size() - 1; x++) { text += grid[x][y]; } words_found += stringContainsWord(text, words_text); for (String word : words_text) { word = word.replaceAll("\\s+", ""); int pos = text.indexOf(word); if (pos == -1) { pos = text.indexOf(reverseString(word)); } if (pos != -1) { // Update Word for (Word w : words) { if (w.get().equals(word)) { w.setFound(true); w.setDirection(Direction.TOP_TO_BOTTOM); w.setStartPos(y, pos); } } // System.out.println(word + " found at " + (y + 1) + "," + (pos + 1)); } } text = ""; } // Get diagonals // Top left to bottom right for (int x_pos = 0; x_pos < puzzle.size() - 1; x_pos++) { for (int y = 0, x = x_pos; y < puzzle.size(); y++) { text += grid[y][x]; if (x < puzzle.size() - 1) { x++; } else { break; } } words_found += stringContainsWord(text, words_text); for (String word : words_text) { word = word.replaceAll("\\s+", ""); int pos = text.indexOf(word); if (pos == -1) { pos = text.indexOf(reverseString(word)); } if (pos != -1) { // Update Word for (Word w : words) { if (w.get().equals(word)) { w.setFound(true); w.setDirection(Direction.DIAGONAL_L_R_DOWN); w.setStartPos(pos, x_pos); } } // System.out.println(word + " found at " + (pos) + "," + (x_pos)); // System.out.println("Diagonal " + Direction.DIAGONAL_L_R_DOWN); } } text = ""; } // Bottom right to top left for (int x_pos = puzzle.size() - 2; x_pos > 0; x_pos--) { for (int y = puzzle.size() - 1, x = x_pos; y >= 0; y--) { text += grid[y][x]; if (x != 0) { x--; } else { break; } } words_found += stringContainsWord(text, words_text); for (String word : words_text) { word = word.replaceAll("\\s+", ""); int pos = text.indexOf(word); if (pos == -1) { pos = text.indexOf(reverseString(word)); } if (pos != -1) { // Update Word for (Word w : words) { if (w.get().equals(word)) { w.setFound(true); w.setDirection(Direction.DIAGONAL_R_L_UP); w.setStartPos(puzzle.size() - pos - 1, x_pos + pos); } } System.out.println(word + " found at " + (puzzle.size() - pos) + "," + (x_pos + pos + 1)); System.out.println("Diagonal " + Direction.DIAGONAL_R_L_UP); } } text = ""; } // Bottom left to top right for (int x_pos = 0; x_pos < puzzle.size() - 1; x_pos++) { for (int y = puzzle.size() - 1, x = x_pos; y > 0; y--) { text += grid[y][x]; if (x < puzzle.size() - 1) { x++; } else { break; } } words_found += stringContainsWord(text, words_text); for (String word : words_text) { word = word.replaceAll("\\s+", ""); int pos = text.indexOf(word); if (pos == -1) { pos = text.indexOf(reverseString(word)); } if (pos != -1) { // Update Word for (Word w : words) { if (w.get().equals(word)) { w.setFound(true); w.setDirection(Direction.DIAGONAL_L_R_UP); w.setStartPos(puzzle.size() - pos - 1, x_pos + pos); } } // System.out.println(word + " found at " + (puzzle.size() - pos) + "," + (x_pos + pos + 1)); // System.out.println("Diagonal " + Direction.DIAGONAL_L_R_UP); } } text = ""; } // Rows for (int y = 0; y < puzzle.size(); y++) { words_found += stringContainsWord(puzzle.get(y), words_text); for (String word : words_text) { word = word.replaceAll("\\s+", ""); int pos = puzzle.get(y).indexOf(word); if (pos == -1) { pos = puzzle.get(y).indexOf(reverseString(word)); } if (pos != -1) { // Update Word for (Word w : words) { if (w.get().equals(word)) { w.setFound(true); w.setDirection(Direction.LEFT_TO_RIGHT); w.setStartPos(pos, y); } } // System.out.println(word + " found at " + (y + 1) + "," + (pos + 1)); } } } System.out.println(words_found + " of " + word_count + " words found"); System.out.println(); displayPuzzle(puzzle.size(), puzzle); System.out.println(); for (Word w : words) { if (w.isFound() ) { int[] pos = w.getStartPos(); // System.out.println(w.get() + " found at " + pos[0] + "," + pos[1]); resetPuzzle(puzzle.size(), puzzle); replaceWord(w, puzzle.size()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } displayPuzzle(puzzle.size(), puzzle); System.out.println(); System.out.println("Found " + w.get()); System.out.println(); } else { System.out.println("Not found " + w.get()); } } } public static void replaceWord(Word w, int size) { if ( w.get().length() == 0) { return; } int[] startPos = w.getStartPos(); int x = startPos[0]; int y = startPos[1]; switch (w.getDirection()) { case TOP_TO_BOTTOM: for (int i = 0; i < w.get().length(); i++) { grid[y + i][x] = ' '; } break; case LEFT_TO_RIGHT: for (int i = 0; i < w.get().length(); i++) { if (x + i > (size - 1)) { break; } grid[y][x + i] = ' '; } break; case DIAGONAL_L_R_UP: for (int i = 0; i < w.get().length(); i++) { grid[x - i][y + i] = ' '; } break; case DIAGONAL_R_L_UP: for (int i = 0; i < w.get().length(); i++) { grid[x - i][y - i] = ' '; } break; case DIAGONAL_L_R_DOWN: for (int i = 0; i < w.get().length(); i++) { grid[x + i][y + i] = ' '; } break; default: break; } } public static void resetPuzzle(int size, ArrayList<String> lines) { // Populate the 2d array for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) { grid[y][x] = lines.get(y).charAt(x); } } } public static void displayPuzzle(int size, ArrayList<String> lines) { // Populate the 2d array for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) { System.out.print(grid[y][x]); } System.out.println(); } } public static int[] stringStartPos(String s, String word) { return new int[] {0, 0 }; } public static int stringContainsWord(String s, ArrayList<String> list) { int foundWords = 0; for (String word : list) { word = word.replaceAll("\\s+", ""); if (s.contains(word) || reverseString(s).contains(word)) { foundWords++; } } return foundWords; } public static String reverseString(String s) { StringBuilder sb = new StringBuilder(s); return sb.reverse().toString(); } }
27.137584
97
0.553481
6b41320c0a4733e2735df6761efc35c339d6bb5f
2,478
package com.github.zuihou.cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.zuihou.cache.lock.CaffeineDistributedLock; import com.github.zuihou.cache.properties.CustomCacheProperties; import com.github.zuihou.cache.repository.CacheRepository; import com.github.zuihou.cache.repository.CaffeineRepositoryImpl; import com.github.zuihou.lock.DistributedLock; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cache.CacheManager; import org.springframework.cache.caffeine.CaffeineCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; /** * 内存缓存配置 * * @author zuihou * @date 2019/08/07 */ @Slf4j @ConditionalOnProperty(name = "zuihou.cache.type", havingValue = "CAFFEINE") @EnableConfigurationProperties({CustomCacheProperties.class}) public class CaffeineAutoConfigure { @Autowired private CustomCacheProperties cacheProperties; /** * 为了解决演示环境启动报错而加的类 * * @return */ @Bean @ConditionalOnMissingBean public DistributedLock RedisDistributedLock() { return new CaffeineDistributedLock(); } /** * caffeine 持久库 * * @return the redis repository */ @Bean @ConditionalOnMissingBean public CacheRepository redisRepository() { return new CaffeineRepositoryImpl(); } @Bean @Primary public CacheManager caffeineCacheManager() { CaffeineCacheManager cacheManager = new CaffeineCacheManager(); Caffeine caffeine = Caffeine.newBuilder() .recordStats() .initialCapacity(500) .expireAfterWrite(cacheProperties.getDef().getTimeToLive()) .maximumSize(cacheProperties.getDef().getMaxSize()); cacheManager.setAllowNullValues(true); cacheManager.setCaffeine(caffeine); //配置了这里,就必须实现在这里指定key 才能缓存 // Map<String, CustomCacheProperties.Redis> configs = cacheProperties.getConfigs(); // Optional.ofNullable(configs).ifPresent((config)->{ // cacheManager.setCacheNames(config.keySet()); // }); return cacheManager; } }
31.769231
90
0.733253
63be1799c56f1fc8d883f368ec72913a0aa05423
764
package com.mikedeejay2.mikedeejay2lib.gui.tree; /** * The way that a branch connects the parent item to the * child item in a <code>GUITreeModule</code> * * @author Mikedeejay2 */ public enum BranchType { /** * When creating a branch, run the branch horizontal first, such as: * <pre> * ⇩ parent item * ■───────────┐ * │ * │ * │ * ■ ⇦ child item * </pre> */ HORIZONTAL_FIRST, /** * When creating a branch, run the branch vertical first, such as: * <pre> * ⇩ parent item * ■ * │ * │ * │ * └───────────■ ⇦ child item * </pre> */ VERTICAL_FIRST }
20.648649
72
0.441099
fe29beafd974c6c29f61b10620500472b26dc806
72
package com.kmboot.jvm.base; public class U1 { public byte[] u1 ; }
14.4
28
0.666667
d2ec1142125e8475c9077b56ca0afae1dac95986
471
package Arithmetic;//import java.text.DecimalFormat; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Scanner; public class 圆的面积 { public static void main(String[] args) { double PI=3.14159265358979323; double s; Scanner ss=new Scanner(System.in); int r=ss.nextInt(); s=r*r*PI; BigDecimal d=new BigDecimal(r*r); BigDecimal x=new BigDecimal(PI); BigDecimal i=d.multiply(x).setScale(7,RoundingMode.HALF_EVEN); System.out.print(i); } }
26.166667
63
0.755839
b316c5a61497275dc782f269971233b5b0217438
38,634
/* * Copyright 2017 Software Engineering and Synthesis Group * * 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.sesygroup.choreography.coordinationlogic.realizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.collections4.IterableUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import com.sesygroup.choreography.choreographyspecification.model.ChoreographySpecification; import com.sesygroup.choreography.choreographyspecification.model.Participant; import com.sesygroup.choreography.choreographyspecification.model.Transition; import com.sesygroup.choreography.choreographyspecification.model.action.SendingMessageActionTransition; import com.sesygroup.choreography.concreteparticipantbehavior.model.ConcreteParticipantBehavior; import com.sesygroup.choreography.concreteparticipantbehavior.model.State; import com.sesygroup.choreography.concreteparticipantbehavior.model.action.AsynchronousReceiveActionTransition; import com.sesygroup.choreography.concreteparticipantbehavior.model.action.AsynchronousSendActionTransition; import com.sesygroup.choreography.concreteparticipantbehavior.model.action.InternalActionTransition; import com.sesygroup.choreography.concreteparticipantbehavior.model.action.SynchronousReceiveActionTransition; import com.sesygroup.choreography.concreteparticipantbehavior.model.action.SynchronousSendActionTransition; import com.sesygroup.choreography.concreteparticipantbehavior.model.message.InputMessage; import com.sesygroup.choreography.concreteparticipantbehavior.model.message.OutputMessage; /** * * @author Alexander Perucci (http://www.alexanderperucci.com/) * */ public class CoordinationLogicRealizer { private static final String BRANCH_STATE_SUFFIX = "_branch"; private static final String MID_STATE_SUFFIX = "_mid"; private static final String SYNCH_STATE_SUFFIX = "_synch"; private static final String SYNCH_MESSAGE_PREFIX = "Synch_"; private static final String SYNCH_MESSAGE_TO = "->"; private ChoreographySpecification choreographySpecification; private Map<Participant, ConcreteParticipantBehavior> participantToConcreteParticipantBehaviorMap; private Map<Pair<Participant, Participant>, ConcreteParticipantBehavior> cdNameToConcreteParticipantBehaviorMap; public CoordinationLogicRealizer(final ChoreographySpecification choreographySpecification, final Map<Participant, ConcreteParticipantBehavior> participantToConcreteParticipantBehaviorMap) { this.choreographySpecification = choreographySpecification; this.participantToConcreteParticipantBehaviorMap = participantToConcreteParticipantBehaviorMap; } public Map<Pair<Participant, Participant>, ConcreteParticipantBehavior> realize() { cdNameToConcreteParticipantBehaviorMap = new HashMap<Pair<Participant, Participant>, ConcreteParticipantBehavior>(); // find all possible CD name Collection<Pair<Participant, Participant>> coordinationDelegateParticipantPairs = CoordinationLogicRealizerUtils.findCoordinationDelegatesToBeCreated(choreographySpecification); // create a ConcreteParticipantBehavior for each CD and copy all ChoreographySpecification in the // ConcreteParticipantBehavior states coordinationDelegateParticipantPairs.forEach(pair -> { ConcreteParticipantBehavior concreteParticipantBehavior = new ConcreteParticipantBehavior(); choreographySpecification.getStates() .forEach(state -> concreteParticipantBehavior.getStates().add(new State(state.getName()))); concreteParticipantBehavior.setInitialState(new State(choreographySpecification.getInitialState().getName())); cdNameToConcreteParticipantBehaviorMap.put(pair, concreteParticipantBehavior); }); // add all necessary state to the CDs createMidState(); createSynchState(); createBranchingState(); // add all necessary transition to the CDs // createSynchTransitionsForBranchingState(); createSynchTransitionsForIndipendentSequence(); createSynchTransitionsThatReachBranchingState(); createSynchTransitionsForBranchingStateToItsState(); createSynchTransitionsForBranchingStateToOtherSate(); createMessageTransitions(); return cdNameToConcreteParticipantBehaviorMap; } private void createMidState() { // create mid state and synch state choreographySpecification.getTransitions().forEach(transition -> { if (transition instanceof SendingMessageActionTransition) { Pair<Participant, Participant> cd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transition).getSourceParticipant(), ((SendingMessageActionTransition) transition).getTargetParticipant()); // get ConcreteParticipantBehavior of the CD ConcreteParticipantBehavior concreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(cd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(concreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, cd); // create mid state in the ConcreteParticipantBehavior concreteParticipantBehavior.getStates() .add(new State(transition.getSourceState().getName() + MID_STATE_SUFFIX)); } }); } private void createSynchState() { // create synch state choreographySpecification.getTransitions().forEach(transition -> { if (transition instanceof SendingMessageActionTransition) { Pair<Participant, Participant> cd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transition).getSourceParticipant(), ((SendingMessageActionTransition) transition).getTargetParticipant()); // get ConcreteParticipantBehavior of the CD ConcreteParticipantBehavior concreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(cd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(concreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, cd); // create synch state in the ConcreteParticipantBehavior if the source participant of the outgoing is not // equal to the source participant of the target transition for (Transition outgoingTransition : CoordinationLogicRealizerUtils .findAllOutgoingTransition(choreographySpecification, transition.getTargetState())) { State synchState = new State(transition.getTargetState().getName() + SYNCH_STATE_SUFFIX); if (outgoingTransition instanceof SendingMessageActionTransition && !((SendingMessageActionTransition) outgoingTransition).getSourceParticipant() .equals(((SendingMessageActionTransition) transition).getSourceParticipant())) { if (!concreteParticipantBehavior.getStates().contains(synchState)) { concreteParticipantBehavior.getStates().add(synchState); } // add the synch state to the target CD Pair<Participant, Participant> outgoingCd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) outgoingTransition).getSourceParticipant(), ((SendingMessageActionTransition) outgoingTransition).getTargetParticipant()); ConcreteParticipantBehavior outgoingConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(outgoingCd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(outgoingConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, outgoingCd); if (!outgoingConcreteParticipantBehavior.getStates().contains(synchState)) { outgoingConcreteParticipantBehavior.getStates().add(synchState); } } } } }); } private void createBranchingState() { // find branching states List<com.sesygroup.choreography.choreographyspecification.model.State> branchingStates = CoordinationLogicRealizerUtils.findBranchingStates(choreographySpecification); // create branch state for each branching state branchingStates.forEach(state -> { List<Transition> outgoingTransitionsOfBranchingState = CoordinationLogicRealizerUtils.findAllOutgoingTransition(choreographySpecification, state); outgoingTransitionsOfBranchingState.forEach(transition -> { if (transition instanceof SendingMessageActionTransition) { Pair<Participant, Participant> cd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transition).getSourceParticipant(), ((SendingMessageActionTransition) transition).getTargetParticipant()); // get ConcreteParticipantBehavior of the CD ConcreteParticipantBehavior concreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(cd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(concreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, cd); // create branch state in the ConcreteParticipantBehavior concreteParticipantBehavior.getStates().add(new State(state.getName() + BRANCH_STATE_SUFFIX)); } }); }); } private void createSynchTransitionsForIndipendentSequence() { choreographySpecification.getTransitions().forEach(transition -> { if (transition instanceof SendingMessageActionTransition) { Pair<Participant, Participant> incomingCd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transition).getSourceParticipant(), ((SendingMessageActionTransition) transition).getTargetParticipant()); // check target is not a branching state we consider later this situation if (!CoordinationLogicRealizerUtils.isBranchingState(choreographySpecification, transition.getTargetState())) { // get ConcreteParticipantBehavior of the CD ConcreteParticipantBehavior incomingConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(incomingCd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(incomingConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, incomingCd); // create synch state in the ConcreteParticipantBehavior if the source participant of the outgoing is not // equal to the source participant of the target transition for (Transition outgoingTransition : CoordinationLogicRealizerUtils .findAllOutgoingTransition(choreographySpecification, transition.getTargetState())) { State synchState = new State(transition.getTargetState().getName() + SYNCH_STATE_SUFFIX); if (outgoingTransition instanceof SendingMessageActionTransition && !((SendingMessageActionTransition) outgoingTransition).getSourceParticipant() .equals(((SendingMessageActionTransition) transition).getSourceParticipant())) { // add the synch state to the target CD Pair<Participant, Participant> outgoingCd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) outgoingTransition).getSourceParticipant(), ((SendingMessageActionTransition) outgoingTransition).getTargetParticipant()); ConcreteParticipantBehavior outgoingConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(outgoingCd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(outgoingConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, outgoingCd); // here we have the synch state and the source and target CDs, if (incomingConcreteParticipantBehavior.getStates().contains(synchState) && outgoingConcreteParticipantBehavior.getStates().contains(synchState)) { // we need to create transition from the state to the synch SynchronousSendActionTransition incomingSynchronousSendActionTransition = new SynchronousSendActionTransition( IterableUtils.find(incomingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(transition.getTargetState().getName()))), IterableUtils.find(incomingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(synchState)), new OutputMessage(SYNCH_MESSAGE_PREFIX + "{" + incomingCd.getLeft().getName() + "," + incomingCd.getRight().getName() + "}" + SYNCH_MESSAGE_TO + "{" + outgoingCd .getLeft().getName() + "," + outgoingCd.getRight().getName() + "}")); incomingConcreteParticipantBehavior.getTransitions() .add(incomingSynchronousSendActionTransition); // we need to create transition from the synch to the state SynchronousReceiveActionTransition outgoingSynchronousReceiveActionTransition = new SynchronousReceiveActionTransition( IterableUtils.find(outgoingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(synchState)), IterableUtils.find(outgoingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(transition.getTargetState().getName()))), new InputMessage(SYNCH_MESSAGE_PREFIX + "{" + incomingCd.getLeft().getName() + "," + incomingCd.getRight().getName() + "}" + SYNCH_MESSAGE_TO + "{" + outgoingCd .getLeft().getName() + "," + outgoingCd.getRight().getName() + "}")); outgoingConcreteParticipantBehavior.getTransitions() .add(outgoingSynchronousReceiveActionTransition); } else { // TODO remove if and use Validate.x in order to throw exception. } } } } } }); } private void createSynchTransitionsThatReachBranchingState() { choreographySpecification.getTransitions().forEach(transition -> { if (transition instanceof SendingMessageActionTransition) { if (CoordinationLogicRealizerUtils.isBranchingState(choreographySpecification, transition.getTargetState())) { Pair<Participant, Participant> incomingCd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transition).getSourceParticipant(), ((SendingMessageActionTransition) transition).getTargetParticipant()); // get ConcreteParticipantBehavior of the CD ConcreteParticipantBehavior incomingConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(incomingCd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(incomingConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, incomingCd); // create synch state in the ConcreteParticipantBehavior if the source participant of the outgoing is not // equal to the source participant of the target transition List<Transition> outgoingTransitions = CoordinationLogicRealizerUtils .findAllOutgoingTransition(choreographySpecification, transition.getTargetState()); // add sending transition to the incoming CD State synchState = new State(transition.getTargetState().getName() + SYNCH_STATE_SUFFIX); State branchState = new State(transition.getTargetState().getName() + BRANCH_STATE_SUFFIX); StringBuilder nameOutputMessage = new StringBuilder(); nameOutputMessage.append(SYNCH_MESSAGE_PREFIX + "{" + incomingCd.getLeft().getName() + "," + incomingCd.getRight().getName() + "}" + SYNCH_MESSAGE_TO); getTargetCDs(outgoingTransitions, transition).forEach(pair -> { nameOutputMessage.append("{" + pair.getLeft().getName() + "," + pair.getRight().getName() + "}"); }); // we need to create transition from the synch to the branch SynchronousSendActionTransition incomingSynchronousSendActionTransition = new SynchronousSendActionTransition( IterableUtils.find(incomingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(synchState)), IterableUtils.find(incomingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(branchState)), new OutputMessage(nameOutputMessage.toString())); incomingConcreteParticipantBehavior.getTransitions().add(incomingSynchronousSendActionTransition); for (Transition outgoingTransition : outgoingTransitions) { Pair<Participant, Participant> outgoingCd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) outgoingTransition).getSourceParticipant(), ((SendingMessageActionTransition) outgoingTransition).getTargetParticipant()); if (!incomingCd.equals(outgoingCd)) { ConcreteParticipantBehavior outgoingConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(outgoingCd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(outgoingConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, outgoingCd); // we need to create transition from the synch to the branch SynchronousReceiveActionTransition outgoingSynchronousReceiveActionTransition = new SynchronousReceiveActionTransition( IterableUtils.find(outgoingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(synchState)), IterableUtils.find(outgoingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(branchState)), new InputMessage(SYNCH_MESSAGE_PREFIX + "{" + incomingCd.getLeft().getName() + "," + incomingCd.getRight().getName() + "}" + SYNCH_MESSAGE_TO + "{" + outgoingCd.getLeft().getName() + "," + outgoingCd.getRight().getName() + "}")); outgoingConcreteParticipantBehavior.getTransitions() .add(outgoingSynchronousReceiveActionTransition); } } } } }); } private void createSynchTransitionsForBranchingStateToItsState() { choreographySpecification.getTransitions().forEach(transition -> { if (transition instanceof SendingMessageActionTransition) { if (CoordinationLogicRealizerUtils.isBranchingState(choreographySpecification, transition.getTargetState())) { Pair<Participant, Participant> incomingCd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transition).getSourceParticipant(), ((SendingMessageActionTransition) transition).getTargetParticipant()); // get ConcreteParticipantBehavior of the CD ConcreteParticipantBehavior incomingConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(incomingCd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(incomingConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, incomingCd); // create synch state in the ConcreteParticipantBehavior if the source participant of the outgoing is not // equal to the source participant of the target transition List<Transition> outgoingTransitions = CoordinationLogicRealizerUtils .findAllOutgoingTransition(choreographySpecification, transition.getTargetState()); // add sending transition to the incoming CD State branchState = new State(transition.getTargetState().getName() + BRANCH_STATE_SUFFIX); for (Transition outgoingTransition : outgoingTransitions) { Pair<Participant, Participant> outgoingCd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) outgoingTransition).getSourceParticipant(), ((SendingMessageActionTransition) outgoingTransition).getTargetParticipant()); ConcreteParticipantBehavior outgoingConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(outgoingCd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(outgoingConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, outgoingCd); // we need to create transition from the branch to its state StringBuilder nameInputMessage = new StringBuilder(); nameInputMessage.append(SYNCH_MESSAGE_PREFIX + "{" + outgoingCd.getLeft().getName() + "," + outgoingCd.getRight().getName() + "}" + SYNCH_MESSAGE_TO); getTargetCDs(outgoingTransitions, outgoingTransition).forEach(pair -> { nameInputMessage.append("{" + pair.getLeft().getName() + "," + pair.getRight().getName() + "}"); }); SynchronousSendActionTransition outgoingSynchronousReceiveActionTransition = new SynchronousSendActionTransition( IterableUtils.find(outgoingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(branchState)), IterableUtils.find(outgoingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(transition.getTargetState().getName()))), new OutputMessage(nameInputMessage.toString())); outgoingConcreteParticipantBehavior.getTransitions().add(outgoingSynchronousReceiveActionTransition); } } } }); } private void createSynchTransitionsForBranchingStateToOtherSate() { choreographySpecification.getTransitions().forEach(transition -> { if (transition instanceof SendingMessageActionTransition) { if (CoordinationLogicRealizerUtils.isBranchingState(choreographySpecification, transition.getTargetState())) { List<Transition> outgoingTransitions = CoordinationLogicRealizerUtils .findAllOutgoingTransition(choreographySpecification, transition.getTargetState()); State branchState = new State(transition.getTargetState().getName() + BRANCH_STATE_SUFFIX); for (Transition outgoingTransition : outgoingTransitions) { Pair<Participant, Participant> outgoingCd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) outgoingTransition).getSourceParticipant(), ((SendingMessageActionTransition) outgoingTransition).getTargetParticipant()); ConcreteParticipantBehavior outgoingConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(outgoingCd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(outgoingConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, outgoingCd); // consider all the transition by excluding the actual transition for (Transition transitionToAdd : ListUtils.removeAll(outgoingTransitions, Arrays.asList(outgoingTransition))) { Pair<Participant, Participant> incomingCd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transitionToAdd).getSourceParticipant(), ((SendingMessageActionTransition) transitionToAdd).getTargetParticipant()); ConcreteParticipantBehavior inputConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(outgoingCd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(inputConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, incomingCd); // add transition from branch state to transitionToAdd.target state SynchronousReceiveActionTransition outgoingSynchronousReceiveActionTransition = new SynchronousReceiveActionTransition( IterableUtils.find(outgoingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>(branchState)), IterableUtils.find(outgoingConcreteParticipantBehavior.getStates(), new EqualPredicate<State>( new State(transitionToAdd.getTargetState().getName()))), new InputMessage(SYNCH_MESSAGE_PREFIX + "{" + incomingCd.getLeft().getName() + "," + incomingCd.getRight().getName() + "}" + SYNCH_MESSAGE_TO + "{" + outgoingCd .getLeft().getName() + "," + outgoingCd.getRight().getName() + "}")); outgoingConcreteParticipantBehavior.getTransitions() .add(outgoingSynchronousReceiveActionTransition); } } } } }); } private void createMessageTransitions() { choreographySpecification.getTransitions().forEach(transition -> { if (transition instanceof SendingMessageActionTransition) { Pair<Participant, Participant> cd = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transition).getSourceParticipant(), ((SendingMessageActionTransition) transition).getTargetParticipant()); ConcreteParticipantBehavior concreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(cd); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(concreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, cd); State midState = new State(transition.getSourceState().getName() + MID_STATE_SUFFIX); State synchState = new State(transition.getTargetState().getName()); if (CoordinationLogicRealizerUtils.isBranchingState(choreographySpecification, transition.getTargetState())) { synchState = new State(transition.getTargetState().getName() + SYNCH_STATE_SUFFIX); } // add synch or asynch send transition from midState state to synch state InputMessage inputMessage = new InputMessage(((SendingMessageActionTransition) transition).getMessage().getName()); com.sesygroup.choreography.concreteparticipantbehavior.model.Transition foundedReceiveActionTransition = CoordinationLogicRealizerUtils.findConcreteTransition( participantToConcreteParticipantBehaviorMap.get(cd.getRight()), new State(transition.getSourceState().getName()), inputMessage); Validate.notNull(foundedReceiveActionTransition, ValidationMessages.IS_NULL_CONCRETE_PARTICIPANT_BEHAVIOR_TRANSITION_EXCEPTION_MESSAGE, inputMessage.getName()); if (foundedReceiveActionTransition instanceof SynchronousReceiveActionTransition) { SynchronousReceiveActionTransition receiveActionTransition = new SynchronousReceiveActionTransition( IterableUtils.find(concreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(transition.getSourceState().getName()))), IterableUtils.find(concreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(midState.getName()))), inputMessage); concreteParticipantBehavior.getTransitions().add(receiveActionTransition); } else if (foundedReceiveActionTransition instanceof AsynchronousReceiveActionTransition) { AsynchronousReceiveActionTransition receiveActionTransition = new AsynchronousReceiveActionTransition( IterableUtils.find(concreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(transition.getSourceState().getName()))), IterableUtils.find(concreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(midState.getName()))), inputMessage); concreteParticipantBehavior.getTransitions().add(receiveActionTransition); } // add synch or asynch send transition from midState state to synch state OutputMessage outputMessage = new OutputMessage(((SendingMessageActionTransition) transition).getMessage().getName()); com.sesygroup.choreography.concreteparticipantbehavior.model.Transition foundedSendActionTransition = CoordinationLogicRealizerUtils.findConcreteTransition( participantToConcreteParticipantBehaviorMap.get(cd.getLeft()), new State(transition.getSourceState().getName()), outputMessage); Validate.notNull(foundedSendActionTransition, ValidationMessages.IS_NULL_CONCRETE_PARTICIPANT_BEHAVIOR_TRANSITION_EXCEPTION_MESSAGE, outputMessage.getName()); if (foundedSendActionTransition instanceof SynchronousSendActionTransition) { SynchronousSendActionTransition sendActionTransition = new SynchronousSendActionTransition( IterableUtils.find(concreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(midState.getName()))), IterableUtils.find(concreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(synchState.getName()))), outputMessage); concreteParticipantBehavior.getTransitions().add(sendActionTransition); } else if (foundedSendActionTransition instanceof AsynchronousSendActionTransition) { AsynchronousSendActionTransition sendActionTransition = new AsynchronousSendActionTransition( IterableUtils.find(concreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(midState.getName()))), IterableUtils.find(concreteParticipantBehavior.getStates(), new EqualPredicate<State>(new State(synchState.getName()))), outputMessage); concreteParticipantBehavior.getTransitions().add(sendActionTransition); } getTargetCDs(choreographySpecification.getTransitions().stream().collect(Collectors.toList()), transition) .forEach(pair -> { ConcreteParticipantBehavior otherParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(pair); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(otherParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, pair); if (IterableUtils.find(otherParticipantBehavior.getStates(), new EqualPredicate<State>( new State(transition.getSourceState().getName() + BRANCH_STATE_SUFFIX))) == null) { State foundedSourceState = IterableUtils.find(otherParticipantBehavior.getStates(), new EqualPredicate<State>( new State(transition.getSourceState().getName() + SYNCH_STATE_SUFFIX))); if (foundedSourceState == null) { foundedSourceState = new State(transition.getSourceState().getName()); } State foundedTargetState = IterableUtils.find(otherParticipantBehavior.getStates(), new EqualPredicate<State>( new State(transition.getTargetState().getName() + SYNCH_STATE_SUFFIX))); if (foundedTargetState == null) { foundedTargetState = new State(transition.getTargetState().getName()); } InternalActionTransition internalActionTransition = new InternalActionTransition( IterableUtils.find(otherParticipantBehavior.getStates(), new EqualPredicate<State>(foundedSourceState)), IterableUtils.find(otherParticipantBehavior.getStates(), new EqualPredicate<State>(foundedTargetState))); otherParticipantBehavior.getTransitions().add(internalActionTransition); } }); } }); } private List<Pair<Participant, Participant>> getTargetCDs(final List<Transition> transitions, final Transition transitionToExclude) { List<Pair<Participant, Participant>> cdTargets = new ArrayList<Pair<Participant, Participant>>(); Pair<Participant, Participant> cdToExclude = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transitionToExclude).getSourceParticipant(), ((SendingMessageActionTransition) transitionToExclude).getTargetParticipant()); transitions.forEach(transition -> { Pair<Participant, Participant> cdTarget = new ImmutablePair<Participant, Participant>( ((SendingMessageActionTransition) transition).getSourceParticipant(), ((SendingMessageActionTransition) transition).getTargetParticipant()); if (!cdToExclude.equals(cdTarget)) { // get ConcreteParticipantBehavior of the CD ConcreteParticipantBehavior incomingConcreteParticipantBehavior = cdNameToConcreteParticipantBehaviorMap.get(cdTarget); // check if the ConcreteParticipantBehavior exists, should be always true Validate.notNull(incomingConcreteParticipantBehavior, ValidationMessages.IS_CD_NOT_IN_SET_OF_CDS_EXCEPTION_MESSAGE, cdTarget); cdTargets.add(cdTarget); } }); return cdTargets; } }
63.542763
120
0.658927
132dee4b4929300c15cb93495b3c5e9586befe5e
1,993
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.SDITStandardsAndGuidelinesFeedbackInputModelITStandardsAndGuidelinesFeedbackActionRecord; import javax.validation.Valid; /** * SDITStandardsAndGuidelinesFeedbackInputModel */ public class SDITStandardsAndGuidelinesFeedbackInputModel { private Object iTStandardsAndGuidelinesFeedbackActionTaskRecord = null; private SDITStandardsAndGuidelinesFeedbackInputModelITStandardsAndGuidelinesFeedbackActionRecord iTStandardsAndGuidelinesFeedbackActionRecord = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The feedback service call consolidated processing record * @return iTStandardsAndGuidelinesFeedbackActionTaskRecord **/ public Object getITStandardsAndGuidelinesFeedbackActionTaskRecord() { return iTStandardsAndGuidelinesFeedbackActionTaskRecord; } public void setITStandardsAndGuidelinesFeedbackActionTaskRecord(Object iTStandardsAndGuidelinesFeedbackActionTaskRecord) { this.iTStandardsAndGuidelinesFeedbackActionTaskRecord = iTStandardsAndGuidelinesFeedbackActionTaskRecord; } /** * Get iTStandardsAndGuidelinesFeedbackActionRecord * @return iTStandardsAndGuidelinesFeedbackActionRecord **/ public SDITStandardsAndGuidelinesFeedbackInputModelITStandardsAndGuidelinesFeedbackActionRecord getITStandardsAndGuidelinesFeedbackActionRecord() { return iTStandardsAndGuidelinesFeedbackActionRecord; } public void setITStandardsAndGuidelinesFeedbackActionRecord(SDITStandardsAndGuidelinesFeedbackInputModelITStandardsAndGuidelinesFeedbackActionRecord iTStandardsAndGuidelinesFeedbackActionRecord) { this.iTStandardsAndGuidelinesFeedbackActionRecord = iTStandardsAndGuidelinesFeedbackActionRecord; } }
39.86
198
0.864024
4f859c9250075fafb4224b3b2808528ab4eecc4b
781
package osgi.enroute.executor.capabilities; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import org.osgi.annotation.bundle.Requirement; import org.osgi.namespace.implementation.ImplementationNamespace; /** */ @Requirement(namespace = ImplementationNamespace.IMPLEMENTATION_NAMESPACE, filter = "(&(" + ImplementationNamespace.IMPLEMENTATION_NAMESPACE + "=" + ExecutorConstants.EXECUTOR_SPECIFICATION_NAME + ")${frange;${version;==;" + ExecutorConstants.EXECUTOR_SPECIFICATION_VERSION + "}})") @Retention(RetentionPolicy.CLASS) public @interface RequireExecutorImplementation { /** * The place where to look for resources * * @return the location */ String configuration_loc() default "configuration/configuration.json"; }
32.541667
89
0.786172
38bf9720ddd5df4d584af455d6fba176b3534093
717
package javabot2; import net.dv8tion.jda.api.JDA; public class Javabot2 { public static void main(String[] args) throws Exception { JDALoader jdaLoader = new JDALoader(); JDA api = JDALoader.getJDA(); api.addEventListener(jdaLoader); api.addEventListener(new MyListener()); } /** * To-do: * * What if the text file of text channels is gone? * What if the token text file is gone? * What if the token is invalid? * Add console warning if a file is not found * * Needs to improve naming * Move the comments to the top and keep under 70 * * Change the arraylist into a hash table (HashSet) * Serialization * * Gradle & Maven */ }
21.727273
59
0.642957
52d06f3bd48cc43a76d35f268c2303ca2a706b50
1,386
package org.tarantool.queue.auto; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import org.tarantool.queue.internals.operations.EvalOperation; import javax.annotation.processing.Filer; import javax.lang.model.element.Modifier; abstract class TtlQueueManagerGenerator extends QueueManagerGenerator { public TtlQueueManagerGenerator(Filer filer, QueueMeta queueMeta) { super(filer, queueMeta); } @Override protected TypeSpec.Builder queueBuilder(TypeSpec metaSpec) { return super.queueBuilder(metaSpec) .addMethod(generateTouch()); } private MethodSpec generateTouch() { return MethodSpec .methodBuilder("touch") .addModifiers(Modifier.PUBLIC) .returns(operationResultType) .addParameter(long.class, "taskId", Modifier.FINAL) .addParameter(long.class, "increment", Modifier.FINAL) .beginControlFlow("if (increment < 0)") .addStatement("throw new $T($S)", IllegalArgumentException.class, "increment should be >= 0") .endControlFlow() .addStatement("return new $T<>(tarantoolClient, meta, $T.format($S, queueName, taskId, increment))", EvalOperation.class, String.class, "return queue.tube.%s:touch(%s, %s)") .build(); } }
39.6
189
0.661616
71d2c7e1536f2991f1920e58c2d77713434b0b00
1,080
package io.contek.invoker.hbdmlinear.api.websocket.common; import io.contek.invoker.commons.websocket.AnyWebSocketMessage; import io.contek.invoker.commons.websocket.IWebSocketLiveKeeper; import io.contek.invoker.commons.websocket.WebSocketSession; import javax.annotation.concurrent.Immutable; @Immutable public final class WebSocketLiveKeeper implements IWebSocketLiveKeeper { public static WebSocketLiveKeeper getInstance() { return InstanceHolder.INSTANCE; } @Override public void onHeartbeat(WebSocketSession session) {} @Override public void onMessage(AnyWebSocketMessage message, WebSocketSession session) { if (message instanceof WebSocketPing) { WebSocketPing ping = (WebSocketPing) message; WebSocketPong pong = new WebSocketPong(); pong.pong = ping.ping; session.send(pong); } } @Override public void afterDisconnect() {} private WebSocketLiveKeeper() {} @Immutable private static final class InstanceHolder { private static final WebSocketLiveKeeper INSTANCE = new WebSocketLiveKeeper(); } }
27
82
0.771296
5e0059275ee2920e3ffb949c87106c3427779940
8,952
package com.citelic.game.entity.player.content.miscellaneous.pets; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.citelic.cache.impl.item.ItemDefinitions; import com.citelic.game.ForceTalk; import com.citelic.game.entity.Animation; import com.citelic.game.entity.npc.impl.pet.Pet; import com.citelic.game.entity.player.Player; import com.citelic.game.entity.player.item.Item; import com.citelic.game.entity.player.item.ItemConstants; /** * The pet manager. * * @author Emperor * */ public final class PetManager implements Serializable { /** * The serial UID. */ private static final long serialVersionUID = -3379270918966667109L; /** * The pet details mapping, sorted by item id. */ private final Map<Integer, PetDetails> petDetails = new HashMap<Integer, PetDetails>(); /** * The player. */ private Player player; /** * The current NPC id. */ private int npcId; /** * The current item id. */ private int itemId; /** * The troll baby's name (if any). */ private String trollBabyName; /** * Constructs a new {@code PetManager} {@code Object}. */ public PetManager() { /* * empty. */ } /** * Makes the pet eat. * * @param foodId * The food item id. * @param npc * The pet NPC. */ public void eat(int foodId, Pet npc) { if (npc != player.getPet()) { player.getPackets().sendGameMessage("This isn't your pet!"); return; } Pets pets = Pets.forId(itemId); if (pets == null) { return; } if (pets == Pets.TROLL_BABY) { if (!ItemConstants.isTradeable(new Item(foodId))) { player.getPackets().sendGameMessage( "Your troll baby won't eat this item."); return; } trollBabyName = ItemDefinitions.getItemDefinitions(foodId) .getName(); npc.setName(trollBabyName); npc.setNextForceTalk(new ForceTalk("YUM! Me likes " + trollBabyName + "!")); player.getInventory().deleteItem(foodId, 1); player.getPackets().sendGameMessage( "Your pet happily eats the " + ItemDefinitions.getItemDefinitions(foodId) .getName() + "."); return; } for (int food : pets.getFood()) { if (food == foodId) { player.getInventory().deleteItem(food, 1); player.getPackets().sendGameMessage( "Your pet happily eats the " + ItemDefinitions.getItemDefinitions(food) .getName() + "."); player.setNextAnimation(new Animation(827)); npc.getDetails().updateHunger(-15.0); return; } } player.getPackets().sendGameMessage("Nothing interesting happens."); } /** * Gets the itemId. * * @return The itemId. */ public int getItemId() { return itemId; } /** * Gets the npcId. * * @return The npcId. */ public int getNpcId() { return npcId; } /** * Gets the player. * * @return The player. */ public Player getPlayer() { return player; } /** * Gets the trollBabyName. * * @return The trollBabyName. */ public String getTrollBabyName() { return trollBabyName; } /** * Checks if the player has the requirements for the pet. * * @param pet * The pet. * @return {@code True} if so. */ private boolean hasRequirements(Pets pet) { switch (pet) { case TZREK_JAD: case SARADOMIN_OWL: case GUTHIX_RAPTOR: case ZAMORAK_HAWK: case VULTURE_1: case VULTURE_2: case VULTURE_3: case VULTURE_4: case VULTURE_5: case CHAMELEON: case BABY_DRAGON_1: case BABY_DRAGON_2: case BABY_DRAGON_3: case SEARING_FLAME: case GLOWING_EMBER: case TWISTED_FIRESTARTER: case WARMING_FLAME: return true; case FERRET: case GIANT_WOLPERTINGER: return player.getRights() > 1; case ABYSSAL_MINION: break; case BABY_BASILISK: break; case BABY_DRAGON: break; case BABY_KURASK: break; case BROAV: break; case BULLDOG: break; case BULLDOG_1: break; case BULLDOG_2: break; case CAT: break; case CAT_1: break; case CAT_2: break; case CAT_3: break; case CAT_4: break; case CAT_5: break; case CAT_7: break; case CLOCKWORK_CAT: break; case CREEPING_HAND: break; case CUTE_PHOENIX_EGGLING: break; case DALMATIAN: break; case DALMATIAN_1: break; case DALMATIAN_2: break; case EX_EX_PARROT: break; case GECKO: break; case GECKO_1: break; case GECKO_2: break; case GECKO_3: break; case GECKO_4: break; case GIANT_CRAB: break; case GIANT_CRAB_1: break; case GIANT_CRAB_2: break; case GIANT_CRAB_3: break; case GIANT_CRAB_4: break; case GREYHOUND: break; case GREYHOUND_1: break; case GREYHOUND_2: break; case HELLCAT: break; case LABRADOR: break; case LABRADOR_1: break; case LABRADOR_2: break; case MEAN_PHOENIX_EGGLING: break; case MINITRICE: break; case MONKEY: break; case MONKEY_1: break; case MONKEY_2: break; case MONKEY_3: break; case MONKEY_4: break; case MONKEY_5: break; case MONKEY_6: break; case MONKEY_7: break; case MONKEY_8: break; case MONKEY_9: break; case PENGUIN: break; case PENGUIN_1: break; case PENGUIN_2: break; case PLATYPUS: break; case PLATYPUS_1: break; case PLATYPUS_2: break; case RACCOON: break; case RACCOON_1: break; case RACCOON_2: break; case RAVEN: break; case RAVEN_1: break; case RAVEN_2: break; case RAVEN_3: break; case RAVEN_4: break; case RAVEN_5: break; case RUNE_GUARDIAN: break; case RUNE_GUARDIAN_1: break; case RUNE_GUARDIAN_10: break; case RUNE_GUARDIAN_11: break; case RUNE_GUARDIAN_12: break; case RUNE_GUARDIAN_13: break; case RUNE_GUARDIAN_2: break; case RUNE_GUARDIAN_3: break; case RUNE_GUARDIAN_4: break; case RUNE_GUARDIAN_5: break; case RUNE_GUARDIAN_6: break; case RUNE_GUARDIAN_7: break; case RUNE_GUARDIAN_8: break; case RUNE_GUARDIAN_9: break; case SHEEPDOG: break; case SHEEPDOG_1: break; case SHEEPDOG_2: break; case SNEAKER_PEEPER: break; case SQUIRREL: break; case SQUIRREL_1: break; case SQUIRREL_2: break; case SQUIRREL_3: break; case SQUIRREL_4: break; case TERRIER: break; case TERRIER_1: break; case TERRIER_2: break; case TOOTH_CREATURE: break; case TROLL_BABY: break; case VULTURE: break; default: break; } return true; } /** * Initializes the pet manager. */ public void init() { if (npcId > 0 && itemId > 0) { spawnPet(itemId, false); } } /** * Removes the details for this pet. * * @param npcId * The item id of the pet. */ public void removeDetails(int itemId) { Pets pets = Pets.forId(itemId); if (pets == null) { return; } petDetails.remove(pets.getBabyItemId()); } /** * Sets the itemId. * * @param itemId * The itemId to set. */ public void setItemId(int itemId) { this.itemId = itemId; } /** * Sets the npcId. * * @param npcId * The npcId to set. */ public void setNpcId(int npcId) { this.npcId = npcId; } /** * Sets the player. * * @param player * The player to set. */ public void setPlayer(Player player) { this.player = player; } /** * Sets the trollBabyName. * * @param trollBabyName * The trollBabyName to set. */ public void setTrollBabyName(String trollBabyName) { this.trollBabyName = trollBabyName; } /** * Spawns a pet. * * @param itemId * The item id. * @param deleteItem * If the item should be removed. * @return {@code True} if we were dealing with a pet item id. */ public boolean spawnPet(int itemId, boolean deleteItem) { Pets pets = Pets.forId(itemId); if (pets == null) { return false; } if (player.getPet() != null || player.getFamiliar() != null) { player.getPackets().sendGameMessage("You already have a follower."); return true; } if (!hasRequirements(pets)) { return true; } int baseItemId = pets.getBabyItemId(); PetDetails details = petDetails.get(baseItemId); if (details == null) { details = new PetDetails(pets.getGrowthRate() == 0.0 ? 100.0 : 0.0); petDetails.put(baseItemId, details); } int id = pets.getItemId(details.getStage()); if (itemId != id) { player.getPackets().sendGameMessage( "This is not the right pet, grow the pet correctly."); return true; } int npcId = pets.getNpcId(details.getStage()); if (npcId > 0) { Pet pet = new Pet(npcId, itemId, player, player, details); this.npcId = npcId; this.itemId = itemId; pet.setGrowthRate(pets.getGrowthRate()); player.setPet(pet); if (deleteItem) { player.setNextAnimation(new Animation(827)); player.getInventory().deleteItem(itemId, 1); } return true; } return true; } }
18.419753
88
0.640974
34000f4bcd68646d7dfe8ca58d942fb2a69de4dd
3,115
/* * Copyright (c) 2017-2020 Peter G. Horvath, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.blausql.ui; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.googlecode.lanterna.gui.Component; import com.googlecode.lanterna.gui.Window; import com.googlecode.lanterna.gui.component.Label; import com.googlecode.lanterna.gui.component.Table; import com.googlecode.lanterna.gui.listener.WindowAdapter; import com.googlecode.lanterna.input.Key; import com.googlecode.lanterna.input.Key.Kind; class QueryResultWindow extends Window { @SuppressWarnings("FieldCanBeLocal") private final WindowAdapter closeOnEscOrEnterWindowListener = new WindowAdapter() { @Override public void onUnhandledKeyboardInteraction(Window window, Key key) { if (Kind.Escape.equals(key.getKind()) || Kind.Enter.equals(key.getKind())) { QueryResultWindow.this.close(); } } }; //CHECKSTYLE.OFF: AvoidInlineConditionals QueryResultWindow(List<Map<String, Object>> queryResult) { super("Query result (press Enter/ESC to close)"); addWindowListener(closeOnEscOrEnterWindowListener); if (queryResult.size() == 0) { addComponent(new Label("(query yielded no results)")); } else { Map<String, Object> firstRow = queryResult.get(0); final ArrayList<String> columnLabels = new ArrayList<>( firstRow.keySet()); final int numberOfColumns = columnLabels.size(); Table table = new Table(numberOfColumns); Component[] components = new Component[numberOfColumns]; for (int i = 0; i < numberOfColumns; i++) { components[i] = new Label(columnLabels.get(i)); } table.addRow(components); for (Map<String, Object> row : queryResult) { for (int i = 0; i < numberOfColumns; i++) { final String currentColumnLabel = columnLabels.get(i); final Object valueForCurrentColumn = row.get(currentColumnLabel); final Label labelForCurrentColumnValue = (valueForCurrentColumn != null) ? new Label(valueForCurrentColumn.toString()) : new Label("null", true); components[i] = labelForCurrentColumnValue; } table.addRow(components); } addComponent(table); } } //CHECKSTYLE.ON }
32.447917
100
0.642697
9f4ec2e11556e16f24b1cfba5507dc4a1195b866
2,322
/** * 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.pinot.controller.helix.core.realtime.segment; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.pinot.core.realtime.stream.PartitionLevelStreamConfig; /** * Manager which maintains the flush threshold update objects for each table */ public class FlushThresholdUpdateManager { private final ConcurrentMap<String, FlushThresholdUpdater> _flushThresholdUpdaterMap = new ConcurrentHashMap<>(); /** * Check table config for flush size. * * If flush size > 0, create a new DefaultFlushThresholdUpdater with given flush size. * If flush size <= 0, create new SegmentSizeBasedFlushThresholdUpdater if not already created. Create only 1 per * table because we want to maintain tuning information for the table in the updater. */ public FlushThresholdUpdater getFlushThresholdUpdater(PartitionLevelStreamConfig streamConfig) { String realtimeTableName = streamConfig.getTableNameWithType(); int flushThresholdRows = streamConfig.getFlushThresholdRows(); if (flushThresholdRows > 0) { _flushThresholdUpdaterMap.remove(realtimeTableName); return new DefaultFlushThresholdUpdater(flushThresholdRows); } else { return _flushThresholdUpdaterMap .computeIfAbsent(realtimeTableName, k -> new SegmentSizeBasedFlushThresholdUpdater()); } } public void clearFlushThresholdUpdater(String realtimeTableName) { _flushThresholdUpdaterMap.remove(realtimeTableName); } }
41.464286
115
0.77261
4bd6d0538ac8d4102133c1fb93bc786ea89811e0
1,158
package com.iovation.launchkey.sdk.transport.domain; /** * Copyright 2017 iovation, Inc. * <p> * Licensed under the MIT License. * You may not use this file except in compliance with the License. * A copy of the License is located in the "LICENSE.txt" file accompanying * this file. This file 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. */ import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.util.UUID; import static org.junit.Assert.assertEquals; public class ServicesPostResponseTest { @Test public void getId() throws Exception { UUID id = UUID.randomUUID(); assertEquals(id, new ServicesPostResponse(id).getId()); } @Test public void fromJSON() throws Exception { UUID id = UUID.randomUUID(); ServicesPostResponse read = new ObjectMapper() .readValue("{\"id\": \"" + id.toString() + "\"}", ServicesPostResponse.class); assertEquals(id, read.getId()); } }
34.058824
94
0.697755
41f664a0414bf5f746d7d031c5206f26c7fc1778
6,962
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.perftest; import android.os.Environment; import android.content.res.Resources; import android.renderscript.*; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; public class FillTest implements RsBenchBaseTest{ private static final String TAG = "FillTest"; private RenderScriptGL mRS; private Resources mRes; // Custom shaders private ProgramFragment mProgFragmentMultitex; private ProgramFragment mProgFragmentSingletex; private ProgramFragment mProgFragmentSingletexModulate; private final BitmapFactory.Options mOptionsARGB = new BitmapFactory.Options(); int mBenchmarkDimX; int mBenchmarkDimY; private ScriptC_fill_test mFillScript; ScriptField_TestScripts_s.Item[] mTests; ScriptField_FillTestFragData_s mFragData; private final String[] mNames = { "Fill screen 10x singletexture", "Fill screen 10x 3tex multitexture", "Fill screen 10x blended singletexture", "Fill screen 10x blended 3tex multitexture", "Fill screen 3x modulate blended singletexture", "Fill screen 1x modulate blended singletexture", }; public FillTest() { mOptionsARGB.inScaled = false; mOptionsARGB.inPreferredConfig = Bitmap.Config.ARGB_8888; mBenchmarkDimX = 1280; mBenchmarkDimY = 720; } void addTest(int index, int testId, int blend, int quadCount) { mTests[index] = new ScriptField_TestScripts_s.Item(); mTests[index].testScript = mFillScript; mTests[index].testName = Allocation.createFromString(mRS, mNames[index], Allocation.USAGE_SCRIPT); mTests[index].debugName = RsBenchRS.createZeroTerminatedAlloc(mRS, mNames[index], Allocation.USAGE_SCRIPT); ScriptField_FillTestData_s.Item dataItem = new ScriptField_FillTestData_s.Item(); dataItem.testId = testId; dataItem.blend = blend; dataItem.quadCount = quadCount; ScriptField_FillTestData_s testData = new ScriptField_FillTestData_s(mRS, 1); testData.set(dataItem, 0, true); mTests[index].testData = testData.getAllocation(); } public boolean init(RenderScriptGL rs, Resources res) { mRS = rs; mRes = res; initCustomShaders(); initFillScript(); mTests = new ScriptField_TestScripts_s.Item[mNames.length]; int index = 0; addTest(index++, 1 /*testId*/, 0 /*blend*/, 10 /*quadCount*/); addTest(index++, 0 /*testId*/, 0 /*blend*/, 10 /*quadCount*/); addTest(index++, 1 /*testId*/, 1 /*blend*/, 10 /*quadCount*/); addTest(index++, 0 /*testId*/, 1 /*blend*/, 10 /*quadCount*/); addTest(index++, 2 /*testId*/, 1 /*blend*/, 3 /*quadCount*/); addTest(index++, 2 /*testId*/, 1 /*blend*/, 1 /*quadCount*/); return true; } public ScriptField_TestScripts_s.Item[] getTests() { return mTests; } public String[] getTestNames() { return mNames; } private void initCustomShaders() { ProgramFragment.Builder pfbCustom = new ProgramFragment.Builder(mRS); pfbCustom.setShader(mRes, R.raw.multitexf); for (int texCount = 0; texCount < 3; texCount ++) { pfbCustom.addTexture(Program.TextureType.TEXTURE_2D); } mProgFragmentMultitex = pfbCustom.create(); pfbCustom = new ProgramFragment.Builder(mRS); pfbCustom.setShader(mRes, R.raw.singletexf); pfbCustom.addTexture(Program.TextureType.TEXTURE_2D); mProgFragmentSingletex = pfbCustom.create(); pfbCustom = new ProgramFragment.Builder(mRS); pfbCustom.setShader(mRes, R.raw.singletexfm); pfbCustom.addTexture(Program.TextureType.TEXTURE_2D); mFragData = new ScriptField_FillTestFragData_s(mRS, 1); pfbCustom.addConstant(mFragData.getType()); mProgFragmentSingletexModulate = pfbCustom.create(); mProgFragmentSingletexModulate.bindConstants(mFragData.getAllocation(), 0); } private Allocation loadTextureARGB(int id) { Bitmap b = BitmapFactory.decodeResource(mRes, id, mOptionsARGB); return Allocation.createFromBitmap(mRS, b, Allocation.MipmapControl.MIPMAP_ON_SYNC_TO_TEXTURE, Allocation.USAGE_GRAPHICS_TEXTURE); } private Allocation loadTextureRGB(int id) { return Allocation.createFromBitmapResource(mRS, mRes, id, Allocation.MipmapControl.MIPMAP_ON_SYNC_TO_TEXTURE, Allocation.USAGE_GRAPHICS_TEXTURE); } void initFillScript() { mFillScript = new ScriptC_fill_test(mRS, mRes, R.raw.fill_test); ProgramVertexFixedFunction.Builder pvb = new ProgramVertexFixedFunction.Builder(mRS); ProgramVertexFixedFunction progVertex = pvb.create(); ProgramVertexFixedFunction.Constants PVA = new ProgramVertexFixedFunction.Constants(mRS); ((ProgramVertexFixedFunction)progVertex).bindConstants(PVA); Matrix4f proj = new Matrix4f(); proj.loadOrthoWindow(mBenchmarkDimX, mBenchmarkDimY); PVA.setProjection(proj); mFillScript.set_gProgVertex(progVertex); mFillScript.set_gProgFragmentTexture(mProgFragmentSingletex); mFillScript.set_gProgFragmentTextureModulate(mProgFragmentSingletexModulate); mFillScript.set_gProgFragmentMultitex(mProgFragmentMultitex); mFillScript.set_gProgStoreBlendNone(ProgramStore.BLEND_NONE_DEPTH_NONE(mRS)); mFillScript.set_gProgStoreBlendAlpha(ProgramStore.BLEND_ALPHA_DEPTH_NONE(mRS)); mFillScript.set_gLinearClamp(Sampler.CLAMP_LINEAR(mRS)); mFillScript.set_gLinearWrap(Sampler.WRAP_LINEAR(mRS)); mFillScript.set_gTexTorus(loadTextureRGB(R.drawable.torusmap)); mFillScript.set_gTexOpaque(loadTextureRGB(R.drawable.data)); mFillScript.set_gTexTransparent(loadTextureARGB(R.drawable.leaf)); mFillScript.set_gTexChecker(loadTextureRGB(R.drawable.checker)); mFillScript.bind_gFragData(mFragData); } }
40.476744
97
0.676386
e835607229daa6795e39d69e07ff47c942193e8d
2,670
/* * Copyright (C) 2019 Houssem Ben Mabrouk * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package model; /** * * @author Houssem Ben Mabrouk */ public class Client { private int id; private String nom; private String prenom; private int numCarteFidelite; private String mail; private int codePostal; public Client() { } public Client(int id, String nom, String prenom, int numCarteFidelite, String mail, int codePostal) { this.id = id; this.nom = nom.toUpperCase(); this.prenom = prenom; this.numCarteFidelite = numCarteFidelite; this.mail = mail; this.codePostal = codePostal; } public Client(String nom, String prenom, int numCarteFidelite, String mail, int codePostal) { this.nom = nom.toUpperCase(); this.prenom = prenom; this.numCarteFidelite = numCarteFidelite; this.mail = mail; this.codePostal = codePostal; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom.toUpperCase(); } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public int getNumCarteFidelite() { return numCarteFidelite; } public void setNumCarteFidelite(int numCarteFidelite) { this.numCarteFidelite = numCarteFidelite; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public int getCodePostal() { return codePostal; } public void setCodePostal(int codePostal) { this.codePostal = codePostal; } @Override public String toString() { return numCarteFidelite + " | " + nom + " " + prenom; } }
25.188679
106
0.611985
99f77d15cbbd6c410f7e982683ce7ed3df8ae7b3
2,235
package com.company; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class P10_ExamResults { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); HashMap<String, Integer> studentResults = new HashMap<>(); HashMap<String, Integer> counts = new HashMap<>(); int score = 0; while (true) { String input = scanner.nextLine(); if (input.equals("exam finished")) { break; } String[] info = input.split("-"); String name = info[0]; String submission = info[1]; if (info.length > 2) { score = Integer.parseInt(info[2]); } if (!studentResults.containsKey(name) && info.length > 2) { studentResults.put(name, score); } else { if (studentResults.get(name) < score) { studentResults.put(name, score); } } if (!counts.containsKey(submission) && info.length > 2) { counts.put(submission, 1); } else if (info.length > 2) { counts.put(submission, counts.get(submission) + 1); } if (submission.equals("banned")) { studentResults.remove(name); } } System.out.println("Results:"); studentResults.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed() .thenComparing(Map.Entry.<String, Integer>comparingByKey())) .forEach(e -> { System.out.printf("%s | %d\n", e.getKey(), e.getValue()); }); System.out.println("Submissions:"); counts.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed() .thenComparing(Map.Entry.<String, Integer>comparingByKey())) .forEach(e -> { System.out.printf("%s - %d\n", e.getKey(), e.getValue()); }); } }
31.041667
85
0.484116
0ba049396a75de0194869ebd866722f727135936
1,471
package net.muratbalkan.sinnumbervalidator; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @Order(Ordered.HIGHEST_PRECEDENCE) @ControllerAdvice public class AppExceptionHandlers extends ResponseEntityExceptionHandler { private ResponseEntity<Object> buildResponseEntity(ApiError apiError) { return new ResponseEntity<>(apiError, apiError.getStatus()); } //exception handler for HttpRequestMethodNotSupported. @Override protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return buildResponseEntity(new ApiError(HttpStatus.BAD_REQUEST, ex.getMessage())); //populate the ophect } } //catcall exception handler: @Override protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { return buildResponseEntity(new ApiError(status, ex.getMessage())); //populate the ophect } }
47.451613
173
0.842284
3840f889bfc40641f5cf305fca65dfe63b4a8040
224
package eu.vargapeter.financialstatistics.exception; public class ImportFileFormatNotValidException extends RuntimeException { public ImportFileFormatNotValidException(String message) { super(message); } }
24.888889
73
0.794643
5273f74cd708e97086314351ddc91b574e077501
987
package test.java; import org.junit.Test; import com.jacamars.dsp.rtb.jmq.ZPublisher; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; /** * A class for testing that the bid has the right parameters * * @author Ben M. Faul * */ public class TestFileSubscriber { /** * Test a valid bid response. * * @throws Exception * on networking errors. */ @Test public void testPublisherAndSubscriber() throws Exception { com.jacamars.dsp.rtb.jmq.RTopic channel = new com.jacamars.dsp.rtb.jmq.RTopic("file:///media/twoterra/samples/request-2017-03-22-18:13&whence=bof"); channel.addListener(new com.jacamars.dsp.rtb.jmq.MessageListener<String>() { @Override public void onMessage(String channel, String data) { System.out.println("<<<<<<<<<<<<<<<<<" + data); // latch.countDown(); } }); Thread.sleep(15000); } }
23.5
156
0.631206
aa3e438906faef5aea0a75f011510193710ebd92
335
package cl.roberto.microservicios.ventasservice.stream; import org.springframework.integration.annotation.Gateway; import org.springframework.integration.annotation.MessagingGateway; @MessagingGateway public interface BodegaGateway { @Gateway(requestChannel = BodegaSource.CHANNEL_NAME) void generate(AvisoDTO avisoDTO); }
25.769231
67
0.832836
fb93c6858bd113b9f3b432a532b4996e029ae1ee
60
package mods.natura.plugins; public class Gardenstuff { }
10
28
0.766667
0abc0bb9fb1a4335997b66869fe617b64c3595cc
916
package designPatterns; interface Behavior { void moveCommand(); } class Robot { private Behavior behavior; public void setBehavior(Behavior behavior) { this.behavior = behavior; } public void move() { this.behavior.moveCommand(); } } class PassiveBehavior implements Behavior { @Override public void moveCommand() { System.out.println("Standing in place"); } } class AggressiveBehavior implements Behavior { @Override public void moveCommand() { System.out.println("Aggressive!"); } } public class StrategyPattern { public static void main(String[] args) { Robot robot = new Robot(); Behavior behavior = new PassiveBehavior(); robot.setBehavior(behavior); robot.move(); // Standing in place robot.setBehavior(new AggressiveBehavior()); robot.move(); // Aggressive } }
19.489362
52
0.639738
ae08f98e1ac2b7d9346f60a19a3209e2afb5e5a8
654
package indi.w4xj.jvm.code; /** * @Author lemon joker * @Project java_upstream * @Package indi.w4xj.jvm.code * @Classname StackOverflowErrorTest * @Description TODO * @Date 2021/2/16 11:51 * @Created by IntelliJ IDEA */ public class StackOverflowErrorTest { public static void main(String[] args) { method(); } private static void method(){ /* Exception in thread "main" java.lang.StackOverflowError at indi.w4xj.jvm.code.StackOverflowErrorTest.method(StackOverflowErrorTest.java:24) ... Process finished with exit code 1 */ method(); } }
24.222222
99
0.623853
a98037077435fcc3ec3cfa34efd6450547e6a783
19,456
package com.tekdivisal.safet; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.tekdivisal.safet.Adapters.ChildrenAdapter; import com.tekdivisal.safet.Model.Children; import java.util.ArrayList; import java.util.Random; /** * A simple {@link Fragment} subclass. */ public class Locate_Children extends Fragment { private TextView no_children_textView; private TextView no_internet; private ArrayList childrenArray = new ArrayList<Children>(); private RecyclerView children_RecyclerView; private RecyclerView.Adapter children_Adapter; private String school_id_string, parent_code_string, string_child_code, sfirst_name, slastname, sclass, sgender, driver_key, is_assigned, the_assigned_bus; private Accessories home_accessor; private String bus_arrived_title, bus_arrived_message, bus_arrived_time, bus_arrivedImage, bus_arrived_status; public Locate_Children() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View home = inflater.inflate(R.layout.fragment_locate_children, container, false); getActivity().setTitle("Locate_Children"); setRetainInstance(true); //initialization of accessories home_accessor = new Accessories(getActivity()); no_children_textView = home.findViewById(R.id.no_children); no_internet = home.findViewById(R.id.no_internet); children_RecyclerView = home.findViewById(R.id.children_recyclerView); //strings school_id_string = home_accessor.getString("school_code"); parent_code_string = home_accessor.getString("user_phone_number"); if(isNetworkAvailable()){ get_Children_IDs(); new Look_for_all().execute(); }else{ no_children_textView.setVisibility(View.GONE); no_internet.setVisibility(View.VISIBLE); } children_RecyclerView.setHasFixedSize(true); children_RecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL)); children_Adapter = new ChildrenAdapter(getFromDatabase(),getActivity()); children_RecyclerView.setAdapter(children_Adapter); no_internet.setOnClickListener(v -> { if(isNetworkAvailable()){ get_Children_IDs(); new Look_for_all().execute(); }else{ no_children_textView.setVisibility(View.GONE); no_internet.setVisibility(View.VISIBLE); } }); return home; } private void get_Children_IDs() { try{ DatabaseReference get_child_id = FirebaseDatabase.getInstance().getReference("children").child(school_id_string).child(parent_code_string); get_child_id.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ for(DataSnapshot child : dataSnapshot.getChildren()){ Fetch_Child_Details(child.getKey()); } }else{ // Toast.makeText(getActivity(),"Cannot get ID",Toast.LENGTH_LONG).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { // Toast.makeText(getActivity().this,"Cancelled",Toast.LENGTH_LONG).show(); } }); }catch (NullPointerException e){ } } private void Fetch_Child_Details(final String key) { DatabaseReference getChild_info = FirebaseDatabase.getInstance().getReference("children").child(school_id_string).child(parent_code_string).child(key); getChild_info.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ for(DataSnapshot child : dataSnapshot.getChildren()){ if(child.getKey().equals("firstname")){ sfirst_name = child.getValue().toString(); } if(child.getKey().equals("lastname")){ slastname = child.getValue().toString(); } if(child.getKey().equals("class")){ sclass = child.getValue().toString(); } if(child.getKey().equals("gender")){ sgender = child.getValue().toString(); } if(child.getKey().equals("isAssigned_bus")){ is_assigned = child.getValue().toString(); } if(child.getKey().equals("assigned_bus")){ the_assigned_bus = child.getValue().toString(); } string_child_code = key; } Children obj = new Children(parent_code_string,sfirst_name,slastname,sclass,sgender, string_child_code,is_assigned,the_assigned_bus); childrenArray.add(obj); children_RecyclerView.setAdapter(children_Adapter); children_Adapter.notifyDataSetChanged(); no_internet.setVisibility(View.GONE); no_children_textView.setVisibility(View.GONE); //might get user details here } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private class Look_for_all extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... strings) { // final Handler thehandler; // // thehandler = new Handler(Looper.getMainLooper()); // final int delay = 15000; // // thehandler.postDelayed(new Runnable() { // @Override // public void run() { if(isNetworkAvailable()){ get_bus_Arrived_IDs(); get_bus_status_IDs(); }else{ // Toast.makeText(Admin_MainActivity.this,"checking", Toast.LENGTH_LONG).show(); } // thehandler.postDelayed(this,delay); // } // },delay); return null; } } private void get_bus_Arrived_IDs() { // Toast.makeText(getActivity(), "working",Toast.LENGTH_LONG).show(); try { DatabaseReference get_Bus_arrived = FirebaseDatabase.getInstance().getReference("bus_notification") .child(parent_code_string).child(school_id_string); get_Bus_arrived.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ for(DataSnapshot child : dataSnapshot.getChildren()){ Has_bus_arrived(child.getKey()); } }else{ // Toast.makeText(getActivity(),"Cannot get ID",Toast.LENGTH_LONG).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getActivity(),"Cancelled",Toast.LENGTH_LONG).show(); } }); }catch(NullPointerException e){ } } private void Has_bus_arrived(final String key) { DatabaseReference has_bus_arrived = FirebaseDatabase.getInstance().getReference("bus_notification") .child(parent_code_string).child(school_id_string).child(key); has_bus_arrived.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ for(DataSnapshot child : dataSnapshot.getChildren()){ if(child.getKey().equals("title")){ bus_arrived_title = child.getValue().toString(); } if(child.getKey().equals("message")){ bus_arrived_message = child.getValue().toString(); } if(child.getKey().equals("time")){ bus_arrived_time = child.getValue().toString(); } if(child.getKey().equals("image")){ bus_arrivedImage = child.getValue().toString(); } else{ // Toast.makeText(getActivity(),"Couldn't fetch posts",Toast.LENGTH_LONG).show(); } } driver_key = key; Show_arrived_notification(R.drawable.finish_line,bus_arrived_title, bus_arrived_message, bus_arrivedImage,bus_arrived_time); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getActivity(),"Cancelled",Toast.LENGTH_LONG).show(); } }); } private void Show_arrived_notification(int iconss, String bus_arrived_title, String bus_arrived_message, String bus_arrivedImage, String bus_arrived_time) { // Create an explicit intent for an Activity in your app Intent intent = new Intent(getActivity(), Notifications.class); // intent.putExtra("alertID","yes"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity(), "1100") .setSmallIcon(iconss) .setContentTitle(bus_arrived_title) .setContentText(bus_arrived_message) .setStyle(new NotificationCompat.BigTextStyle() .bigText(bus_arrived_message)) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) .setAutoCancel(true); // .setFullScreenIntent(fullScreenPendingIntent,true); // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.app_name); String description = getString(R.string.app_name); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel("1100", name, importance); channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = getActivity().getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(getActivity()); // notificationId is a unique int for each notification that you must define notificationManagerCompat.notify(1100, builder.build()); // builder.setDefaults(Notification.DEFAULT_SOUND); builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); // builder.setDefaults(Notification.DEFAULT_VIBRATE); if(bus_arrivedImage.equals("BAN")){ Move_Arrived_From_pending(bus_arrived_title,bus_arrived_message,bus_arrivedImage,bus_arrived_time); }else{ // Toast.makeText(getActivity(),"Nothing to move",Toast.LENGTH_LONG).show(); } } // builder.setDefaults(Notification.DEFAULT_SOUND); builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); // builder.setDefaults(Notification.DEFAULT_VIBRATE); NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(getActivity()); // notificationId is a unique int for each notification that you must define notificationManagerCompat.notify(1100, builder.build()); if(bus_arrivedImage != null){ Move_Arrived_From_pending(bus_arrived_title,bus_arrived_message,bus_arrivedImage,bus_arrived_time); }else{ Toast.makeText(getActivity(),"Nothing to move",Toast.LENGTH_LONG).show(); } } private void Move_Arrived_From_pending(String bus_arrived_title, String bus_arrived_message, String bus_arrivedImage, String bus_arrived_time) { try { Random ndd = new Random(); int rr = ndd.nextInt(99999); String notifications_id = "notification"+rr+""; DatabaseReference move_from_bus_notification_to_main = FirebaseDatabase.getInstance().getReference("notifications") .child(school_id_string).child(parent_code_string).child(notifications_id); move_from_bus_notification_to_main.child("BAN").setValue(bus_arrivedImage); move_from_bus_notification_to_main.child("message").setValue(bus_arrived_message); move_from_bus_notification_to_main.child("title").setValue(bus_arrived_title); move_from_bus_notification_to_main.child("time").setValue(bus_arrived_time).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { ReMoveSecurity_from_main_toPending(parent_code_string); } }); }catch (NullPointerException e){ } } private void ReMoveSecurity_from_main_toPending(String parent_code_string) { try { DatabaseReference removeRef = FirebaseDatabase.getInstance().getReference("bus_notification").child(parent_code_string); removeRef.removeValue(); }catch (NullPointerException e){ } } private void get_bus_status_IDs() { // Toast.makeText(getActivity(), "house", Toast.LENGTH_LONG).show(); try { DatabaseReference get_Bus_arrived = FirebaseDatabase.getInstance().getReference("trip_status") .child(school_id_string); get_Bus_arrived.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ for(DataSnapshot child : dataSnapshot.getChildren()){ get_Bus_Status(child.getKey()); } }else{ // Toast.makeText(getActivity(),"Cannot get ID",Toast.LENGTH_LONG).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getActivity(),"Cancelled",Toast.LENGTH_LONG).show(); } }); }catch(NullPointerException e){ } } private void get_Bus_Status(String key) { // Toast.makeText(getActivity(), "working", Toast.LENGTH_LONG).show(); DatabaseReference get_Bus_status = FirebaseDatabase.getInstance().getReference("trip_status") .child(school_id_string).child(key); get_Bus_status.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ for(DataSnapshot child : dataSnapshot.getChildren()){ if(child.getKey().equals("status")){ try { bus_arrived_status = child.getValue().toString(); // Toast.makeText(getActivity(), bus_arrived_status,Toast.LENGTH_LONG).show(); // home_accessor.put("bus_status", bus_arrived_status); }catch (NullPointerException e){ e.printStackTrace(); } } else{ // Toast.makeText(getActivity(),"Couldn't fetch posts",Toast.LENGTH_LONG).show(); } } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getActivity(),"Cancelled",Toast.LENGTH_LONG).show(); } }); } public ArrayList<Children> getFromDatabase(){ return childrenArray; } private boolean isNetworkAvailable() { try { ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }catch (NullPointerException e){ } return false; } }
43.623318
159
0.603927
17ca19f9df8378b8dc9581a4a12f6b881e0bee2a
596
package west.unikoblenz.beseppi.resultformats; // Ask query results consist of bool and execution time public class AskQueryResult { private boolean result; private long executionTime; public AskQueryResult(boolean result, long executionTime){ this.setResult(result); this.setExecutionTime(executionTime); } public boolean isResult() { return result; } public void setResult(boolean result) { this.result = result; } public long getExecutionTime() { return executionTime; } public void setExecutionTime(long executionTime) { this.executionTime = executionTime; } }
20.551724
59
0.763423
68bcbbe5099da0cf6c3cb3382606136066c2bf3f
1,888
package org.segrada.model; import org.junit.BeforeClass; import org.junit.Test; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.segrada.test.PropertyAsserter.assertBasicGetterSetterBehavior; public class SourceReferenceTest { private static Validator validator; @BeforeClass public static void setUp() throws Exception { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } @Test public void defaultValues() throws Exception { final SourceReference sourceReference = new SourceReference(); assertEquals("", sourceReference.getReferenceText()); } @Test public void testProperties() { assertBasicGetterSetterBehavior(new SourceReference()); } @Test public void testValidSourceReference() throws Exception { final SourceReference sourceReference = new SourceReference(); sourceReference.setSource(new Source()); sourceReference.setReference(new Node()); Set<ConstraintViolation<SourceReference>> constraintViolations = validator.validate(sourceReference); assertTrue("Source reference not valid", constraintViolations.size() == 0); } @Test public void testSourceEmpty() throws Exception { Set<ConstraintViolation<SourceReference>> constraintViolations = validator.validateValue(SourceReference.class, "source", null); assertTrue("Source empty", constraintViolations.size() == 1); } @Test public void testReferenceEmpty() throws Exception { Set<ConstraintViolation<SourceReference>> constraintViolations = validator.validateValue(SourceReference.class, "reference", null); assertTrue("Reference empty", constraintViolations.size() == 1); } }
33.122807
133
0.797669
c121721e911d518dd7f47c8804a9f0695dae3df4
2,961
package org.martseniuk.diploma.apigateway.config; import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents; import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider; import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper; import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; /** * Security configuration for KeyCloak recourse server. * * @author Roman_Martseniuk */ @Configuration @EnableWebSecurity @Profile("prod") @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider(); keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper()); auth.authenticationProvider(keycloakAuthenticationProvider); } @Bean public KeycloakSpringBootConfigResolver keycloakConfigResolver() { return new KeycloakSpringBootConfigResolver(); } @Bean @Override protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); } @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); http.sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) .and() .csrf().disable() .authorizeRequests() .antMatchers("/foo/**").hasRole("admin") .antMatchers("/bar/**").hasRole("user") .and() .logout() .logoutUrl("/logout") .invalidateHttpSession(true) .deleteCookies("JSESSIONID"); } }
44.19403
107
0.777102
cbf07ef9ae4974ba165c9150b3c3cdd4939f28dd
5,179
/** * 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.kafka.metrics.topic; import com.cloudera.csd.tools.codahale.CodahaleMetric; import com.cloudera.csd.tools.codahale.CodahaleMetricTypes; import org.apache.kafka.metrics.UnitConstants; import java.util.Arrays; import java.util.List; /** * Note: The context is missing its "root" because that is generated per topic in CM */ public class TopicMetrics { private static final CodahaleMetric MESSAGES_RECEIVED_METRIC = new CodahaleMetric.Builder() .setName("messages_received") .setLabel("Messages Received") .setDescription("Number of messages written to topic on this broker") .setNumerator(UnitConstants.messages) .setDenominator(UnitConstants.second) .setCodahaleMetricType(CodahaleMetricTypes.CodahaleMetricType.METER) .setContext("MessagesInPerSec") .build(); private static final CodahaleMetric BYTES_RECEIVED_METRIC = new CodahaleMetric.Builder() .setName("bytes_received") .setLabel("Bytes Received") .setDescription("Amount of data written to topic on this broker") .setNumerator(UnitConstants.bytes) .setDenominator(UnitConstants.second) .setCodahaleMetricType(CodahaleMetricTypes.CodahaleMetricType.METER) .setContext("BytesInPerSec") .build(); private static final CodahaleMetric BYTES_FETCHED_METRIC = new CodahaleMetric.Builder() .setName("bytes_fetched") .setLabel("Bytes Fetched") .setDescription("Amount of data consumers fetched from this topic on this broker") .setNumerator(UnitConstants.bytes) .setDenominator(UnitConstants.second) .setCodahaleMetricType(CodahaleMetricTypes.CodahaleMetricType.METER) .setContext("BytesOutPerSec") .build(); private static final CodahaleMetric BYTES_REJECTED_METRIC = new CodahaleMetric.Builder() .setName("bytes_rejected") .setLabel("Bytes Rejected") .setDescription("Amount of data in messages rejected by broker for this topic") .setNumerator(UnitConstants.bytes) .setDenominator(UnitConstants.second) .setCodahaleMetricType(CodahaleMetricTypes.CodahaleMetricType.METER) .setContext("BytesRejectedPerSec") .build(); private static final CodahaleMetric REJECTED_MESSAGE_BATCHES_METRIC = new CodahaleMetric.Builder() .setName("rejected_message_batches") .setLabel("Rejected Message Batches") .setDescription("Number of message batches sent by producers that the broker rejected for this topic") .setNumerator(UnitConstants.message_batches) .setDenominator(UnitConstants.second) .setCodahaleMetricType(CodahaleMetricTypes.CodahaleMetricType.METER) .setContext("FailedProduceRequestsPerSec") .build(); private static final CodahaleMetric FETCH_REQUEST_FAILURES_METRIC = new CodahaleMetric.Builder() .setName("fetch_request_failures") .setLabel("Fetch Request Failures") .setDescription("Number of data read requests from consumers that brokers failed to process for this topic") .setNumerator(UnitConstants.fetch_requests) .setDenominator(UnitConstants.second) .setCodahaleMetricType(CodahaleMetricTypes.CodahaleMetricType.METER) .setContext("FailedFetchRequestsPerSec") .build(); public static List<CodahaleMetric> getMetrics() { return Arrays.asList( MESSAGES_RECEIVED_METRIC, BYTES_RECEIVED_METRIC, BYTES_FETCHED_METRIC, BYTES_REJECTED_METRIC, REJECTED_MESSAGE_BATCHES_METRIC, FETCH_REQUEST_FAILURES_METRIC ); } }
47.513761
128
0.632168
baaf09662055623611acf363b4a6e732bf663a85
308
package org.siping.scaffold.service.platform.service; import org.siping.scaffold.platform.entity.SysRoleMenu; import com.baomidou.mybatisplus.service.IService; /** * <p> * 服务类 * </p> * * @author Siping * @since 2018-01-14 */ public interface ISysRoleMenuService extends IService<SysRoleMenu> { }
18.117647
68
0.737013
797fe833ccf10979c1111f96d5d86cd8b4ee40c3
1,253
class B { @Override public boolean equals(Object obj) { return obj != null; } @Override public int hashCode() { return super.hashCode(); } } class A extends B { Object[] a1; Object[][] a2; String[] a3; String[][] a4; int[] a5; int[][] a6; byte a7; short a8; int a9; long a10; float a11; double a12; Object a13; String a14; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final A a = (A) o; return new org.apache.commons.lang3.builder.EqualsBuilder().appendSuper(super.equals(o)).append(a7, a.a7).append(a8, a.a8).append(a9, a.a9).append(a10, a.a10).append(a11, a.a11).append(a12, a.a12).append(a1, a.a1).append(a2, a.a2).append(a3, a.a3).append(a4, a.a4).append(a5, a.a5).append(a6, a.a6).append(a13, a.a13).append(a14, a.a14).isEquals(); } @Override public int hashCode() { return new org.apache.commons.lang3.builder.HashCodeBuilder(17, 37).appendSuper(super.hashCode()).append(a1).append(a2).append(a3).append(a4).append(a5).append(a6).append(a7).append(a8).append(a9).append(a10).append(a11).append(a12).append(a13).append(a14).toHashCode(); } }
27.23913
356
0.628093
6092a5d917a3b5e9d88292f2e04ca0f5cf6107e4
299
package com.raysonxin.rpc.server; /** * @className: MethodArgumentConverter.java * @author: raysonxin * @date: 2020/2/15 5:51 下午 * @email: raysonxin@163.com * @description: TODO **/ public interface MethodArgumentConverter { ArgumentConvertOutput convert(ArgumentConvertInput input); }
19.933333
62
0.73913
74d9fcc99175b37b9ed9922657e068f65a428ee1
1,218
package kr.gooroom.gpms.common.service; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile; import java.util.List; public interface ExcelCommonService { /** * 업로드 된 엑셀 포맷에 맞는 workbook 객체 생성 * @param file * @return */ Workbook getWorkbook(MultipartFile file) throws Exception; /** * 셀 형식에 따른 값 String으로 변환 * @param cell * @return */ String getValue(Cell cell); /** * 일괄등록(조직, 사용자) 엑셀 파일 내용 읽기 * @param file * @return * @throws Exception */ List<List<String>> read(MultipartFile file, String fileType) throws Exception; /** * 조직, 사용자 리스트 엑셀파이로 출력 * @param list * @return */ XSSFWorkbook write(List<List<String>> list); /** * 조직코드 유효성 체크 * @param deptCd * @return */ boolean deptCdRegex(String deptCd); /** * 사용자 아이디 유효성 체크 * @param userId * @return */ boolean userIdRegex(String userId); /** * 이메일 형식 체크 * @param email * @return */ boolean emailRegex(String email); }
19.645161
82
0.599343
3c3054ab942491625d749f7fdc4e3732a69baafc
2,824
/* * Copyright (c) 2012 - 2018 Arvato Systems GmbH * * 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.arvatosystems.t9t.ssm.be.impl; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.arvatosystems.t9t.cfg.be.ConfigProvider; import de.jpaw.dp.Jdp; import de.jpaw.dp.Startup; import de.jpaw.dp.StartupShutdown; /** * This class is responsible for the life cycle of the scheduler. * It launches Quartz as the almost last service of the application. * As part of the shutdown sequence, it shuts down the scheduler service. */ @Startup(2000000012) public class QuartzLifecycle implements StartupShutdown { private static final Logger LOGGER = LoggerFactory.getLogger(QuartzLifecycle.class); private Scheduler scheduler = null; @Override public void onStartup() { final Boolean disableScheduler = ConfigProvider.getConfiguration().getDisableScheduler(); if (Boolean.TRUE.equals(disableScheduler)) { LOGGER.info("Configuration sets scheduler to disabled - not starting quartz"); return; } else { LOGGER.info("Starting quartz"); } StdSchedulerFactory quartzSchedulerFactory = new StdSchedulerFactory(); try { final IQuartzPropertyProvider propertyProvider = Jdp.getOptional(IQuartzPropertyProvider.class); if (propertyProvider != null) { quartzSchedulerFactory.initialize(propertyProvider.getProperties()); } scheduler = quartzSchedulerFactory.getScheduler(); Jdp.bindInstanceTo(scheduler, Scheduler.class); // scheduler.setJobFactory(myJdpJobFactory); // not required with Jdp? scheduler.start(); } catch (SchedulerException e) { LOGGER.error("Error creating Quartz scheduler.", e); } } @Override public void onShutdown() { if (scheduler == null) return; // scheduler was not started - don't try to shut it down try { scheduler.shutdown(true); } catch (SchedulerException e) { LOGGER.error("Error shutting down Quartz scheduler", e); } } }
35.746835
108
0.686615
968c40525df09cdc7ec54d8021fd40d10ea39f42
719
package org.smicon.rest.emberwiring.general.pools; import org.apache.commons.pool2.impl.AbandonedConfig; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.smicon.rest.emberwiring.general.factories.StringBuilderFactory; public class StringBuilderPool extends GenericObjectPool<StringBuilder> { public StringBuilderPool(GenericObjectPoolConfig config, AbandonedConfig abandonedConfig) { super(new StringBuilderFactory(), config, abandonedConfig); } public StringBuilderPool(GenericObjectPoolConfig config) { super(new StringBuilderFactory(), config); } public StringBuilderPool() { super(new StringBuilderFactory()); } }
24.793103
90
0.820584
c3aba48994071850e061dc0041fb7e8a14c9adbd
282
package com.example.minhquan.w2vinova.News.view; import com.example.minhquan.w2vinova.Model.Doc; import java.util.List; public interface ListNewsView { void showLoading(); void hideLoading(); void showListNews(List<Doc> docs); void showError(String error); }
16.588235
48
0.734043
04248893bbb78ab2b2561c89bcdfb09742057280
986
import java.io.Serializable; public class Request implements Serializable { /** * */ private static final long serialVersionUID = 1L; // Atributes private int objectID; private String method; private String type; private Place place; // Constructors public Request(Place place) { this.place = place; this.type = "new"; } public Request(int objectID, String method) { this.objectID = objectID; this.method = method; this.type = "invoke"; } public int getObjectID() { return objectID; } public void setObjectID(int objectID) { this.objectID = objectID; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Place getPlace() { return place; } public void setPlace(Place place) { this.place = place; } }
17
50
0.64503
9872fffbc2541404f64bfe8ed130adfa68263a84
4,880
/******************************************************************************* * Copyright (c) 七月 14 2016 @author <a href="mailto:iffiff1@gmail.com">Tyler Chen</a>. * All rights reserved. * * Contributors: * <a href="mailto:iffiff1@gmail.com">Tyler Chen</a> - initial API and implementation. * Auto Generate By foreveross.com Quick Deliver Platform. ******************************************************************************/ package com.foreveross.common.web; import com.foreveross.common.ConstantBean; import com.foreveross.common.ResultBean; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.iff.infra.util.Logger; import org.iff.infra.util.MapHelper; import org.iff.infra.util.StreamHelper; import org.iff.infra.util.StringHelper; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; /** * file upload download. * * @author <a href="mailto:iffiff1@gmail.com">Tyler Chen</a> * @since Aug 9, 2015 * auto generate by qdp. */ @Controller @RequestMapping("/file") public class FileController extends BaseController { @ResponseBody @RequestMapping(value = "/upload.do", method = RequestMethod.POST) public ResultBean upload(@RequestParam("file") MultipartFile upload, HttpServletRequest request, HttpServletResponse response) { String fileName = null; if (upload == null) { return ResultBean.error().setBody("Unable to upload. File is empty."); } try { String path = ConstantBean.getProperty("file.upload.dir", StringHelper.pathConcat(System.getProperty("java.io.tmpdir"), "/upload/")); File parent = new File(path); if (!parent.exists()) { parent.mkdirs(); } fileName = upload.getOriginalFilename(); String fileId = StringHelper.uuid(); { int indexOf = StringUtils.lastIndexOf(fileName, '.'); if (indexOf > -1) { fileName = fileName.substring(0, indexOf) + "-" + fileId + "." + fileName.substring(indexOf + 1); } } byte[] bytes = upload.getBytes(); BufferedOutputStream bos = null; FileOutputStream fos = null; try { File file = new File(parent, fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes); Logger.debug("file upload: " + file.getAbsolutePath()); return ResultBean.success().setBody(MapHelper.toMap("id", fileId, "fileName", fileName)); } finally { StreamHelper.closeWithoutError(fos); StreamHelper.closeWithoutError(bos); } } catch (Exception e) { return ResultBean.success() .setBody("You failed to upload " + upload.getOriginalFilename() + ": " + e.getMessage()); } } @ResponseBody @RequestMapping(value = "/remove.do", method = RequestMethod.POST) public ResultBean remove(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) { String fileName = null; try { //String id = request.getParameter("id"); fileName = request.getParameter("fileName"); if (StringUtils.isBlank(fileName)) { return ResultBean.error().setBody("Unable to remove upload: fileName is empty."); } String path = ConstantBean.getProperty("file.upload.dir", StringHelper.pathConcat(System.getProperty("java.io.tmpdir"), "/upload/")); File parent = new File(path); if (!parent.exists()) { parent.mkdirs(); } File file = new File(parent, fileName); FileUtils.deleteQuietly(file); Logger.debug("upload file removed: " + file.getAbsolutePath()); return ResultBean.success().setBody("success"); } catch (Exception e) { return ResultBean.success().setBody("You failed to remove upload file " + fileName + ": " + e.getMessage()); } } }
43.571429
121
0.593648
f8236d00b79f29a9aafc9b12789154e94a859f75
1,789
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.tasks.diagnostics.internal.graph; import org.gradle.internal.logging.text.StyledTextOutput; import static org.gradle.internal.logging.text.StyledTextOutput.Style.Info; public class LegendRenderer { private final StyledTextOutput output; private boolean hasCyclicDependencies; private boolean hasUnresolvableConfigurations; public LegendRenderer(StyledTextOutput output) { this.output = output; } public void printLegend() { if (hasCyclicDependencies) { output.println(); output.withStyle(Info).println("(*) - dependencies omitted (listed previously)"); } if (hasUnresolvableConfigurations) { output.println(); output.withStyle(Info).println("(n) - Not resolved (configuration is not meant to be resolved)"); } } public void setHasUnresolvableConfigurations(boolean hasUnresolvableConfigurations) { this.hasUnresolvableConfigurations = hasUnresolvableConfigurations; } public void setHasCyclicDependencies(boolean hasCyclicDependencies) { this.hasCyclicDependencies = hasCyclicDependencies; } }
35.078431
109
0.724427
168105d0f165f2b20b300f551b1a1503f78b5be9
677
package app.had.demo.out.adapter; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; import app.had.demo.domain.Taxi; import app.had.demo.out.port.GPSRepository; @Repository public class GPSRepositoryImpl implements GPSRepository{ @Override public List<Taxi> getTaxies(String pickUpAddress, String dropAddress) { List<Taxi> taxies = new ArrayList<>(); Taxi tx1 = new Taxi(); tx1.setTaxiId(101); taxies.add(tx1); Taxi tx2 = new Taxi(); tx2.setTaxiId(102); taxies.add(tx2); Taxi tx3 = new Taxi(); tx3.setTaxiId(103); taxies.add(tx3); return taxies; } }
19.911765
73
0.6839
435f2565f67adc1f0b68e0c9f06eaf65914358ae
1,097
package cursoemvideo.aula13.Exercic01; public class Cachorro { public void reagir(String frase) { if (frase == "Toma comida") { frase = "Olá"; System.out.println("Sem vergonha"); } else { System.out.println("Rosnar"); } } public void reagir(int min, int hora) { if (hora < 12) { System.out.println("Está feliz em me ver"); } else if (hora >= 18) System.out.println("Ignorar"); else System.out.println("Abanar e latir"); } public void reagir(boolean dono) { if (dono = true) { System.out.println("Sou dono desse vira lata"); } else { System.out.println("Ele vai me morder!!!!!!!!!"); } } public void reagir(int idade, float peso) { if (idade < 5) if (peso < 10) System.out.println("Abanar"); else System.out.println("latir"); if (peso < 10) System.out.println("Rosnar"); else System.out.println("Ignorar"); } }
25.511628
61
0.505014
140e2d03917d231250749ee80af052d9d4ae5023
5,636
/* * 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.jmeter.gui.util; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.LinkedList; import java.util.List; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.apache.jmeter.util.JMeterUtils; public class FilePanelEntry extends HorizontalPanel implements ActionListener { private static final long serialVersionUID = 280L; private static final Font FONT_DEFAULT = UIManager.getDefaults().getFont("TextField.font"); //$NON-NLS-1$ private static final Font FONT_SMALL = new Font("SansSerif", Font.PLAIN, (int) Math.round(FONT_DEFAULT.getSize() * 0.8)); //$NON-NLS-1$ private final JTextField filename = new JTextField(10); private final JLabel label; private final JButton browse = new JButton(JMeterUtils.getResString("browse")); //$NON-NLS-1$ private static final String ACTION_BROWSE = "browse"; //$NON-NLS-1$ private final List<ChangeListener> listeners = new LinkedList<>(); private final String[] filetypes; private boolean onlyDirectories = false; // Mainly needed for unit test Serialisable tests public FilePanelEntry() { this(JMeterUtils.getResString("file_visualizer_filename")); //$NON-NLS-1$ } public FilePanelEntry(String label) { this(label, (ChangeListener) null); } public FilePanelEntry(String label, String ... exts) { this(label, (ChangeListener) null, exts); } public FilePanelEntry(String label, boolean onlyDirectories, String ... exts) { this(label, onlyDirectories, (ChangeListener) null, exts); } public FilePanelEntry(String label, ChangeListener listener, String ... exts) { this(label, false, listener, exts); } public FilePanelEntry(String label, boolean onlyDirectories, ChangeListener listener, String ... exts) { this.label = new JLabel(label); if (listener != null) { listeners.add(listener); } if (exts != null && !(exts.length == 1 && exts[0] == null) // String null is converted to String[]{null} ) { this.filetypes = new String[exts.length]; System.arraycopy(exts, 0, this.filetypes, 0, exts.length); } else { this.filetypes = null; } this.onlyDirectories=onlyDirectories; init(); } public final void addChangeListener(ChangeListener l) { listeners.add(l); } private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final) add(label); add(filename); filename.addActionListener(this); browse.setFont(FONT_SMALL); add(browse); browse.setActionCommand(ACTION_BROWSE); browse.addActionListener(this); } public void clearGui(){ filename.setText(""); // $NON-NLS-1$ } /** * If the gui needs to enable/disable the FilePanel, call the method. * * @param enable The Flag whether the {@link FilePanel} should be enabled */ public void enableFile(boolean enable) { browse.setEnabled(enable); filename.setEnabled(enable); } /** * Gets the filename attribute of the FilePanel object. * * @return the filename value */ public String getFilename() { return filename.getText(); } /** * Sets the filename attribute of the FilePanel object. * * @param f * the new filename value */ public void setFilename(String f) { filename.setText(f); } private void fireFileChanged() { for (ChangeListener cl : listeners) { cl.stateChanged(new ChangeEvent(this)); } } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(ACTION_BROWSE)) { JFileChooser chooser; if(filetypes == null || filetypes.length == 0){ chooser = FileDialoger.promptToOpenFile(filename.getText(),onlyDirectories); } else { chooser = FileDialoger.promptToOpenFile(filetypes, filename.getText(),onlyDirectories); } if (chooser != null && chooser.getSelectedFile() != null) { filename.setText(chooser.getSelectedFile().getPath()); fireFileChanged(); } } else { fireFileChanged(); } } }
33.547619
140
0.63396
f4860a4b1333a4198ea40c785d46c513c136ab49
740
package com.demo.spring.po; public class Car { private String brand; private String corp; private int maxSpeed; public Car() { } public Car(String brand, String corp) { this.brand = brand; this.corp = corp; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getCorp() { return corp; } public void setCorp(String corp) { this.corp = corp; } public int getMaxSpeed() { return maxSpeed; } public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } @Override public String toString() { return "Car [brand=" + brand + ", corp=" + corp + ", maxSpeed=" + maxSpeed + "]"; } }
17.619048
66
0.612162
a70e4de30b0bd2519779e10c84316e8fe24197af
5,756
/* * CategoryTests.java * Created by: Scott A. Roehrig * Created on: Jul 9, 2016 */ package org.apache.bazaar; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** * CategoryTests provides JUnit tests for {@link Category}. */ public final class CategoryTests { // declare members // declare constructors /** * Constructor for CategoryTests */ public CategoryTests() { super(); } // declare methods /** * Test for {@link Category#getParent()} */ @Test public void testGetParent() { try { final BazaarManager manager = BazaarManager.newInstance(); final Category parent = manager.findRootCategory(); final Category category = manager.newCategory(); category.setName("testGetParent"); category.setDescription("testGetParent"); category.setParent(parent); category.persist(); Assert.assertNotNull(category.getParent()); Assert.assertEquals(category.getParent().getIdentifier(), manager.findRootCategory().getIdentifier()); } catch (final BazaarException exception) { exception.printStackTrace(System.err); Assert.fail(exception.getLocalizedMessage()); } } /** * Test for {@link Category#getChildren()} */ @Test public void testGetChildren() { try { final BazaarManager manager = BazaarManager.newInstance(); final Category category = manager.newCategory("testGetChildren", "testGetChildren", manager.findRootCategory()); final Category category1 = manager.newCategory("testGetChildren", "testGetChildren", manager.findRootCategory()); category.persist(); final Set<Category> children = manager.findRootCategory().getChildren(); Assert.assertNotNull(children); Assert.assertTrue(!children.isEmpty()); Assert.assertTrue(children.contains(category)); Assert.assertTrue(children.contains(category1)); final Category category2 = manager.newCategory("testGetChildren", "testGetChildren", category1); category1.persist(); Assert.assertNotNull(category1.getChildren()); Assert.assertTrue(!category1.getChildren().isEmpty()); Assert.assertTrue(category1.getChildren().contains(category2)); Assert.assertTrue(!manager.findRootCategory().getChildren().contains(category2)); category.delete(); Assert.assertTrue(!manager.findRootCategory().getChildren().contains(category)); Assert.assertTrue(manager.findRootCategory().getChildren().contains(category1)); } catch (final BazaarException exception) { exception.printStackTrace(System.err); Assert.fail(exception.getLocalizedMessage()); } } /** * Test for {@link Category#persist()} */ @Test public void testPersist() { try { final BazaarManager manager = BazaarManager.newInstance(); final Category parent = manager.findRootCategory(); Category category = manager.newCategory(); category.setName("testPersist"); category.setDescription("testPersist"); category.setParent(parent); category.persist(); category = manager.findCategory(category.getIdentifier()); Assert.assertNotNull(category); Assert.assertEquals(category.getName(), "testPersist"); final Category category1 = manager.newCategory(); category1.setName("testPersist"); category1.setDescription("testPersist"); category1.setParent(category); final Category category2 = manager.newCategory(); category2.setName("testPersist"); category2.setDescription("testPersist"); category2.setParent(category1); // persist child should fail because parent has // not been persisted boolean failed = false; try { category2.persist(); } catch (final BazaarException exception) { failed = true; Assert.assertEquals(CategoryNotFoundException.class, exception.getClass()); } Assert.assertTrue(failed); // persist parent category1.persist(); // verify child has been persisted // this currently fails because we are not // able to retrieve the child structure via // json at the rest service // manager.findCategory(category2.getIdentifier()); } catch (final BazaarException exception) { exception.printStackTrace(System.err); Assert.fail(exception.getLocalizedMessage()); } } /** * Test for {@link Category#delete} */ @Test public void testDelete() { try { final BazaarManager manager = BazaarManager.newInstance(); final Category parent = manager.findRootCategory(); final Category category = manager.newCategory("testDelete", "testDelete", parent); category.persist(); category.delete(); boolean failed = false; try { manager.findCategory(category.getIdentifier()); } catch (final CategoryNotFoundException exception) { failed = true; Assert.assertNotNull(exception); } Assert.assertTrue(failed); // test cascade child delete final Category category1 = manager.newCategory("testDelete", "testDelete", parent); final Category category2 = manager.newCategory("testDelete", "testDelete", category1); category1.persist(); // should find category2 // currently this fails because we haven't // reconstructed the category1 child to // the server side for persistence // manager.findCategory(category2.getIdentifier()); // delete parent category1.delete(); try { // child should be gone manager.findCategory(category2.getIdentifier()); } catch (final CategoryNotFoundException exception) { Assert.assertNotNull(exception); } } catch (final BazaarException exception) { exception.printStackTrace(System.err); Assert.fail(exception.getLocalizedMessage()); } } }
31.626374
106
0.700139
ac55ecacfed3b70cdf4df7a716198df6fb46cf0b
1,813
package org.apache.shiro.biz.utils.uid; import java.sql.Timestamp; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * <b>高并发场景下System.currentTimeMillis()的性能问题的优化</b> * <pre> * System.currentTimeMillis()的调用比new一个普通对象要耗时的多(具体耗时高出多少我还没测试过,有人说是100倍左右) * System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道 * 后台定时更新时钟,JVM退出时,线程自动回收 * 10亿:43410,206,210.72815533980582% * 1亿:4699,29,162.0344827586207% * 1000万:480,12,40.0% * 100万:50,10,5.0%</pre> * @author lry http://git.oschina.net/yu120/sequence */ public class SystemClock { private final long period; private final AtomicLong now; private SystemClock(long period) { this.period = period; this.now = new AtomicLong(System.currentTimeMillis()); scheduleClockUpdating(); } private static class InstanceHolder { public static final SystemClock INSTANCE = new SystemClock(1); } private static SystemClock instance() { return InstanceHolder.INSTANCE; } private void scheduleClockUpdating() { ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { now.set(System.currentTimeMillis()); } }, period, period, TimeUnit.MILLISECONDS); } private long currentTimeMillis() { return now.get(); } public static long now() { return instance().currentTimeMillis(); } public static String nowDate() { return new Timestamp(instance().currentTimeMillis()).toString(); } }
28.777778
81
0.668505
c073d7c958dc65d8399dd7a2fec66daf693a2372
5,546
/* * jGnash, a personal finance application * Copyright (C) 2001-2018 Craig Cavanaugh * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jgnash.ui.register.table; import java.awt.EventQueue; import java.math.BigDecimal; import java.util.Arrays; import jgnash.engine.Account; import jgnash.engine.Comparators; import jgnash.engine.Transaction; import jgnash.engine.message.Message; import jgnash.engine.message.MessageProperty; /** * Sorts the account transactions. * * @author Craig Cavanaugh * */ public class SortedInvestmentTableModel extends InvestmentRegisterTableModel implements SortableTableModel { private Transaction transactions[] = new Transaction[0]; private int sortColumn = 0; private boolean ascending = true; private boolean[] sortedColumnMap; private boolean[] sortColumns; private final Object mutex = new Object(); public SortedInvestmentTableModel(Account account) { super(account); getTransactions(); } /** * @see jgnash.ui.register.table.SortableTableModel#isSortable(int) */ @Override public boolean isSortable(int col) { return sortedColumnMap[col]; } private static boolean[] getSortableColumns() { return new boolean[] { true, true, true, false, false, false, false }; } /** * Overrides the super to build the sort column map * * @see jgnash.ui.register.table.AbstractRegisterTableModel#buildColumnMap() */ @Override protected void buildColumnMap() { super.buildColumnMap(); if (sortColumns == null) { sortColumns = getSortableColumns(); } sortedColumnMap = new boolean[getColumnCount()]; int index = 0; for (int i = 0; i < columnVisible.length; i++) { if (columnVisible[i]) { sortedColumnMap[index] = sortColumns[i]; index++; } } } /** * Creates a private clone of the account's transactions */ private void getTransactions() { synchronized (mutex) { int size = account.getTransactionCount(); transactions = new Transaction[size]; for (int i = 0; i < size; i++) { transactions[i] = account.getTransactionAt(i); } sortColumn(sortColumn, ascending); } } @Override public int getRowCount() { synchronized (mutex) { return transactions.length; } } @Override public Transaction getTransactionAt(int index) { synchronized (mutex) { if (ascending) { return transactions[index]; } return transactions[transactions.length - index - 1]; } } /** * Get the account balance up to a specified index. * * @param index the balance of this account at the specified index. * @return the balance of the account at the specified index. */ @Override public BigDecimal getBalanceAt(int index) { BigDecimal balance = BigDecimal.ZERO; synchronized (mutex) { for (int i = 0; i <= index; i++) { balance = balance.add(getTransactionAt(i).getAmount(account)); } } return balance; } @Override public void messagePosted(final Message event) { if (event.getObject(MessageProperty.ACCOUNT) == account) { EventQueue.invokeLater(() -> { switch (event.getEvent()) { case TRANSACTION_ADD: case TRANSACTION_REMOVE: getTransactions(); break; default: // ignore any other messages that don't matter break; } }); } super.messagePosted(event); // this will fire the update } @Override public boolean getAscending() { return ascending; } @Override public int getSortedColumn() { return sortColumn; } // private static String[] cNames = {"Date", "Action", "Investment", "C", "Quantity", "Price", "Total"}; @Override public void sortColumn(final int col, final boolean ascending1) { this.ascending = ascending1; this.sortColumn = col; switch (getColumnMapping(col)) { case 0: Arrays.sort(transactions, Comparators.getTransactionByDate()); break; case 1: Arrays.sort(transactions, Comparators.getTransactionByType()); break; case 2: Arrays.sort(transactions, Comparators.getTransactionBySecurity()); break; default: Arrays.sort(transactions, Comparators.getTransactionByDate()); break; } fireTableDataChanged(); } }
29.657754
108
0.601515
efaf8ae14d4fac9682e7f39aace6d698b3320324
1,347
/** * Copyright (c) 2013-2022 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.core.store.callback; import org.locationtech.geowave.core.store.entities.GeoWaveRow; /** * This interface provides a callback mechanism when scanning entries * * @param <T> A generic type for ingested entries */ public interface ScanCallback<T, R extends GeoWaveRow> { /** * This will be called after an entry is successfully scanned with the row IDs that were used. * Deduplication, if performed, occurs prior to calling this method. * * <p> Without or without de-duplication, row ids are not consolidate, thus each entry only * contains one row id. If the entry is not de-dupped, then the entry this method is called for * each duplicate, each with a different row id. * * @param entry the entry that was ingested * @param row the raw row scanned from the table for this entry */ public void entryScanned(final T entry, final R row); }
42.09375
100
0.74833
f481b445453972c4048127b1edd70ad9b5237504
482
public class RaggedArrays { public static void main(String[] args) { int[][] ragged = new int[4][]; ragged[0] = new int[3]; // Row 0 has 3 columns ragged[1] = new int[4]; // Row 1 has 4 columns ragged[2] = new int[5]; // Row 2 has 5 columns ragged[3] = new int[6]; // Row 3 has 6 columns for(int i = 0; i < ragged.length; i++) { System.out.println("The number of columns in the row " + i + " is " + ragged[i].length); } } }
22.952381
91
0.549793
92403e90d9b5c8b139433c3d3f6d5159a805b1d5
1,489
package generated.zcsclient.account; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for distributionListSubscribeStatus. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="distributionListSubscribeStatus"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="subscribed"/> * &lt;enumeration value="unsubscribed"/> * &lt;enumeration value="awaiting_approval"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "distributionListSubscribeStatus") @XmlEnum public enum testDistributionListSubscribeStatus { @XmlEnumValue("subscribed") SUBSCRIBED("subscribed"), @XmlEnumValue("unsubscribed") UNSUBSCRIBED("unsubscribed"), @XmlEnumValue("awaiting_approval") AWAITING___APPROVAL("awaiting_approval"); private final String value; testDistributionListSubscribeStatus(String v) { value = v; } public String value() { return value; } public static testDistributionListSubscribeStatus fromValue(String v) { for (testDistributionListSubscribeStatus c: testDistributionListSubscribeStatus.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
27.072727
99
0.691739
09bb6d8368747871c9e28860d0ddd691ff7910da
2,097
package seedu.address.model.tag; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.testutil.Assert.assertThrows; import org.junit.jupiter.api.Test; public class TagTest { @Test public void constructor_null_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> new Tag(null)); } @Test public void constructor_invalidTagName_throwsIllegalArgumentException() { String invalidTagName1 = ""; String invalidTagName2 = "q"; String invalidTagName3 = "a-"; String invalidTagName4 = "-b"; String invalidTagName5 = "c_"; String invalidTagName6 = "_d"; assertThrows(IllegalArgumentException.class, () -> new Tag(invalidTagName1)); assertThrows(IllegalArgumentException.class, () -> new Tag(invalidTagName2)); assertThrows(IllegalArgumentException.class, () -> new Tag(invalidTagName3)); assertThrows(IllegalArgumentException.class, () -> new Tag(invalidTagName4)); assertThrows(IllegalArgumentException.class, () -> new Tag(invalidTagName5)); assertThrows(IllegalArgumentException.class, () -> new Tag(invalidTagName6)); } @Test public void isValidTagName() { // null tag name assertThrows(NullPointerException.class, () -> Tag.isValidTagName(null)); assertTrue(Tag.isValidTagName("ma")); assertTrue(Tag.isValidTagName("Ma")); assertTrue(Tag.isValidTagName("MA")); assertTrue(Tag.isValidTagName("a-b")); assertTrue(Tag.isValidTagName("a_b")); assertTrue(Tag.isValidTagName("apple")); assertFalse(Tag.isValidTagName("a")); assertFalse(Tag.isValidTagName("B")); assertFalse(Tag.isValidTagName("abcd_")); assertFalse(Tag.isValidTagName("_abcd")); assertFalse(Tag.isValidTagName("-abcd")); assertFalse(Tag.isValidTagName("abcd-")); assertFalse(Tag.isValidTagName("-_-")); assertFalse(Tag.isValidTagName("_-_")); } }
38.833333
85
0.680019
6d95c8fd807200562a1b30aa1351d786ba9843e9
2,833
package ch.so.agi.gretl.jobs; import ch.so.agi.gretl.util.GradleVariable; import ch.so.agi.gretl.util.TestUtil; import ch.so.agi.gretl.util.TestUtilSql; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; public class SqlExecutorTaskTest { /* Test's that a chain of statements executes properly 1. statement: fill the source table with rows 2. statement: execute the "insert into select from" statement */ @Test public void taskChainTest() throws Exception { String schemaName = "sqlExecuterTaskChain".toLowerCase(); Connection con = null; try{ con = TestUtilSql.connectPG(); TestUtilSql.createOrReplaceSchema(con, schemaName); TestUtilSql.createSqlExecuterTaskChainTables(con, schemaName); con.commit(); TestUtilSql.closeCon(con); GradleVariable[] gvs = {GradleVariable.newGradleProperty(TestUtilSql.VARNAME_PG_CON_URI, TestUtilSql.PG_CON_URI)}; TestUtil.runJob("jobs/sqlExecutorTaskChain", gvs); //reconnect to check results con = TestUtilSql.connectPG(); String countSrcSql = String.format("select count(*) from %s.albums_src", schemaName); String countDestSql = String.format("select count(*) from %s.albums_dest", schemaName); int countSrc = TestUtilSql.execCountQuery(con, countSrcSql); int countDest = TestUtilSql.execCountQuery(con, countDestSql); Assert.assertEquals("Rowcount in destination table must be equal to rowcount in source table", countSrc, countDest); Assert.assertTrue("Rowcount in destination table must be greater than zero", countDest > 0); } finally { TestUtilSql.closeCon(con); } } /** * Test's if the sql-files can be configured using a relative path. * * The relative path relates to the location of the build.gradle file * of the corresponding gretl job. */ @Test public void relPathTest() throws Exception { String schemaName = "sqlExecuterRelPath".toLowerCase(); Connection con = null; try{ con = TestUtilSql.connectPG(); TestUtilSql.createOrReplaceSchema(con, schemaName); TestUtilSql.createSqlExecuterTaskChainTables(con, schemaName); con.commit(); TestUtilSql.closeCon(con); GradleVariable[] gvs = {GradleVariable.newGradleProperty(TestUtilSql.VARNAME_PG_CON_URI, TestUtilSql.PG_CON_URI)}; TestUtil.runJob("jobs/sqlExecutorTaskRelPath", gvs); } finally { TestUtilSql.closeCon(con); } } }
35.860759
128
0.663607
50f261a80f2bc1e8ba7c500eb154c81d4b0e919b
506
package com.NewsBrowser.Server.Service.Interfaces; /** * Represents validation of user input. * @author MJazy * */ public interface UserInputValidatorInterface { /** * Validates user input. * @param country represents country to which news should be related (e.g. Poland). * @param category represents category to which news should be related (e.g. Technology). * @return true if input is relevant, false in other scenario. */ boolean isInputValid(String country, String category); }
25.3
91
0.733202
881fa20f2066bf0154ec3b51e066e7f82c3af58a
641
package com.rifledluffy.chairs.command.commands; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; public abstract class SubCommand { /* /<command> <subcommand> args[0] args[1] */ public SubCommand() {} public abstract void onCommand(CommandSender sender, String[] args); public abstract void onCommand(ConsoleCommandSender sender, String[] args); public abstract void onCommand(Player player, String[] args); public abstract String name(); public abstract String info(); public abstract String[] aliases(); }
23.740741
79
0.719189
35bfc31bc2af55fbdb09a700bb624b7dc1bdea61
470
package com.chaitali._2structureofjavaapplication; public class SwitchStatement { public static void main(String[] args) { char grade = 'C'; switch(grade) { case 'A' : System.out.println("A grade"); break; case 'B' : System.out.println("B grade"); break; case 'C' : System.out.println("C grade"); break; case 'D' : System.out.println("pass"); break; default : System.out.println("Fail"); } } }
14.242424
50
0.587234