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
568586a345266d80dd5c2c87b07ff790e3499f2f
1,913
/* * Copyright (c) 2008-2012, Hazel Bilisim Ltd. 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.hazelcast.client; import com.hazelcast.core.Instance; import com.hazelcast.impl.base.Values; import java.util.Iterator; import java.util.Map; public class MultiMapEntryIterator extends MapEntryIterator { private volatile Iterator currentValueIterator; private volatile Object lastKey; protected volatile Map.Entry lastMultiMapEntry; public MultiMapEntryIterator(Iterator it, EntryHolder proxy, Instance.InstanceType instanceType) { super(it, proxy, instanceType); } public boolean hasNext() { if (currentValueIterator == null) { return it.hasNext(); } return currentValueIterator.hasNext() || it.hasNext(); } public Map.Entry next() { if (currentValueIterator == null || !currentValueIterator.hasNext()) { lastKey = it.next(); Values value = (Values) proxy.get(lastKey); if (value == null) { return next(); } currentValueIterator = value.iterator(); } if (currentValueIterator == null || !currentValueIterator.hasNext()) { return next(); } lastMultiMapEntry = new MapEntry(lastKey, currentValueIterator.next(), proxy); return lastMultiMapEntry; } }
33.561404
102
0.675379
c572d278ece36869e754e1e659f76a0b630284e4
3,953
package ch.epfl.imhof.painting; /** * ** Une couleur représentée par ses composantes rouges, vertes et bleues. * * @author Pierre Gabioud (247216) * @author Corto Callerisa (251769) * */ public final class Color { private final double r, g, b; /** * La couleur « rouge » (pur). */ public final static Color RED = new Color(1, 0, 0); /** * La couleur « vert » (pur). */ public final static Color GREEN = new Color(0, 1, 0); /** * La couleur « bleu » (pur). */ public final static Color BLUE = new Color(0, 0, 1); /** * La couleur « noir ». */ public final static Color BLACK = new Color(0, 0, 0); /** * La couleur « blanc ». */ public final static Color WHITE = new Color(1, 1, 1); /** * @param g * l'intensité du gris dans l'intervalle [0;1]. * @return le gris créé */ public static Color gray(double g) { if (!(0.0 <= g && g <= 1.0)) throw new IllegalArgumentException("invalid grey: " + g); return new Color(g, g, g); } // throws IllegalArgumentException // si l'une des composantes est hors de l'intervalle [0;1]. private Color(double r, double g, double b) { if (!(0.0 <= r && r <= 1.0)) throw new IllegalArgumentException("invalid red component: " + r); if (!(0.0 <= g && g <= 1.0)) throw new IllegalArgumentException("invalid green component: " + g); if (!(0.0 <= b && b <= 1.0)) throw new IllegalArgumentException("invalid blue component: " + b); this.r = r; this.g = g; this.b = b; } /** * Construit une couleur avec les composantes rouges, vertes et bleues * données, qui doivent être dans l'intervalle [0;1]. * * @param r * la composante rouge. * @param g * la composante verte. * @param b * la composante bleue. */ public static Color rgb(double r, double g, double b) { return new Color(r, g, b); } /** * Dépaquete un entier 24 bit et construit une couleur avec les composantes * rouges, vertes et bleues données, qui doivent être dans l'intervalle * [0;1]. * * @param rgb entier 24 bit comportant les composants de la couleur * @return la couleur correspondant à l'entier dépaqueté */ public static Color rgb(int rgb) { double r = ((rgb >> 16) & 0xFF)/255d; double g = ((rgb >> 8) & 0xFF)/255d; double b = (rgb & 0xFF)/255d; return new Color(r, g, b); } /** * Retourne la composante rouge de la couleur, comprise entre 0 et 1. * * @return la composante rouge de la couleur. */ public double r() { return r; } /** * Retourne la composante verte de la couleur, comprise entre 0 et 1. * * @return la composante verte de la couleur. */ public double g() { return g; } /** * Retourne la composante bleue de la couleur, comprise entre 0 et 1. * * @return la composante bleue de la couleur. */ public double b() { return b; } /** * multiplie deux couleurs entre elles, par multiplication des composantes individuelles. * * @param that la couleur externe multipliée * @return la couleur issue du produit de la couleur actuelle et de celle passée en argument */ public Color multiplyWith(Color that) { return new Color(r * that.r, g * that.g, b * that.b); } /** * Convertit la couleur en une couleur AWT. * * @return La couleur AWT correspondant à la couleur réceptrice. */ /** * @return une couleur AWT à partir d'une couleur de la classe Color */ public java.awt.Color toAWTColor() { return new java.awt.Color((float) r, (float) g, (float) b); } }
26.891156
96
0.558563
d646a5b76c7ff3b71ec4b5d5f63d5cb19622d95b
103
package jMapGen.com.nodename.Delaunay; import jMapGen.Point; interface ICoord { Point getCoord(); }
11.444444
38
0.76699
890cb4a62c85282f3cafbd22845d86ee96befde4
284
package com.scm.dao.inventory; import com.scm.dao.common.GenericDao; import com.scm.dao.domain.CededSupplier; public interface CededSupplierDao extends GenericDao<CededSupplier, Long>{ public CededSupplier getCededSupplierDetails(Long supplierId) throws Throwable; }
25.818182
81
0.795775
b3a316216a39531bd5305330e1a32237bf057362
2,224
/** * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lambkit.web.websocket; import org.apache.mina.util.CopyOnWriteMap; public class WebSocketService { public static final WebSocketService bo = new WebSocketService(); //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 //private static CopyOnWriteArraySet<WebSocketController> webSocketSet = new CopyOnWriteArraySet<WebSocketController>(); private final CopyOnWriteMap<String, IWebSocketMsg> members = new CopyOnWriteMap<String, IWebSocketMsg>(100); private WebSocketService() { } public void add(String sessionid, IWebSocketMsg wsm) { members.put(sessionid, wsm); } public void close(String sessionid, IWebSocketMsg wsm, String msg) { members.remove(sessionid); //members.remove(wsm); } public void receive(String sessionid, IWebSocketMsg wsm, String data) { wsm.receive(data); } public void send(String msg) { for (IWebSocketMsg wsm : members.values()) { wsm.send(msg); } } public void send(String sessionid, String msg) { IWebSocketMsg wsm = members.get(sessionid); if(wsm!=null) wsm.send(msg); else System.out.println("当前session.id无连接!"); } public static synchronized int getOnlineCount() { return bo.members.size();//onlineCount; } public static synchronized void addOnlineCount() { WebSocketService.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketService.onlineCount--; } }
32.231884
125
0.718975
a8628ac52773e5120b4600ac7d527735fdca4b73
936
/* * Copyright 2013 Guidewire Software, Inc. */ package gw.internal.xml.xsd.typeprovider.schema; import gw.internal.xml.xsd.typeprovider.XmlSchemaIndex; import gw.lang.reflect.LocationInfo; import java.util.Map; public final class XmlSchemaEnumerationFacet extends XmlSchemaFacet<XmlSchemaEnumerationFacet> { private final Map<String, String> _namespaceContext; public XmlSchemaEnumerationFacet( XmlSchemaIndex schemaIndex, LocationInfo locationInfo, String value, Map<String,String> namespaceContext ) { super( schemaIndex, locationInfo, value ); _namespaceContext = namespaceContext; } public Map<String,String> getNamespaceContext() { return _namespaceContext; } @Override protected XmlSchemaEnumerationFacet copy( XmlSchemaIndex schemaIndex ) throws UnsupportedOperationException { return new XmlSchemaEnumerationFacet( schemaIndex, getLocationInfo(), getValue(), _namespaceContext ); } }
30.193548
144
0.793803
bae064fedf59a2d840d59ba7c625f2b7adbfbeb5
1,493
package me.acablade.ultimatebans; import me.acablade.ultimatebans.commands.*; import me.acablade.ultimatebans.data.MuteConfiguration; import me.acablade.ultimatebans.listeners.ChatListener; import me.acablade.ultimatebans.listeners.InventoryListener; import me.acablade.ultimatebans.listeners.JoinListener; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.io.IOException; public final class UltimateBans extends JavaPlugin { private static UltimateBans instance; public static UltimateBans getInstance(){ return instance; } @Override public void onEnable() { getCommand("ban").setExecutor(new BanCommand()); getCommand("tempban").setExecutor(new TempBanCommand()); getCommand("baninfo").setExecutor(new BanInfoCommand()); getCommand("mute").setExecutor(new MuteCommand()); getCommand("unmute").setExecutor(new UnmuteCommand()); getCommand("tempmute").setExecutor(new TempMuteCommand()); Bukkit.getPluginManager().registerEvents(new JoinListener(), this); Bukkit.getPluginManager().registerEvents(new InventoryListener(), this); Bukkit.getPluginManager().registerEvents(new ChatListener(), this); instance = this; try { MuteConfiguration.createCustomConfig(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onDisable() { // Plugin shutdown logic } }
33.177778
80
0.705291
6b1a2517f0777e435885e8964abc8bb100495ae4
785
package com.viktor.e_commerce; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; public class BaseActivity extends AppCompatActivity { public static int userId = 0; public static int storeId = 0; // public static final String ROOT = "http://172.23.175.252:9000/api/"; public static final String ROOT = "http://www.mallproject.cn:8000/api/"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityCollector.addActivity(this); } @Override protected void onDestroy() { super.onDestroy(); ActivityCollector.removeActivity(this); } }
26.166667
76
0.718471
6b4a50a1cd9a2d3fc9c9dfee49c62f71927628f5
3,572
package teamcode.demo; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.hardware.*; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit; /** * Example OpMode. Demonstrates use of gyro, color sensor, encoders, and telemetry. * */ @TeleOp(name = "two wheel demo linear", group = "TwoWheel") public class TwoWheelDemoLinear extends LinearOpMode { public void runOpMode() { DcMotorEx left = (DcMotorEx)hardwareMap.dcMotor.get("left_motor"); DcMotorEx right = (DcMotorEx)hardwareMap.dcMotor.get("right_motor"); left.setDirection(DcMotor.Direction.REVERSE); GyroSensor gyro = hardwareMap.gyroSensor.get("gyro_sensor"); Servo backServo = hardwareMap.servo.get("back_servo"); gyro.init(); ColorSensor colorSensor = hardwareMap.colorSensor.get("color_sensor"); DistanceSensor frontDistance = hardwareMap.get(DistanceSensor.class, "front_distance"); DistanceSensor leftDistance = hardwareMap.get(DistanceSensor.class, "left_distance"); DistanceSensor backDistance = hardwareMap.get(DistanceSensor.class, "back_distance"); DistanceSensor rightDistance = hardwareMap.get(DistanceSensor.class, "right_distance"); telemetry.addData("Press Start to Continue",""); telemetry.update(); waitForStart(); while (opModeIsActive()){ if (gamepad1.a){ telemetry.addData("a pressed",""); left.setPower(-.5); right.setPower(-.5); } else if (gamepad1.y) { telemetry.addData("y pressed", ""); left.setVelocity(401.8, AngleUnit.DEGREES); right.setVelocity(401.8, AngleUnit.DEGREES); } else if (gamepad1.b){ telemetry.addData("b pressed", ""); left.setPower(0.5); right.setPower(-0.5); } else if (gamepad1.x){ telemetry.addData("x pressed", ""); left.setPower(-0.5); right.setPower(0.5); } else { left.setPower(0); right.setPower(0); } backServo.setPosition(0.5 - 0.5* gamepad1.left_stick_y); telemetry.addData("Press", "Y-fwd, A-rev, B-Rt, X-Lt"); telemetry.addData("Left Gamepad stick controls back servo",""); telemetry.addData("Color","R %d G %d B %d", colorSensor.red(), colorSensor.green(), colorSensor.blue()); telemetry.addData("Heading"," %.1f", gyro.getHeading()); telemetry.addData("Encoders","Left %d Right %d", left.getCurrentPosition(), right.getCurrentPosition()); telemetry.addData("Vel, TPS", "Left %.0f Right %.0f", left.getVelocity(), right.getVelocity()); telemetry.addData("Vel, DPS", "Left %.1f Right %.1f", left.getVelocity(AngleUnit.DEGREES), right.getVelocity(AngleUnit.DEGREES)); telemetry.addData("Distance", " Fr %.1f Lt %.1f Rt %.1f Bk %.1f ", frontDistance.getDistance(DistanceUnit.CM), leftDistance.getDistance(DistanceUnit.CM), rightDistance.getDistance(DistanceUnit.CM), backDistance.getDistance(DistanceUnit.CM) ); telemetry.update(); } left.setPower(0); right.setPower(0); } }
48.27027
142
0.62542
ee02e63e961dce0738b9f5aaf6953f4f462c4753
3,100
package io.lbry.browser.tasks.lbryinc; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.AsyncTask; import java.util.HashMap; import java.util.Map; import io.lbry.browser.MainActivity; import io.lbry.browser.data.DatabaseHelper; import io.lbry.browser.exceptions.LbryioRequestException; import io.lbry.browser.exceptions.LbryioResponseException; import io.lbry.browser.model.lbryinc.Subscription; import io.lbry.browser.utils.Helper; import io.lbry.browser.utils.Lbryio; public class ChannelSubscribeTask extends AsyncTask<Void, Void, Boolean> { private Context context; private String channelClaimId; private Subscription subscription; private ChannelSubscribeHandler handler; private Exception error; private boolean isUnsubscribing; public ChannelSubscribeTask(Context context, String channelClaimId, Subscription subscription, boolean isUnsubscribing, ChannelSubscribeHandler handler) { this.context = context; this.channelClaimId = channelClaimId; this.subscription = subscription; this.handler = handler; this.isUnsubscribing = isUnsubscribing; } protected Boolean doInBackground(Void... params) { SQLiteDatabase db = null; try { // Save to (or delete from) local store if (context instanceof MainActivity) { db = ((MainActivity) context).getDbHelper().getWritableDatabase(); } if (db != null) { if (!isUnsubscribing) { DatabaseHelper.createOrUpdateSubscription(subscription, db); } else { DatabaseHelper.deleteSubscription(subscription, db); } } // Save with Lbryio Map<String, String> options = new HashMap<>(); options.put("claim_id", channelClaimId); if (!isUnsubscribing) { options.put("channel_name", subscription.getChannelName()); options.put("notifications_disabled", String.valueOf(subscription.isNotificationsDisabled()).toLowerCase()); } String action = isUnsubscribing ? "delete" : "new"; Object response = Lbryio.parseResponse(Lbryio.call("subscription", action, options, context)); if (!isUnsubscribing) { Lbryio.addSubscription(subscription); } else { Lbryio.removeSubscription(subscription); } } catch (LbryioRequestException | LbryioResponseException | SQLiteException ex) { error = ex; return false; } return true; } protected void onPostExecute(Boolean success) { if (handler != null) { if (success) { handler.onSuccess(); } else { handler.onError(error); } } } public interface ChannelSubscribeHandler { void onSuccess(); void onError(Exception exception); } }
36.046512
158
0.640323
843e2c3892bff2f1eb411ab066cc21314dc5482a
507
package io.renren.modules.cbs.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import io.renren.modules.cbs.entity.CbsImgPurchaseInvoiceEntity; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * 出口发票附件图片表 * * @author chenshun * @email sunlightcs@gmail.com * @date 2020-02-20 17:14:19 */ @Mapper public interface CbsImgPurchaseInvoiceDao extends BaseMapper<CbsImgPurchaseInvoiceEntity> { List<CbsImgPurchaseInvoiceEntity> listByPurchaseId(Long purchaseId); }
25.35
91
0.794872
4712e5ee7ca6445026b3e660b3105885ce216833
2,319
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.dadoco.common.lazyModel; import java.util.List; import java.util.Map; /** * * @author fernando * @param <T> */ public class InfoModel<T> { private String jpqlQuery; private Map<String,Object> parametros; private List<T> listaDatos; private int count; public InfoModel() { } public InfoModel(String jpqlQuery, Map<String, Object> parametros) { this.jpqlQuery = jpqlQuery; this.parametros = parametros; } public InfoModel(String jpqlQuery, Map<String, Object> parametros, List<T> listaDatos) { this.jpqlQuery = jpqlQuery; this.parametros = parametros; this.listaDatos = listaDatos; } public InfoModel(String jpqlQuery, Map<String, Object> parametros, List<T> listaDatos, int count) { this.jpqlQuery = jpqlQuery; this.parametros = parametros; this.listaDatos = listaDatos; this.count = count; } public String getJpqlQuery() { // if(jpqlQuery!=null){ // if(parametros!=null){ // for (Map.Entry<String, Object> entry : parametros.entrySet()) { // String key = entry.getKey(); // jpqlQuery=jpqlQuery.replace(":"+key, "$P{"+key+"}"); // } // } // } return jpqlQuery; } public void setJpqlQuery(String jpqlQuery) { this.jpqlQuery = jpqlQuery; } public Map<String,Object> getParametros() { return parametros; } public void setParametros(Map<String,Object> parametros) { this.parametros = parametros; } /** * @return the listaDatos */ public List<T> getListaDatos() { return listaDatos; } /** * @param listaDatos the listaDatos to set */ public void setListaDatos(List<T> listaDatos) { this.listaDatos = listaDatos; } /** * @return the count */ public int getCount() { return count; } /** * @param count the count to set */ public void setCount(int count) { this.count = count; } }
23.424242
103
0.586891
81a6c311ab50cb168dab62c2d07b622170d9c648
192
package repositories; import models.StockType; import org.springframework.data.jpa.repository.JpaRepository; public interface StockTypeRepository extends JpaRepository<StockType, Long> { }
21.333333
77
0.838542
2be3a936c30cdc46b407c4d135bd002c79f8edb4
7,738
// Copyright 2020 Goldman Sachs // // 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.finos.legend.engine.plan.execution.result.freemarker; import freemarker.core.TemplateDateFormat; import freemarker.template.TemplateDateModel; import org.eclipse.collections.api.RichIterable; import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.factory.Lists; import org.finos.legend.engine.shared.core.operational.logs.LogInfo; import org.finos.legend.engine.shared.core.operational.logs.LoggingEventType; import org.slf4j.Logger; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PlanDateParameterDateFormat extends TemplateDateFormat { private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger("Alloy Execution Server"); private static final RichIterable<PlanDateParameterFormatter> planStrictDateFormatters = Lists.immutable.with(new PlanDateParameterFormatter("yyyy-MM-dd", false, false, false, false)); private static final RichIterable<PlanDateParameterFormatter> planDateTimeFormatters = Lists.immutable.with( new PlanDateParameterFormatter("yyyy-MM-dd'T'HH:mm:ss", true, false, true, false), new PlanDateParameterFormatter("yyyy-MM-dd'T'HH:mm:ss.SSS", true, false, true, true), new PlanDateParameterFormatter("yyyy-MM-dd HH:mm:ss.SSS", true, false, true, true), new PlanDateParameterFormatter("yyyy-MM-dd HH:mm:ss", true, false, true, false), new PlanDateParameterFormatter("yyyy-MM-dd'T'HH:mm:ss.SSSZ", true, true, true, true), new PlanDateParameterFormatter("yyyy-MM-dd'T'HH:mm:ssZ", true, true, true, false)); private static final RichIterable<PlanDateParameterFormatter> planDateFormatters = Lists.mutable.withAll(planStrictDateFormatters).withAll(planDateTimeFormatters); private static final String dateRegex = "\\[(\\S+)\\]\\s(\\S+([\\sT]\\S+)?)"; private static final Pattern datePattern = Pattern.compile(dateRegex); static final PlanDateParameterDateFormat INSTANCE = new PlanDateParameterDateFormat(); public static class PlanDateParameterFormatter { DateTimeFormatter dateFormatter; public boolean isDateTime; private boolean hasTimeOffset; boolean performTzConversion; public boolean hasSubSecond; private final String datePattern; PlanDateParameterFormatter(String datePattern, boolean isDateTime, boolean hasTimeOffset, boolean performTzConversion, boolean hasSubSecond) { this.isDateTime = isDateTime; this.hasTimeOffset = hasTimeOffset; this.dateFormatter = DateTimeFormatter.ofPattern(datePattern); this.performTzConversion = performTzConversion; this.hasSubSecond = hasSubSecond; this.datePattern = datePattern; } public LocalDateTime parse(String date) throws DateTimeParseException { LocalDateTime localDateTime; if (this.hasTimeOffset) { localDateTime = OffsetDateTime.parse(date, this.dateFormatter).atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime(); } else if (this.isDateTime) { localDateTime = LocalDateTime.parse(date, this.dateFormatter); } else { localDateTime = LocalDate.parse(date, this.dateFormatter).atStartOfDay(); } return localDateTime; } public String getDatePattern() { return this.datePattern; } } private PlanDateParameterDateFormat() { } public static RichIterable<PlanDateParameterFormatter> getPlanDateFormatters() { return planDateFormatters; } public static RichIterable<PlanDateParameterFormatter> getPlanDateFormatters(boolean isDateTime) { return isDateTime ? planDateTimeFormatters : planStrictDateFormatters; } @Override public java.lang.Object format(freemarker.template.TemplateDateModel dateModel) { PlanDateParameter pureFreemarkerDate = (PlanDateParameter) dateModel; return pureFreemarkerDate.formattedDate(); } @Override public PlanDateParameter parse(String dateExpression, int i) { PlanDateParameter pureFreemarkerDate = getPlanFreemarkerDateTimeForTz(dateExpression); if (pureFreemarkerDate == null) { throwIllegalArgumentException(dateExpression); } return pureFreemarkerDate; } private static void throwIllegalArgumentException(String dateExpression) throws IllegalArgumentException { String exceptionMessage = "Plan parsing error; unable to process Date: " + dateExpression + ", expecting: " + dateRegex + " e.g.: '[EST] + $date', where $date is of format: " + planDateFormatters.collect(pdf -> pdf.datePattern).makeString("[", ", ", "]") + " , e.g. : [EST] 2018-10-15T20:00:00.123"; LOGGER.error(new LogInfo(null, LoggingEventType.JSON_PARSING_ERROR, exceptionMessage).toString()); throw new IllegalArgumentException(exceptionMessage); } private PlanDateParameter getPlanFreemarkerDateTimeForTz(String dateExpression) { DateAndTimeZone dateAndTimeZone = extractDateAndTimeZone(dateExpression); return planDateFormatters.asLazy().collect(dtf -> { try { LocalDateTime dateTime = dtf.parse(dateAndTimeZone.date); if (dtf.performTzConversion) { return new PlanDateParameter(dateTime, dtf.dateFormatter, dateAndTimeZone.tz); } else { return new PlanDateParameter(dateTime, dtf.dateFormatter); } } catch (DateTimeParseException e) { return null; } }).detect(Predicates.notNull()); } private DateAndTimeZone extractDateAndTimeZone(String dateExpression) { Matcher m = datePattern.matcher(dateExpression); if (!m.matches()) { throwIllegalArgumentException(dateExpression); } String tz = m.group(1); String date = m.group(2); return new DateAndTimeZone(date, tz); } private static class DateAndTimeZone { String date; String tz; DateAndTimeZone(String date, String tz) { this.date = date; this.tz = tz; } } @Override public String formatToPlainText(TemplateDateModel templateDateModel) { throw new UnsupportedOperationException(); } @Override public boolean isLocaleBound() { return true; } @Override public boolean isTimeZoneBound() { return true; } @Override public String getDescription() { return "Plan Date Format"; } }
37.201923
307
0.67679
0a5e4df3e76fc0466630ffad5831c81d53761cf5
2,142
package auth.service; import auth.dto.AuthDto; import auth.entity.User; import auth.repository.UserRepository; import auth.service.impl.UserServiceImpl; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpHeaders; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.*; @RunWith(JUnit4.class) public class UserServiceImplTest { @InjectMocks private UserServiceImpl userServiceImpl; @Mock private UserRepository userRepository; @Mock protected PasswordEncoder passwordEncoder; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testSaveUser() { User user = new User(); Assert.assertEquals(null, userServiceImpl.saveUser(user)); } @Test public void testGetAllUser() { List<User> userList = new ArrayList<>(); userList.add(new User()); Mockito.when(userRepository.findAll()).thenReturn(userList); Assert.assertEquals(userList, userServiceImpl.getAllUser(headers)); } @Test public void testCreateDefaultAuthUser() { AuthDto dto = new AuthDto(UUID.randomUUID().toString(), "username", "password"); User user = new User(); Mockito.when(userRepository.save(user)).thenReturn(user); Mockito.when(passwordEncoder.encode(dto.getPassword())).thenReturn("password"); Assert.assertEquals(null, userServiceImpl.createDefaultAuthUser(dto)); } @Test public void testDeleteByUserId() { UUID userId = UUID.randomUUID(); Mockito.doNothing().doThrow(new RuntimeException()).when(userRepository).deleteByUserId(userId); Assert.assertEquals(new Response(1, "DELETE USER SUCCESS", null), userServiceImpl.deleteByUserId(userId, headers)); } }
30.169014
123
0.720822
1f5e880454ca90384f653450c89c0e272f98a8c5
1,036
package ch.agent.crnickl.jdbc.junit; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { TestSuite suite = new TestSuite(AllTests.class.getName()); //$JUnit-BEGIN$ suite.addTestSuite(T005_BasicTest.class); suite.addTestSuite(T005_CacheTest.class); suite.addTestSuite(T006_ChronicleTest_StrictMode.class); suite.addTestSuite(T006_ChronicleTest_NonStrictMode.class); suite.addTestSuite(T012_ValueTypeTest.class); suite.addTestSuite(T013_PropertyTest.class); suite.addTestSuite(T015_SchemaChronicleSeriesValueTest.class); suite.addTestSuite(T017_SchemaTest.class); suite.addTestSuite(T040_SeriesTest.class); suite.addTestSuite(T041_UpdatableSeriesTest.class); suite.addTestSuite(T042_SeriesValuesTest.class); suite.addTestSuite(T043_SparseSeriesTest.class); suite.addTestSuite(T045_EventTest.class); suite.addTestSuite(T050_ChronicleTest.class); suite.addTestSuite(T060_ByAttributeValueTest.class); //$JUnit-END$ return suite; } }
33.419355
64
0.810811
bc1ca05e4359318f3c274d43625d650d8ce34739
3,075
/** * alert-common * * Copyright (C) 2019 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * 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 com.synopsys.integration.alert.common.persistence.util; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.google.gson.Gson; import com.synopsys.integration.alert.common.AlertProperties; @Component public class FilePersistenceUtil { public static final String ENCODING = "UTF-8"; private final File parentDataDirectory; private final Gson gson; @Autowired public FilePersistenceUtil(final AlertProperties alertProperties, final Gson gson) { this.gson = gson; String dataDirectory = "data/"; if (StringUtils.isNotBlank(alertProperties.getAlertConfigHome())) { dataDirectory = String.format("%s/data", alertProperties.getAlertConfigHome()); } this.parentDataDirectory = new File(dataDirectory); } public void writeToFile(final String fileName, final String content) throws IOException { FileUtils.write(createFilePath(fileName), content, ENCODING); } public void writeJsonToFile(final String fileName, final Object content) throws IOException { final String jsonString = gson.toJson(content); writeToFile(fileName, jsonString); } public String readFromFile(final String fileName) throws IOException { return FileUtils.readFileToString(createFilePath(fileName), ENCODING); } public <T> T readJsonFromFile(final String fileName, final Class<T> clazz) throws IOException { final String jsonString = readFromFile(fileName); return gson.fromJson(jsonString, clazz); } public boolean exists(final String fileName) { final File file = createFilePath(fileName); return file.exists(); } public void delete(final String fileName) throws IOException { final File file = createFilePath(fileName); FileUtils.forceDelete(file); } private File createFilePath(final String fileName) { return new File(parentDataDirectory, fileName); } }
36.176471
99
0.733008
5591f876a7603256d18cef6ac57cf4273e41617f
6,684
package com.example.bdafahim.easyrent; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionButton; import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionHelper; import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionLayout; import com.wangjie.rapidfloatingactionbutton.contentimpl.labellist.RFACLabelItem; import com.wangjie.rapidfloatingactionbutton.contentimpl.labellist.RapidFloatingActionContentLabelList; import com.wangjie.rapidfloatingactionbutton.util.RFABShape; import com.wangjie.rapidfloatingactionbutton.util.RFABTextUtil; import java.util.ArrayList; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; import static java.security.AccessController.getContext; public class profile_user extends AppCompatActivity implements RapidFloatingActionContentLabelList.OnRapidFloatingActionContentLabelListListener{ private CircleImageView imageViewb; private TextView sname,semail,saddress,sphone; private DatabaseReference mdata; private static User_Info uinfo ; private RapidFloatingActionLayout rfaLayout; private RapidFloatingActionButton rfaBtn; private RapidFloatingActionHelper rfabHelper; private String EMAIL,url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile_user); final ProgressDialog Dialog = new ProgressDialog(profile_user.this); Dialog.setMessage("Loading ..."); Dialog.show(); imageViewb = findViewById(R.id.imageView); sname = findViewById(R.id.show_name); saddress = findViewById(R.id.show_address); sphone = findViewById(R.id.show_phone); semail = findViewById(R.id.show_email); mdata = FirebaseDatabase.getInstance().getReference("Users"); rfaLayout = (RapidFloatingActionLayout) findViewById(R.id.activity_main_rfal); rfaBtn = (RapidFloatingActionButton) findViewById(R.id.activity_main_rfab); RapidFloatingActionContentLabelList rfaContent = new RapidFloatingActionContentLabelList(this); rfaContent.setOnRapidFloatingActionContentLabelListListener(profile_user.this); List<RFACLabelItem> items = new ArrayList<>(); items.add(new RFACLabelItem<Integer>() .setLabel("Update Profile") .setResId(R.drawable.circle_ba) .setIconNormalColor(0xff64b5f6) .setIconPressedColor(0xffbf360c) .setWrapper(0) ); items.add(new RFACLabelItem<Integer>() .setLabel("Create Post") // .setResId(R.mipmap.ico_test_c) .setDrawable(getResources().getDrawable(R.drawable.circle_ba)) .setIconNormalColor(0xff64b5f6) .setIconPressedColor(0xff3e2723) .setLabelSizeSp(14) .setWrapper(1) ); items.add(new RFACLabelItem<Integer>() .setLabel("Manage Post") .setResId(R.drawable.circle_ba) .setIconNormalColor(0xff64b5f6) .setIconPressedColor(0xff0d5302) .setWrapper(2) ); items.add(new RFACLabelItem<Integer>() .setLabel("Logout") .setResId(R.drawable.circle_ba) .setIconNormalColor(0xff64b5f6) .setIconPressedColor(0xff1a237e) .setWrapper(3) ); rfaContent .setItems(items) .setIconShadowRadius(RFABTextUtil.dip2px(this, 5)) .setIconShadowColor(0xff888888) .setIconShadowDy(RFABTextUtil.dip2px(this, 5)) ; rfabHelper = new RapidFloatingActionHelper( this, rfaLayout, rfaBtn, rfaContent ).build(); mdata.child(FirebaseAuth.getInstance().getCurrentUser().getUid().toString()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { url = dataSnapshot.child("imageString").getValue(String.class).toString(); //System.out.println(url); uinfo = dataSnapshot.getValue(User_Info.class); //uinfo.pri(); Picasso.get().load(url).fit().into(imageViewb); //System.out.println("Naem" +uinfo.getImageString()); sname.setText("Name : "+uinfo.getUname()); saddress.setText("Address : "+uinfo.getUaddress()); sphone.setText("Phone : "+uinfo.getUphoneNo()); semail.setText("Email : "+uinfo.getUemail()); EMAIL = uinfo.getUemail(); Dialog.dismiss(); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onRFACItemLabelClick(int position, RFACLabelItem item) { Toast.makeText(profile_user.this, "clicked label: " + position, Toast.LENGTH_SHORT).show(); rfabHelper.toggleContent(); } @Override public void onRFACItemIconClick(int position, RFACLabelItem item) { if(position==0) { Intent i = new Intent(profile_user.this,profile_update.class); i.putExtra("email",EMAIL); i.putExtra("URL",url); startActivity(i); } else if(position==1) { startActivity(new Intent(profile_user.this,Post_Add.class)); } else if(position==2) { startActivity(new Intent(profile_user.this,Manage_Post.class)); } else if(position==3) { FirebaseAuth.getInstance().signOut(); startActivity(new Intent(profile_user.this,UserCatagory.class)); } rfabHelper.toggleContent(); } }
37.133333
145
0.648265
71fa1f8d71c4bc4ea0bfa0a4d5e921acc98f9c9f
1,060
package br.com.flaviogf.manager.controllers; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import br.com.flaviogf.manager.entities.Company; import br.com.flaviogf.manager.repositories.CompanyRepository; import br.com.flaviogf.manager.repositories.InMemoryCompanyRepository; public class JsonController { private final CompanyRepository companyRepository; public JsonController() { companyRepository = new InMemoryCompanyRepository(); } public void index(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter writer = response.getWriter(); List<Company> companies = new ArrayList<>(companyRepository.findAll()); Gson gson = new Gson(); String json = gson.toJson(companies); response.setHeader("Content-Type", "application/json"); writer.print(json); } }
28.648649
100
0.754717
e612364065fadcbd0e6df4ed60137f5941b4634f
1,247
package kafkacollector.common; import kafkacollector.exception.KafkaCollectorException; /** * Copyright 2017 Hiroki Uchida * * 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. */ public interface TaskExecutor { void initialize() throws KafkaCollectorException; void preProcess() throws KafkaCollectorException; void process() throws KafkaCollectorException; void postProcess() throws KafkaCollectorException; void terminate() throws KafkaCollectorException; default void execute() throws KafkaCollectorException{ try { this.initialize(); this.preProcess(); this.process(); this.postProcess(); } finally { this.terminate(); } } }
32.815789
75
0.708099
aa1d1adcdd5e7bc23b801bd92c0ecbe83289d290
194
package ood.srp; public interface InterCalc { void resetResult(); void showMenu(); Operation getOperation(int key); double getResult(); void setResult(double result); }
13.857143
36
0.675258
389e25de3602871886122e8da1a0087a3e74edb6
1,595
// Autor y desarrollador parcial o total: Santiago Hernández Plazas (santiago.h.plazas@gmail.com). package co.gov.ideamredd.mbc.conexion; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import javax.sql.DataSource; import oracle.jdbc.OracleTypes; /** * clase para consultar los parametros del sistema de forma basica. */ public class ParametroNoBean { public String getParametro(String nombreParametro) { ConexionBDNoBean conexion; Connection conn = null; DataSource dataSource; String parametro = null; try { conexion = new ConexionBDNoBean(); dataSource = conexion.getConnection(); conn = dataSource.getConnection(); CallableStatement consultarParameto = conn.prepareCall("{call RED_PK_PARAMETROS.Parametro_Consulta_RP(?,?,?)}"); consultarParameto.setString("un_Nombre", nombreParametro); consultarParameto.registerOutParameter("una_Ruta", OracleTypes.CURSOR); consultarParameto.registerOutParameter("sentencia", OracleTypes.VARCHAR, 250); consultarParameto.execute(); // System.out.println(consultarParameto.getObject("sentencia")); ResultSet resultSet = (ResultSet) consultarParameto.getObject("una_Ruta"); while (resultSet.next()) { parametro = resultSet.getString(1); } resultSet.close(); consultarParameto.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); conn = null; } catch (Exception e) { e.printStackTrace(); } } } return parametro; } }
24.166667
115
0.715361
3befc28c9de6634577926401bf53d37f6fd0ee81
1,493
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2006-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.filter; import java.util.Iterator; import java.util.List; import org.opengis.filter.Filter; import org.opengis.filter.FilterVisitor; import org.opengis.filter.And; /** * Direct implementation of And filter. * * @author jdeolive * * * * @source $URL$ */ public class AndImpl extends LogicFilterImpl implements And { protected AndImpl(List<Filter> children) { super(children); } public boolean evaluate(Object object) { for (Iterator<Filter> itr = children.iterator(); itr.hasNext();) { Filter filter = itr.next(); if (!filter.evaluate(object)) { return false; // short circuit } } return true; } public Object accept(FilterVisitor visitor, Object extraData) { return visitor.visit(this,extraData); } }
26.660714
74
0.668453
90bd1ba048177cebd4e661e291603f7e6506510f
3,102
/** * Copyright 2019-2020 Zheng Jie * * 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.dubhe.admin.service; import org.dubhe.admin.domain.dto.*; import org.dubhe.admin.domain.entity.Menu; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; /** * @description 菜单服务 Service * @date 2020-06-01 */ public interface MenuService { /** * 按条件查询菜单列表 * * @param criteria 菜单请求实体 * @return java.util.List<org.dubhe.domain.dto.MenuDTO> 菜单返回实例 */ List<MenuDTO> queryAll(MenuQueryDTO criteria); /** * 根据id查询菜单信息 * * @param id 菜单id * @return org.dubhe.domain.dto.MenuDTO 菜单返回实例 */ MenuDTO findById(long id); /** * 新增菜单 * * @param resources 菜单新增请求实体 * @return org.dubhe.domain.dto.MenuDTO 菜单返回实例 */ MenuDTO create(MenuCreateDTO resources); /** * 修改菜单 * * @param resources 菜单修改请求实体 */ void update(MenuUpdateDTO resources); /** * 查询可删除的菜单 * * @param menuList * @param menuSet * @return java.util.Set<org.dubhe.domain.entity.Menu> */ Set<Menu> getDeleteMenus(List<Menu> menuList, Set<Menu> menuSet); /** * 获取菜单树 * * @param menus 菜单列表 * @return java.lang.Object 菜单树结构列表 */ Object getMenuTree(List<Menu> menus); /** * 根据ID获取菜单列表 * * @param pid id * @return java.util.List<org.dubhe.domain.entity.Menu> 菜单返回列表 */ List<Menu> findByPid(long pid); /** * 构建菜单树 * * @param menuDtos 菜单请求实体 * @return java.util.Map<java.lang.String, java.lang.Object> 菜单树结构 */ Map<String, Object> buildTree(List<MenuDTO> menuDtos); /** * 根据角色查询菜单列表 * * @param roles 角色 * @return java.util.List<org.dubhe.domain.dto.MenuDTO> 菜单返回实例 */ List<MenuDTO> findByRoles(List<RoleSmallDTO> roles); /** * 构建菜单树 * * @param menuDtos 菜单请求实体 * @return java.util.List<org.dubhe.domain.vo.MenuVo> 菜单树返回实例 */ Object buildMenus(List<MenuDTO> menuDtos); /** * 获取菜单 * * @param id id * @return org.dubhe.domain.entity.Menu 菜单返回实例 */ Menu findOne(Long id); /** * 删除菜单 * * @param menuSet 删除菜单请求集合 */ void delete(Set<Menu> menuSet); /** * 导出 * * @param queryAll 待导出的数据 * @param response 导出http响应 * @throws IOException 导出异常 */ void download(List<MenuDTO> queryAll, HttpServletResponse response) throws IOException; }
22.642336
91
0.624113
b9ca17ae7de72bb4ae165c00c78afb0dc50ec523
175
package com.poc.poo.inheritance.Hierarchical; public class FourWheeler extends Bike{ int noOfWheels; public FourWheeler() { noOfWheels = 4; } }
17.5
46
0.645714
12ac93ab994e04046d4b10503a4c8b4185029a20
298
import java.lang.ArithmeticException; public class Arithmetic { public static void main(String[] args) { System.out.println("Hello, World"); try { int i = 0 / 0; } catch (ArithmeticException e) { System.out.println("ArithmeticException occured!"); } } }
21.285714
58
0.624161
fe9b00e49238d983827dca13a37dddabe1594349
1,195
package no.gorandalum.fluentresult; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.*; class Result_RunIfError_Test { @Test void runIfError_success_consumerShouldBeRun() { Result<String, String> result = Result.success("Success"); Result<String, String> finalResult = result.runIfError(() -> fail("Should not be run")); assertThat(finalResult).isNotNull(); } @Test void runIfError_error_consumerShouldBeRun() { List<String> resultList = new ArrayList<>(); Result<String, String> result = Result.error("Error"); Result<String, String> finalResult = result.runIfError(() -> resultList.add("Ran")); assertThat(resultList.size()).isOne(); assertThat(resultList.get(0)).isEqualTo("Ran"); assertThat(finalResult).isNotNull(); } @Test void runIfError_success_nullRunnableGivesNPE() { Result<String, String> result = Result.success("Success"); assertThatThrownBy(() -> result.runIfError(null)) .isInstanceOf(NullPointerException.class); } }
32.297297
67
0.658577
d0df9c0291d3239d371854178a847be98bc25b1c
1,077
package cn.itcast.service; import cn.itcast.domain.PageBean; import cn.itcast.domain.User; import java.util.List; import java.util.Map; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 登录方法 * @param user * @return */ User login(User user); /** * 保存User * @param user */ void addUser(User user); /** * 根据id删除User * @param id */ void deleteUser(String id); /** * 根据id查询 * @param id * @return */ User findUserById(String id); /** * 修改用户信息 * @param user */ void updateUser(User user); /** * 批量删除用户 * @param ids */ void delSelectedUser(String[] ids); /** * 分页条件查询 * @param currentPage * @param rows * @param condition * @return */ PageBean<User> findUserByPage(String currentPage, String rows, Map<String, String[]> condition); }
16.074627
101
0.499536
ccaf951e712ed22ba3be298484910a68d49b7d78
286
package com.example.context_ref; import arez.annotations.ArezComponent; import com.example.context_ref.other.BaseProtectedAccessContextRefModel; @ArezComponent( allowEmpty = true ) abstract class ProtectedAccessFromBaseContextRefModel extends BaseProtectedAccessContextRefModel { }
26
72
0.863636
0f2982055788374f6e7e51d1c3c4ec284be19460
7,371
package de.hhu.stups.plues.ui.controller; import com.google.inject.Inject; import de.hhu.stups.plues.Delayed; import de.hhu.stups.plues.data.Store; import de.hhu.stups.plues.data.entities.Course; import de.hhu.stups.plues.routes.RouteNames; import de.hhu.stups.plues.services.SolverService; import de.hhu.stups.plues.services.UiDataService; import de.hhu.stups.plues.ui.components.ColorSchemeSelection; import de.hhu.stups.plues.ui.components.ControllerHeader; import de.hhu.stups.plues.ui.components.MajorMinorCourseSelection; import de.hhu.stups.plues.ui.components.PdfGenerationSettings; import de.hhu.stups.plues.ui.components.ResultBox; import de.hhu.stups.plues.ui.components.ResultBoxFactory; import de.hhu.stups.plues.ui.components.UnitDisplayFormatSelection; import de.hhu.stups.plues.ui.components.timetable.TimetableMisc; import de.hhu.stups.plues.ui.layout.Inflater; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ListView; import javafx.scene.layout.GridPane; import java.util.Optional; import java.util.ResourceBundle; public class Musterstudienplaene extends GridPane implements Activatable { @FXML private ResourceBundle resources; private final Delayed<Store> delayedStore; private final Delayed<SolverService> delayedSolverService; private final BooleanProperty solverProperty; private final ResultBoxFactory resultBoxFactory; private final UiDataService uiDataService; private PdfGenerationSettings pdfGenerationSettings; @FXML @SuppressWarnings("unused") private ControllerHeader controllerHeader; @FXML @SuppressWarnings("unused") private MajorMinorCourseSelection courseSelection; @FXML @SuppressWarnings("unused") private ColorSchemeSelection colorSchemeSelection; @FXML @SuppressWarnings("unused") private Button btGenerate; @FXML @SuppressWarnings("unused") private ListView<ResultBox> resultBoxWrapper; @FXML @SuppressWarnings("unused") private UnitDisplayFormatSelection unitDisplayFormatSelection; /** * This view presents a selection of major and minor courses where the user can choose a * combination of courses or a standalone course from. The specific pdf file can be generated and * success or failure is displayed in a list of {@link ResultBox result boxes}. The user is able * to view or save the pdf file or remove the result box from the list. * * @param inflater Inflater to handle fxml loading * @param delayedStore Store containing relevant data * @param delayedSolverService SolverService for usage of ProB solver * @param resultBoxFactory Factory to create ResultBox entities */ @Inject public Musterstudienplaene(final Inflater inflater, final Delayed<Store> delayedStore, final Delayed<SolverService> delayedSolverService, final UiDataService uiDataService, final ResultBoxFactory resultBoxFactory) { this.delayedStore = delayedStore; this.delayedSolverService = delayedSolverService; this.resultBoxFactory = resultBoxFactory; this.uiDataService = uiDataService; this.solverProperty = new SimpleBooleanProperty(false); this.pdfGenerationSettings = new PdfGenerationSettings(null, null); inflater.inflate("Musterstudienplaene", this, this, "musterstudienplaene"); } @FXML public void initialize() { colorSchemeSelection.defaultInitialization(); colorSchemeSelection.disableProperty().bind(courseSelection .getMajorComboBox().disabledProperty()); pdfGenerationSettings.colorSchemeProperty().bind(colorSchemeSelection.selectedColorScheme()); pdfGenerationSettings.unitDisplayFormatProperty() .bind(unitDisplayFormatSelection.selectedDisplayFormatProperty()); btGenerate.disableProperty().bind(solverProperty.not()); resultBoxWrapper.visibleProperty().bind(Bindings.isEmpty(resultBoxWrapper.getItems()).not()); // disable list-view selection resultBoxWrapper.getSelectionModel().selectedIndexProperty().addListener( (observable, oldValue, newValue) -> Platform.runLater(() -> resultBoxWrapper.getSelectionModel().select(-1))); delayedStore.whenAvailable(store -> courseSelection.setMajorCourseList(FXCollections.observableList(store.getMajors()))); courseSelection.impossibleCoursesProperty().bind(uiDataService.impossibleCoursesProperty()); delayedSolverService.whenAvailable(s -> this.solverProperty.set(true)); initializeControllerHeader(); } private void initializeControllerHeader() { controllerHeader.setTitle(resources.getString("titlePDF")); controllerHeader.setInfoText(resources.getString("infoPDF")); } /** * Function to handle generation of resultbox containing result for chosen major and minor. */ @FXML @SuppressWarnings( {"unused,WeakerAccess"}) public void btGeneratePressed() { addOrRestartResultBox(courseSelection.getSelectedCourses()); } /** * In case the {@link #resultBoxWrapper} already contains a {@link ResultBox} with the * selected courses we restart this box and bring it to the top of the list view. * Otherwise, a new result box is created. */ @SuppressWarnings("unused") private void addOrRestartResultBox(final ObservableList<Course> selectedCourses) { if (selectedCourses.size() == 0) { return; } final Course majorCourse = selectedCourses.get(0); final Course minorCourse; if (selectedCourses.size() == 2) { minorCourse = selectedCourses.get(1); } else { minorCourse = null; } final Optional<ResultBox> containsBox = resultBoxWrapper.getItems().stream().filter( resultBox -> majorCourse.equals(resultBox.getMajorCourse()) && TimetableMisc.equalCoursesOrNull(minorCourse, resultBox.getMinorCourse())) .findFirst(); if (containsBox.isPresent()) { toTopOfListview(containsBox.get()); return; } resultBoxWrapper.getItems().add(0, resultBoxFactory.create(majorCourse, minorCourse, resultBoxWrapper, pdfGenerationSettings)); resultBoxWrapper.scrollTo(0); } private void toTopOfListview(final ResultBox resultBox) { resultBoxWrapper.getItems().remove(resultBox); resultBoxWrapper.getItems().add(0, resultBox); resultBoxWrapper.scrollTo(0); resultBox.runSolverTask(); } /** * Select the given courses within the {@link #courseSelection} when the user navigates to the * view via the {@link de.hhu.stups.plues.routes.ControllerRoute}. */ @Override public void activateController(final RouteNames routeName, final Object... courses) { if (courses.length > 0) { courseSelection.selectCourse((Course) courses[0]); } if (courses.length > 1) { courseSelection.selectCourse((Course) courses[1]); } if (courses.length == 2) { btGeneratePressed(); } } ListView<ResultBox> getResultBoxWrapper() { return resultBoxWrapper; } Button getBtGenerate() { return btGenerate; } }
37.040201
99
0.746846
cab7a3f9bdb6c7e2aeace487c594ec68d1d45a76
961
package mlog.ctrl.rt; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.List; import reactor.core.publisher.Flux; import reactor.core.publisher.UnicastProcessor; import reactor.util.concurrent.Queues; public class MessageQueue { private UnicastProcessor<Message> processor = UnicastProcessor.create(Queues.<Message>unboundedMultiproducer().get()); public void process(Message message){ if (processor.sink().isCancelled()){ throw new RuntimeException("Queue is cancelled"); } processor.sink().next(message); } public Flux<List<Message>> getMessageBatches() { return processor.bufferTimeout(100, Duration.of(1, ChronoUnit.SECONDS)); } public int getQueueSize(){ return processor.size(); } public int getBufferSize(){ return processor.getBufferSize(); } public void stop(){ processor.cancel(); } public boolean isAlive() { return !processor.isDisposed(); } }
23.439024
120
0.726327
66ef651977435b5cb94dadb6ca2a5ebf2ce59129
823
package org.ovirt.engine.ui.webadmin.section.main.view.popup.pool; import org.ovirt.engine.ui.common.view.popup.AbstractVmPopupView; import org.ovirt.engine.ui.common.widget.uicommon.popup.pool.PoolNewPopupWidget; import org.ovirt.engine.ui.webadmin.ApplicationConstants; import org.ovirt.engine.ui.webadmin.ApplicationResources; import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.pool.PoolNewPopupPresenterWidget; import com.google.gwt.event.shared.EventBus; import com.google.inject.Inject; public class PoolNewPopupView extends AbstractVmPopupView implements PoolNewPopupPresenterWidget.ViewDef { @Inject public PoolNewPopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants) { super(eventBus, resources, new PoolNewPopupWidget(constants)); } }
41.15
112
0.827461
6bd75f2409a7663574be77815c2257333775d2fd
6,468
package com.lesjuz.movy.Adapter; import android.content.Context; import android.content.res.Configuration; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.lesjuz.movy.Model.Movies; import com.lesjuz.movy.R; import com.squareup.picasso.Picasso; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.picasso.transformations.RoundedCornersTransformation; /** * Created by Lesjuz on 3/6/2017. */ public class MovieRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public interface OnItemClickListener { void onItemClick(Movies item); } private List<Movies> movies; private Context mContext; private final OnItemClickListener listener; final static int PopularMovies = 0; final static int NotPopularMovies = 1; public class MovieViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.title) TextView title; @BindView(R.id.description) TextView description; @BindView(R.id.poster) ImageView poster; public MovieViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } public class PopularMovieViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.ivMovie) public FrameLayout ivMovie; @BindView(R.id.tvTitle) public TextView tvTitle; @BindView(R.id.ivPlay) public ImageView ivPlay; @BindView(R.id.ivMovieImage) public ImageView ivImage; public PopularMovieViewHolder(View view) { super(view); ButterKnife.bind(this, view); } public ImageView getImageView() { return ivImage; } public void setImageView(ImageView ivExample) { this.ivImage = ivExample; } public TextView getTitle() { return tvTitle; } public void setTitle(TextView title) { this.tvTitle = title; } } private class RecyclerViewSimpleTextViewHolder extends RecyclerView.ViewHolder { public RecyclerViewSimpleTextViewHolder(View v) { super(v); }} public MovieRecyclerAdapter(Context context, List<Movies> movies, OnItemClickListener listener){ this.movies = movies; this.mContext=context; this.listener = listener; } private Context getContext() { return mContext; } @Override public int getItemViewType(int position) { Movies mv=movies.get(position); if (mv.getVoteAverage() >= 5) { return PopularMovies; } return NotPopularMovies; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { RecyclerView.ViewHolder viewHolder; LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); switch (viewType) { case PopularMovies: View v1 = inflater.inflate(R.layout.popular_movie_item, viewGroup, false); viewHolder = new PopularMovieViewHolder(v1); break; case NotPopularMovies: View v2 = inflater.inflate(R.layout.movie_item, viewGroup, false); viewHolder = new MovieViewHolder(v2); break; default: View v = inflater.inflate(android.R.layout.simple_list_item_1, viewGroup, false); viewHolder = new RecyclerViewSimpleTextViewHolder(v); break; } return viewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { switch (viewHolder.getItemViewType()) { case PopularMovies: PopularMovieViewHolder vh1 = (PopularMovieViewHolder) viewHolder; configureViewHolder1(vh1, position,listener); break; case NotPopularMovies: MovieViewHolder vh2 = (MovieViewHolder) viewHolder; configureViewHolder2(vh2, position,listener); break; default: break; } } private void configureViewHolder2(MovieViewHolder vh2, int position, final OnItemClickListener listener) { final Movies mv=movies.get(position); TextView tv1 = vh2.title; tv1.setText(mv.getTitle()); TextView tv2 = vh2.description; tv2.setText(mv.getOverview()); ImageView iv=vh2.poster; int orientation = getContext().getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_PORTRAIT) { Picasso.with(getContext()).load(mv.getPosterUrl()).transform(new RoundedCornersTransformation(10, 10)).placeholder(R.mipmap.movie_placeholder).into(iv); } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) { Picasso.with(getContext()).load(mv.getBackDropUrl()).transform(new RoundedCornersTransformation(10, 10)).placeholder(R.mipmap.movie_placeholder).into(iv); } vh2.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listener.onItemClick(mv); } }); } private void configureViewHolder1(PopularMovieViewHolder vh1, int position, final OnItemClickListener listener) { final Movies mv=movies.get(position); vh1.getImageView().setImageResource(0); vh1.getTitle().setText(mv.getTitle()); Picasso.with(getContext()) .load(mv.getBackDropUrl()) .placeholder(R.mipmap.movie_placeholder) .transform(new RoundedCornersTransformation(10, 10)) .into(vh1.getImageView()); vh1.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listener.onItemClick(mv); } }); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } @Override public int getItemCount() { return movies.size(); } }
31.705882
166
0.64363
608bfeccc36ef431b0d7c75daf76a0ab8c9cfc37
1,236
package org.helper.gerrit.core.main; import java.io.IOException; import java.util.List; import org.helper.gerrit.core.GerritApiUtils; import org.helper.gerrit.core.PropertyUtils; import org.helper.gerrit.model.GerritProperties; import com.google.gerrit.extensions.api.GerritApi; import com.google.gerrit.extensions.common.ChangeInfo; import com.google.gerrit.extensions.restapi.RestApiException; /** * @author Sukhpal Singh * */ public class GerritGetToBeReviewedChanges { public static void main(String[] args) throws IOException, RestApiException { GerritProperties gerritProperties = PropertyUtils.loadProperties(); GerritApi gerritApi = GerritApiUtils.login(gerritProperties); List<ChangeInfo> changes = gerritApi.changes().query("is:open+owner:self").get(); System.out.println("Please review : "); for (int index = 0; index < changes.size(); index++) { ChangeInfo change = changes.get(index); System.out.println(change.subject); System.out.println("Project : " + change.project); // System.out.println("Branch : " + change.branch); System.out.println("Url : " + gerritProperties.namedServerUrl + "/#/c/" + change._number); System.out.println(); } } }
35.314286
96
0.724919
7896f84ff1e891f56465866aef0d81c1e9f62e30
5,056
package net.whg.we.ui; import net.whg.we.utils.ComponentList; import net.whg.we.utils.ObjectPool; import net.whg.we.utils.Poolable; public class UIStack { private ComponentList<UIComponent> _components = new ComponentList<>(); private ObjectPool<ComponentAction> _componentActions = new ObjectPool<UIStack.ComponentAction>() { @Override protected ComponentAction build() { return new ComponentAction(); } }; private boolean _running = false; public void addComponent(UIComponent component) { if (component == null) return; if (!_running) _components.addInstant(component); else _components.add(component); component.init(); } public void removeComponent(UIComponent component) { if (component == null) return; if (!_running) _components.removeInstant(component); else _components.remove(component); if (!component.isDisposed()) component.dispose(); } public void endFrame() { _components.endFrame(); } public void update() { try { _running = true; for (UIComponent component : _components) { if (component.isDisposed()) removeComponent(component); else component.update(); } endFrame(); } finally { _running = false; } } public void updateFrame() { try { _running = true; for (UIComponent component : _components) { if (component.isDisposed()) removeComponent(component); else component.updateFrame(); } endFrame(); } finally { _running = false; } } public void render() { try { _running = true; for (UIComponent component : _components) { if (component.isDisposed()) removeComponent(component); else component.render(); } endFrame(); } finally { _running = false; } } public void dispose() { try { _running = true; for (UIComponent component : _components) { if (!component.isDisposed()) component.dispose(); } _components.clearPending(); } finally { _running = false; } } public void sendToFront(UIComponent comp) { if (!_running) { ComponentAction action = _componentActions.get(); action.set(comp, ComponentAction.SEND_TO_FRONT).run(); _componentActions.put(action); return; } _components.preformComponentAction( _componentActions.get().set(comp, ComponentAction.SEND_TO_FRONT)); } public void sendToBack(UIComponent comp) { if (!_running) { ComponentAction action = _componentActions.get(); action.set(comp, ComponentAction.SEND_TO_BACK).run(); _componentActions.put(action); return; } _components.preformComponentAction( _componentActions.get().set(comp, ComponentAction.SEND_TO_BACK)); } public void moveForward(UIComponent comp) { if (!_running) { ComponentAction action = _componentActions.get(); action.set(comp, ComponentAction.MOVE_FORWARD).run(); _componentActions.put(action); return; } _components.preformComponentAction( _componentActions.get().set(comp, ComponentAction.MOVE_FORWARD)); } public void moveBackward(UIComponent comp) { if (!_running) { ComponentAction action = _componentActions.get(); action.set(comp, ComponentAction.MOVE_BACKWARD).run(); _componentActions.put(action); return; } _components.preformComponentAction( _componentActions.get().set(comp, ComponentAction.MOVE_BACKWARD)); } public int size() { return _components.size(); } public class ComponentAction implements Runnable, Poolable { private static final int SEND_TO_FRONT = 0; private static final int SEND_TO_BACK = 1; private static final int MOVE_FORWARD = 2; private static final int MOVE_BACKWARD = 3; private UIComponent _component; private int _action; @Override public void init() { } @Override public void dispose() { _component = null; } public ComponentAction set(UIComponent component, int action) { _component = component; _action = action; return this; } @Override public void run() { try { if (_component == null || _component.isDisposed()) return; int compIndex = _components.indexOf(_component); if (compIndex == -1) return; switch (_action) { case SEND_TO_FRONT: _components.removeInstant(_component); _components.add(_components.size(), _component); break; case SEND_TO_BACK: _components.removeInstant(_component); _components.add(0, _component); break; case MOVE_FORWARD: if (compIndex < _components.size() - 1) { _components.removeInstant(_component); _components.add(compIndex + 1, _component); } break; case MOVE_BACKWARD: if (compIndex > 0) { _components.removeInstant(_component); _components.add(compIndex - 1, _component); } break; default: throw new IllegalStateException("Unknown component action!"); } } finally { _componentActions.put(this); } } } }
18.588235
72
0.668513
e7cf93508bbea134e4be34a9dcbe8b224c58851a
275
package benchmarkdp.datagenerator.generator.ocl; import benchmarkdp.datagenerator.core.ModelType; import benchmarkdp.datagenerator.core.TestCase; public interface OCLEvaluatorInterface { public ModelType getModelType(); public void evaluateTestModel(TestCase tm); }
21.153846
48
0.829091
53f84ae3783150d8014426e2b2e830bb2bc8ac45
3,832
package com.wisdom.acm.sys.mapper; import com.wisdom.acm.sys.po.SysOrgPo; import com.wisdom.acm.sys.vo.ProjectTeamUserVo; import com.wisdom.acm.sys.vo.SectionTreeVo; import com.wisdom.acm.sys.vo.SectionVo; import com.wisdom.acm.sys.vo.SysOrgUserVo; import com.wisdom.base.common.mapper.CommMapper; import com.wisdom.base.common.vo.GeneralVo; import com.wisdom.base.common.vo.sys.SectionProjectVo; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * 标段-数据处理 */ public interface SectionMapper extends CommMapper<SysOrgPo> { /** * 获取标段项目信息 * @param type org/section * @param projectIds 项目IDS * @return */ List<SectionProjectVo> selectSectionProjectVos(@Param("type") String type, @Param("projectIds") List<Integer> projectIds); /** * 根据项目ID查询出顶层业主单位集合 * @param projectId 项目ID * @return */ List<SectionTreeVo> selectOwnerOrgListByProjectId(@Param("projectId") Integer projectId); /** * 获取项目某类型团队下的团队成员 * @param projectId * @param orgType * @param userId * @return */ List<ProjectTeamUserVo> selectProjectTreamUserList(@Param("projectId")int projectId, @Param("orgType")String orgType, @Param("userId")Integer userId); /** * 查询组织用户信息 * @param projectId 项目ID * @param userId 用户ID * @return */ List<SysOrgUserVo> selectSysOrgUserList(@Param("projectId") Integer projectId, @Param("userId") Integer userId); /** * 查询组织用户信息 * @param orgId * @return */ List<SysOrgUserVo> selectSysOrgUserVoList(@Param("orgId") Integer orgId); /** * 查询组织用户信息 * @param orgId * @param userId * @return */ SysOrgUserVo selectSysOrgUserVo(@Param("orgId") Integer orgId, @Param("userId") Integer userId); /** * 根据当前用户的ID和项目ID,查询该用户能直接看到的该项目下的标段信息(业主可以看所有的标段,非业主只能看到用户相关的标段) * @param userId 用户ID * @param projectId 项目ID * @return List<SectionTreeVo> 标段信息集合 */ List<SectionTreeVo> selectSectionByUserIdAndProjectId(@Param("userId") Integer userId, @Param("projectId") Integer projectId); /** * 获取团队下的子级团队信息 * @param parentIds 父级IDS * @param type org/单位 section/标段 * @return List<SectionTreeVo> 信息集合 */ List<SectionTreeVo> selectSubSectionByParentIds(@Param("parentIds") List<Integer> parentIds, @Param("type") String type); /** * 获取标段信息 * @param ids 标段IDS * @return */ List<SectionVo> selectSectionByIds(@Param("ids") List<Integer> ids); /** * 获取标段信息 * @param projectId 项目ID * @param key 关键字 * @return */ List<SectionVo> selectSectionByProjectId(@Param("projectId") Integer projectId, @Param("key") String key); /** * 根据条件查询标段 * @param mapWhere * @return */ List<SectionVo> selectSections(Map<String,Object> mapWhere); /** * 获取项目团队VO * @param id 团队ID * @return */ SectionVo selectSectionById(@Param("id") Integer id); /** * 查询项目团队下的角色 * @param projectId * @param userId * @return */ List<GeneralVo> queryTeamRoles(@Param("projectId") Integer projectId, @Param("userId") Integer userId); /** * 根据项目ID ,用户ID查询该用户参与的标段IDS * @param userId * @return */ List<Integer> selectSectUserOrgIdsByUId(@Param("projectId") Integer projectId,@Param("userId") Integer userId); /** * 查询与监理标段有关的施工标 * @param sectionTreeVoList * @return */ List<SectionTreeVo> selectSgSectionByJls(@Param("jlbList") List<SectionTreeVo> sectionTreeVoList); /** * 查询施工监理对应表数据 * @param mapWhere * @return */ List<Map<String,Object>> selectSgJlRelat(Map<String,Object> mapWhere); List<Integer> querySectionIdsParams(int projectId, int orgId); }
26.797203
154
0.652401
9171b9f52790e1c4b6e38763f9c298e6ac4882a8
3,605
package tech.quantit.northstar.strategy.api.indicator; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.springframework.util.StringUtils; import lombok.extern.slf4j.Slf4j; import tech.quantit.northstar.strategy.api.BarDataAware; import tech.quantit.northstar.strategy.api.model.TimeSeriesValue; import tech.quantit.northstar.strategy.api.utils.collection.RingArray; import xyz.redtorch.pb.CoreField.BarField; /** * 行情指标抽象类 * @author KevinHuangwl * */ @Slf4j public abstract class Indicator implements BarDataAware { /** * 指标历史记录 * 采用环型数组记录 */ private RingArray<TimeSeriesValue> refVals; /** * 指标取值类型 */ private ValueType valType; private String unifiedSymbol; private int size; protected Indicator(String unifiedSymbol, int size, ValueType valType) { refVals = new RingArray<>(size); for(int i=0; i<size; i++) { refVals.update(new TimeSeriesValue(0, 0)); } this.unifiedSymbol = unifiedSymbol; this.valType = valType; this.size = size; } /** * 获取指标回溯值 * @param numOfStepBack 回溯步长。0代表当前值,正数代表从近到远N个周期前的值,负数代表从远到近N个周期的值 * 例如有一个记录集 [77,75,80,99], 当前指针是2,即值为80。 * 当回溯步长为0时,返回80; * 当回溯步长为1时,返回75; * 当回溯步长为2时,返回77; * 当回溯步长为3时,返回99; * 当回溯步长为-1时,返回99; * 如此类推 * @return */ public double value(int numOfStepBack) { if(Math.abs(numOfStepBack) > size) { throw new IllegalArgumentException("回溯步长超过记录长度"); } return refVals.get(-numOfStepBack).getValue(); } /** * 获取指标回溯值 * @param time 指标值对应的时间戳 * @return */ public Optional<Double> valueOn(long time){ Map<Long, Double> valMap = new HashMap<>(); for(Object obj : refVals.toArray()) { TimeSeriesValue val = (TimeSeriesValue) obj; valMap.put(val.getTimestamp(), val.getValue()); } return Optional.ofNullable(valMap.get(time)); } @Override public void onBar(BarField bar) { if(!bar.getUnifiedSymbol().equals(unifiedSymbol)) { return; } log.trace("{} -> {}", this, bar); TimeSeriesValue tsv = refVals.get(1); tsv.setTimestamp(bar.getActionTimestamp()); switch(valType) { case HIGH -> tsv.setValue(updateVal(bar.getHighPrice())); case CLOSE -> tsv.setValue(updateVal(bar.getClosePrice())); case LOW -> tsv.setValue(updateVal(bar.getLowPrice())); case OPEN -> tsv.setValue(updateVal(bar.getOpenPrice())); case OPEN_INTEREST -> tsv.setValue(updateVal(bar.getOpenInterestDelta())); case VOL -> tsv.setValue(updateVal(bar.getVolumeDelta())); default -> throw new IllegalArgumentException("Unexpected value: " + valType); } refVals.update(tsv); } public TimeSeriesValue highestVal() { TimeSeriesValue highest = null; for(Object obj : refVals.toArray()) { if(highest == null) { highest = (TimeSeriesValue) obj; } else { highest = highest.compareTo((TimeSeriesValue) obj) > 0 ? highest : (TimeSeriesValue) obj; } } return highest; } public TimeSeriesValue lowestVal() { TimeSeriesValue lowest = null; for(Object obj : refVals.toArray()) { if(lowest == null) { lowest = (TimeSeriesValue) obj; } else { lowest = lowest.compareTo((TimeSeriesValue) obj) < 0 ? lowest : (TimeSeriesValue) obj; } } return lowest; } /** * 指标更新值 * @param newVal * @return */ protected abstract double updateVal(double newVal); /** * 指标取值类型 * @author KevinHuangwl * */ public enum ValueType { /** * 最高价 */ HIGH, /** * 最低价 */ LOW, /** * 开盘价 */ OPEN, /** * 收盘价 */ CLOSE, /** * 成交量 */ VOL, /** * 持仓量 */ OPEN_INTEREST; } }
21.716867
93
0.672954
9aed1c64677058d0a94a1ab6d69ed0d4c209fcec
302
package no.nav.foreldrepenger.mottak.infotrygd; import no.nav.vedtak.exception.IntegrasjonException; import no.nav.vedtak.feil.Feil; public class InfotrygdPersonIkkeFunnetException extends IntegrasjonException { public InfotrygdPersonIkkeFunnetException(Feil feil) { super(feil); } }
27.454545
78
0.798013
942cfec12504ef2fa32bfbc2f5c41b814aeaf0eb
2,407
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import javax.swing.JFileChooser; import javax.crypto.Cipher; import javax.crypto.CipherOutputStream; import javax.crypto.spec.SecretKeySpec; import javax.swing.JOptionPane; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class ImgCry1 extends HttpServlet { // JDK 1.6 and above only // The doGet() runs once per HTTP GET request to this servlet. @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the MIME type for the response message response.setContentType("text/html"); // Get a output writer to write the response message into the network socket PrintWriter out = response.getWriter(); String a = request.getParameter("img"); String b = "C:\\Users\\SMP\\Desktop\\" + a; try { out.println("<html>"); out.println("<head><title>Image Encryption</title></head>"); out.println("<body>"); out.println("<h1>Image Encryption</h1>"); // Echo client's request information out.println("<p>Request URL: " + a + "</p>"); // Generate a random number upon each request out.println("<p>Random Number: <strong>" + Math.random() + "</strong></p>"); try{ FileInputStream file = new FileInputStream(b); FileOutputStream outStream = new FileOutputStream("Encrypt.jpg"); byte k[]="CooL2116NiTh5252".getBytes(); SecretKeySpec key = new SecretKeySpec(k, "AES"); Cipher enc = Cipher.getInstance("AES"); enc.init(Cipher.ENCRYPT_MODE, key); CipherOutputStream cos = new CipherOutputStream(outStream, enc); byte[] buf = new byte[1024]; int read; while((read=file.read(buf))!=-1){ cos.write(buf,0,read); } file.close(); outStream.flush(); cos.close(); out.println("The file encrypted successfully in bin folder"); out.println("<form method='get' action='http://localhost:9999/password/imgcry2'><br><input type='submit' value='Decrypt'></form>"); }catch(Exception e){ out.println(""+ e); } out.println("</body></html>"); }finally { out.close(); // Always close the output writer } } }
34.884058
136
0.635231
36646bf9b974c80528ba5cee41eb4887f4f01c1b
2,486
package entities; import java.util.ArrayList; public class Order { // ATTRIBUTES int id; Client client; // Foodstuffs breakfest; // Foodstuffs appetizers; // Foodstuffs principal; // Foodstuffs dessert; ArrayList<Foodstuffs> ItensOrdered = new ArrayList<Foodstuffs>(); float value = 0; String paymentMethodString; // METHODS public void add(Foodstuffs food) { ItensOrdered.add(food); System.out.println(food.getDescription() + " added."); } public void remove(Foodstuffs food) { ItensOrdered.remove(food); } public void remove(int index) { ItensOrdered.remove(ItensOrdered.get(index)); // Calls showOrders() System.out.println("Your order now is: "); showOrders(); } public int getOrdersSize() { // Shows the length of order's array return ItensOrdered.size(); } public void showOrders() { // 1) Shows the items of 'ItensOrdered's array // 2) Sums the order total cost if (ItensOrdered.size() == 0) { System.out.println("You didn't order anything."); } else { float totalCost = 0f; for (int i = 0; i < ItensOrdered.size(); i++) { // 1 System.out.println("[" + i + "] " + ItensOrdered.get(i).getDescription() + " / Cost $: " + ItensOrdered.get(i).getPrice()); totalCost += ItensOrdered.get(i).getPrice(); // this.value += ItensOrdered.get(i).getPrice(); } System.out.println("- - - - Total Cost $: " + totalCost); setValue(totalCost); } } // Setters and Getters public void setId() { // Randomly generate double rand = Math.random()*1000; rand = Math.round(rand); this.id = (int) rand; System.out.println(" |= Client: "+ client.getName() + "\n |= Order N.: " + this.getId()); } public void setPaymentMethod(String paymentMethod) { this.paymentMethodString = paymentMethod; } public final int getId() { return id; } public final Client getClient() { return client; } public final ArrayList<Foodstuffs> getItensOrdered() { return ItensOrdered; } public final float getValue() { return value; } public final void setClient(Client client) { this.client = client; } public final void setItensOrdered(ArrayList<Foodstuffs> itensOrdered) { ItensOrdered = itensOrdered; } protected final void setValue(float value) { this.value = value; } @Override public String toString() { return "- - - Reciept - - - " + "\nOrder id: " + id + "\nClient: " + client.getName() + "\nValue = " + value + "\nPayment method: " + paymentMethodString; } }
24.86
110
0.66251
fb3d2f1b396b79c6eb7793ebea6e7b5ab2a7d112
694
package org.gjgr.exam.stack; /** * File Name : arithmetic4j - org.gjgr.exam.stack * CopyRright (c) 1949-xxxx: * File Number: * Author:gwd * Date:on 9/9/2017 * Modify:gwd * Time : * Comment: * Description: * Version: */ public final class HanoiDemo { public static void hanoi(Integer n,Character A,Character B,Character C){ if(n==1){ move(A,C); } hanoi(n-1,A,C,B); move(A,C); hanoi(n-1,B,A,C); } public static void move(Character A,Character C){ System.out.println("move"); } public static void main(String[] args){ hanoi(3,new Character('A'),new Character('B'),new Character('C')); } }
20.411765
77
0.579251
fce82e1ad1b3d17f53a977ca1e1fccd0d3b0f8f1
3,689
/* * Copyright 2002-2019 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.http.server; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.util.FileCopyUtils; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma * @author Rossen Stoyanchev * @author Juergen Hoeller */ public class ServletServerHttpResponseTests { private ServletServerHttpResponse response; private MockHttpServletResponse mockResponse; @Before public void create() throws Exception { mockResponse = new MockHttpServletResponse(); response = new ServletServerHttpResponse(mockResponse); } @Test public void setStatusCode() throws Exception { response.setStatusCode(HttpStatus.NOT_FOUND); assertEquals("Invalid status code", 404, mockResponse.getStatus()); } @Test public void getHeaders() throws Exception { HttpHeaders headers = response.getHeaders(); String headerName = "MyHeader"; String headerValue1 = "value1"; headers.add(headerName, headerValue1); String headerValue2 = "value2"; headers.add(headerName, headerValue2); headers.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8)); response.close(); assertTrue("Header not set", mockResponse.getHeaderNames().contains(headerName)); List<String> headerValues = mockResponse.getHeaders(headerName); assertTrue("Header not set", headerValues.contains(headerValue1)); assertTrue("Header not set", headerValues.contains(headerValue2)); assertEquals("Invalid Content-Type", "text/plain;charset=UTF-8", mockResponse.getHeader("Content-Type")); assertEquals("Invalid Content-Type", "text/plain;charset=UTF-8", mockResponse.getContentType()); assertEquals("Invalid Content-Type", "UTF-8", mockResponse.getCharacterEncoding()); } @Test public void preExistingHeadersFromHttpServletResponse() { String headerName = "Access-Control-Allow-Origin"; String headerValue = "localhost:8080"; this.mockResponse.addHeader(headerName, headerValue); this.response = new ServletServerHttpResponse(this.mockResponse); assertEquals(headerValue, this.response.getHeaders().getFirst(headerName)); assertEquals(Collections.singletonList(headerValue), this.response.getHeaders().get(headerName)); assertTrue(this.response.getHeaders().containsKey(headerName)); assertEquals(headerValue, this.response.getHeaders().getFirst(headerName)); assertEquals(headerValue, this.response.getHeaders().getAccessControlAllowOrigin()); } @Test public void getBody() throws Exception { byte[] content = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(content, response.getBody()); assertArrayEquals("Invalid content written", content, mockResponse.getContentAsByteArray()); } }
35.133333
107
0.777446
f138eb0af9b48d14ac2714e1bd1ffacd35069a0b
446
package com.sallyf.sallyf.Authentication.DeniedHandler; import com.sallyf.sallyf.Authentication.SecurityDeniedHandler; import com.sallyf.sallyf.Container.Container; import com.sallyf.sallyf.Exception.HttpException; import com.sallyf.sallyf.Server.Status; public class ForbiddenHandler implements SecurityDeniedHandler { @Override public Object apply(Container container) { throw new HttpException(Status.FORBIDDEN); } }
27.875
62
0.800448
ba9efd9264e68b5bc9c0e51c7c6457df004f597a
536
package com.ay.test; import org.junit.Test; import org.springframework.data.redis.core.RedisTemplate; import javax.annotation.Resource; /** * redis缓存测试 * * @author Ay * @create 2018/07/08 **/ public class RedisTest extends BaseJunit4Test { @Resource private RedisTemplate redisTemplate; @Test public void testRedis() { redisTemplate.opsForValue().set("name", "ay"); String name = (String) redisTemplate.opsForValue().get("name"); System.out.println("value of name is:" + name); } }
20.615385
71
0.675373
cce48811927bc9dabef09cfcc857700243cbe7d5
5,281
package com.exiro.buildingList.delivery.agorashop; import com.exiro.buildingList.Building; import com.exiro.buildingList.BuildingCategory; import com.exiro.buildingList.delivery.Agora; import com.exiro.buildingList.delivery.AgoraShop; import com.exiro.object.Case; import com.exiro.object.City; import com.exiro.object.ObjectType; import com.exiro.object.Resource; import com.exiro.render.IsometricRender; import com.exiro.sprite.BuildingSprite; import com.exiro.sprite.Sprite; import com.exiro.systemCore.GameManager; import com.exiro.utils.Point; import java.awt.*; import java.util.ArrayList; public class AgoraShopBuilding extends Building { Agora agora; AgoraShop shop; int reserve, distribution; Case mcase; ArrayList<Resource> resourcesPossible; boolean buying = false; public AgoraShopBuilding(AgoraShop shop, ObjectType type) { super(false, type, BuildingCategory.FOOD, 0, 4, 16, 10, 0, 0, 2, 2, null, false, GameManager.currentCity, 0); this.shop = shop; reserve = distribution = 0; } @Override public ArrayList<Case> getPlace(int xPos, int yPos, int yLenght, int xLenght, City city) { if (this instanceof EmptyShop) { if (city.getMap().getCase(xPos, yPos) != null && city.getMap().getCase(xPos, yPos).getObject() != null && city.getMap().getCase(xPos, yPos).getObject() instanceof Agora) { ArrayList<Case> c = new ArrayList<>(); c.add(city.getMap().getCase(xPos, yPos)); return c; } } if (city.getMap().getCase(xPos, yPos) != null && city.getMap().getCase(xPos, yPos).getObject() != null && city.getMap().getCase(xPos, yPos).getObject() instanceof EmptyShop) { ArrayList<Case> c = new ArrayList<>(); c.add(city.getMap().getCase(xPos, yPos)); c.add(city.getMap().getCase(xPos, yPos)); c.add(city.getMap().getCase(xPos, yPos)); c.add(city.getMap().getCase(xPos, yPos)); return c; } return null; } @Override public boolean build(int xPos, int yPos) { ArrayList<Case> cases = getPlace(xPos, yPos, 0, 0, city); if (cases != null) { Agora agora = (Agora) cases.get(0).getObject(); this.agora = agora; if (agora.addShop(this)) { BuildingSprite bs = new BuildingSprite("Zeus_General", 3, shop.getId() + 1, 1, city, this); addSprite(bs); setxPos(xPos); setyPos(yPos); setXB(getxPos()); setYB(getyPos()); city.addBuilding(this); city.addObj(this); for (Case c : cases) { c.setOccupied(true); c.setObject(this); c.setMainCase(false); } city.getMap().getCase(xPos, yPos).setMainCase(true); this.setMainCase(city.getMap().getCase(getxPos(), getyPos())); return true; } } return false; } @Override public void Render(Graphics g, int camX, int camY) { com.exiro.utils.Point p = IsometricRender.TwoDToIsoTexture(new Point(getxPos(), (getyPos())), getWidth(), getHeight(), 2); g.drawImage(getImg(), camX + (int) p.getX(), camY + (int) p.getY(), null); if (reserve > 0) { bsprites.get(0).Render(g, camX, camY); if (isWorking()) { bsprites.get(1).Render(g, camX, camY); } } //g.drawString(getPop() + "/" + getPopMax() + " " + reserve, camX + (int) p.getX() + 30, camY + (int) p.getY() + 30); /* if(getPop()>0 && isActive()){ bsprites.get(1).Render(g,camX,camY); } */ } public ArrayList<Resource> getResources() { return resourcesPossible; } public boolean needRefuel() { return (reserve < 100 && !buying); } public void refuel(int amount) { reserve += amount; } public void setBuying(boolean buying) { this.buying = buying; } @Override public void processSprite(double delta) { for (Sprite s : sprites) { if (isActive() && getPop() > 0) s.process(delta); } } @Override public void populate(double deltaTime) { } @Override protected void addPopulation() { } public void setMcase(Case mcase) { this.mcase = mcase; this.setxPos(mcase.getxPos()); this.setyPos(mcase.getyPos()); setXB(mcase.getxPos()); setYB(mcase.getyPos()); } public AgoraShop getShop() { return shop; } public void setShop(AgoraShop shop) { this.shop = shop; } public int getReserve() { return reserve; } public void setReserve(int reserve) { this.reserve = reserve; } public int getDistribution() { return distribution; } public void setDistribution(int distribution) { this.distribution = distribution; } public Agora getAgora() { return agora; } public void setAgora(Agora agora) { this.agora = agora; } }
28.701087
183
0.571293
0ce779498c5666d52c070908a8749d069e430e60
505
package com.lanluyug.leetCode.algorithm.simple; import java.util.HashMap; import java.util.Map; public class Unique { public boolean isUnique(String astr) { Map map = new HashMap<>(); boolean flag = true; for (int i = 0; i < astr.length(); i++) { char s = astr.charAt(i); if(map.get(s) == null){ map.put(s,0); }else{ flag = false; break; } } return flag; } }
22.954545
49
0.481188
c932d4dc1ec95753adecfa41d52fa0911b55698a
4,679
package org.sagebionetworks.web.client.widget.table.v2.results.facets; import static org.sagebionetworks.repo.model.table.TableConstants.NULL_VALUE_KEYWORD; import static org.sagebionetworks.web.client.DisplayUtils.DO_NOTHING_CLICKHANDLER; import java.util.HashSet; import java.util.Set; import org.sagebionetworks.repo.model.table.ColumnType; import org.sagebionetworks.repo.model.table.FacetColumnRequest; import org.sagebionetworks.repo.model.table.FacetColumnResultValueCount; import org.sagebionetworks.repo.model.table.FacetColumnResultValues; import org.sagebionetworks.repo.model.table.FacetColumnValuesRequest; import org.sagebionetworks.web.client.PortalGinInjector; import org.sagebionetworks.web.client.utils.CallbackP; import org.sagebionetworks.web.client.widget.table.v2.results.cell.EntityIdCellRenderer; import org.sagebionetworks.web.client.widget.table.v2.results.cell.UserIdCellRenderer; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class FacetColumnResultValuesWidget implements IsWidget, FacetColumnResultValuesView.Presenter { public static final String SHOW_ALL = "Show all "; public static final String UNSPECIFIED = "Not set"; public static final String EMPTY_STRING = "(empty string)"; FacetColumnResultValuesView view; FacetColumnResultValues facet; CallbackP<FacetColumnRequest> onFacetRequest; Set<String> facetValues; public static final int MAX_VISIBLE_FACET_VALUES = 5; PortalGinInjector ginInjector; @Inject public FacetColumnResultValuesWidget(FacetColumnResultValuesView view, PortalGinInjector ginInjector) { this.view = view; this.ginInjector = ginInjector; view.setPresenter(this); } public void configure(FacetColumnResultValues facet, ColumnType columnType, CallbackP<FacetColumnRequest> onFacetRequest) { boolean isUserIdColumnType = ColumnType.USERID.equals(columnType); boolean isEntityIdColumnType = ColumnType.ENTITYID.equals(columnType); view.clearValues(); facetValues = new HashSet<String>(); this.facet = facet; this.onFacetRequest = onFacetRequest; view.setColumnName(facet.getColumnName()); int i = 0; int max = MAX_VISIBLE_FACET_VALUES; for (int j = MAX_VISIBLE_FACET_VALUES; j < facet.getFacetValues().size(); j++) { // if any facet is selected beyond the max visible count, then show them all if (facet.getFacetValues().get(j).getIsSelected()) { max = Integer.MAX_VALUE; break; } } for (FacetColumnResultValueCount valueCount : facet.getFacetValues()) { if (valueCount.getIsSelected()) { facetValues.add(valueCount.getValue()); } Widget displayWidget; if (valueCount.getValue() == null || NULL_VALUE_KEYWORD.equals(valueCount.getValue())) { displayWidget = view.getSpanWithText(UNSPECIFIED); } else if (isUserIdColumnType) { displayWidget = getUserBadge(valueCount.getValue()); } else if (isEntityIdColumnType) { displayWidget = getEntityBadge(valueCount.getValue()); } else { displayWidget = view.getSpanWithText(valueCount.getValue()); } if (i < max) { view.addValue(valueCount.getIsSelected(), displayWidget, valueCount.getCount(), valueCount.getValue()); } else { view.addValueToOverflow(valueCount.getIsSelected(), displayWidget, valueCount.getCount(), valueCount.getValue()); } i++; } if (facet.getFacetValues().size() > max) { view.setShowAllButtonText(SHOW_ALL + facet.getFacetValues().size()); view.setShowAllButtonVisible(true); } else { view.setShowAllButtonVisible(false); } } public Widget getUserBadge(String userId) { UserIdCellRenderer userBadge = ginInjector.getUserIdCellRenderer(); userBadge.setValue(userId, DO_NOTHING_CLICKHANDLER); return userBadge.asWidget(); } public Widget getEntityBadge(String entityId) { EntityIdCellRenderer entityBadge = ginInjector.getEntityIdCellRenderer(); boolean hideIfLoadError = true; entityBadge.setValue(entityId, DO_NOTHING_CLICKHANDLER, hideIfLoadError); return entityBadge.asWidget(); } @Override public void onFacetChange(String facetValue) { FacetColumnValuesRequest facetColumnValuesRequest = new FacetColumnValuesRequest(); facetColumnValuesRequest.setColumnName(facet.getColumnName()); if (facetValues.contains(facetValue)) { facetValues.remove(facetValue); } else { facetValues.add(facetValue); } facetColumnValuesRequest.setFacetValues(facetValues); onFacetRequest.invoke(facetColumnValuesRequest); } @Override public Widget asWidget() { return view.asWidget(); } }
38.352459
124
0.783928
51f701183ee058b32159db4b6ab1b467215d2805
1,587
package com.egangotri.monierWilliams.dao.vo; import java.util.Calendar; public class ClickLogMaster implements java.io.Serializable { private long id; private String module; private Calendar time; private String ipAddress; private String country; private String city; private String region; private String searchTerms; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getModule() { return module; } public void setModule(String module) { this.module = module; } public Calendar getTime() { return time; } public void setTime(Calendar time) { this.time = time; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getSearchTerms() { return searchTerms; } public void setSearchTerms(String searchTerms) { this.searchTerms = searchTerms; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } }
15.259615
59
0.574669
0e4e8090b2b63c26412a887b0f8c14474cacfd64
2,324
package com.lambdaschool.crudyrestauarants.controllers; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.lambdaschool.crudyrestauarants.models.Restaurant; import com.lambdaschool.crudyrestauarants.services.RestaurantService; @RestController @RequestMapping("/api/restaurants") public class RestaurantController { @Autowired private RestaurantService service; // GET /api/restaurants @GetMapping(value = "", produces = { "application/json" }) public ResponseEntity<?> listAllRestaurants() { List<Restaurant> myList = service.findall(); return new ResponseEntity<>(myList, HttpStatus.OK); } // GET /api/restaurants/{id} @GetMapping(value = "/{id}", produces = { "application/json" }) public ResponseEntity<?> getRestaurantById(@PathVariable long id) { Restaurant myRestaurant = service.findById(id); return new ResponseEntity<>(myRestaurant, HttpStatus.OK); } // POST /api/restaurants/ @PostMapping(value = "", consumes = { "application/json" }) public ResponseEntity<?> addNewRestaurant(@Valid @RequestBody Restaurant newRestaurant) { service.save(newRestaurant); return new ResponseEntity<>(HttpStatus.CREATED); } // PUT /api/restaurants/{id} @PutMapping(value = "/{id}", consumes = { "application/json" }) public ResponseEntity<?> updateRestaurant(@Valid @RequestBody Restaurant restaurant, @PathVariable long id) { service.update(restaurant, id); return new ResponseEntity<>(HttpStatus.OK); } // DELETE /api/restaurants/{id} @DeleteMapping(value = "/{id}") public ResponseEntity<?> deleteRestaurantById(@PathVariable long id) { service.delete(id); return new ResponseEntity<>(HttpStatus.OK); } }
34.686567
90
0.776678
076b8171c555214f75ab1b76867ca13f7c8200b2
2,044
package ru.mdashlw.hypixel.pit.stats.util; import com.mojang.authlib.GameProfile; import java.lang.ref.WeakReference; import java.util.List; import java.util.concurrent.ForkJoinPool; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTUtil; import net.minecraft.tileentity.TileEntitySkull; public final class ItemStackUtils { private ItemStackUtils() { } public static ItemStack withDisplay(final ItemStack itemStack, final String name, final List<String> lore) { NBTTagCompound tag = itemStack.getTagCompound(); if (tag == null) { tag = new NBTTagCompound(); itemStack.setTagCompound(tag); } if (!tag.hasKey("display", 10)) { tag.setTag("display", new NBTTagCompound()); } final NBTTagCompound displayTag = tag.getCompoundTag("display"); displayTag.setString("Name", name); displayTag.setTag("Lore", NbtUtils.asStringTagList(lore)); return itemStack; } public static ItemStack withNoAttributeModifiers(final ItemStack itemStack) { NBTTagCompound tag = itemStack.getTagCompound(); if (tag == null) { tag = new NBTTagCompound(); itemStack.setTagCompound(tag); } tag.setTag("AttributeModifiers", new NBTTagList()); return itemStack; } public static ItemStack withLazySkullOwner(final ItemStack itemStack, final String owner) { NBTTagCompound tag = itemStack.getTagCompound(); if (tag == null) { tag = new NBTTagCompound(); itemStack.setTagCompound(tag); } final WeakReference<NBTTagCompound> tagRef = new WeakReference<>(tag); ForkJoinPool.commonPool().execute(() -> { GameProfile gameProfile = new GameProfile(null, owner); gameProfile = TileEntitySkull.updateGameprofile(gameProfile); final NBTTagCompound t = tagRef.get(); if (t != null) { t.setTag("SkullOwner", NBTUtil.writeGameProfile(new NBTTagCompound(), gameProfile)); } }); return itemStack; } }
27.621622
110
0.706947
1e72601c62febb773080352aca582c479747f59f
1,762
package org.checkerframework.framework.qual; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation can be used two ways: * * <p>1. As a meta-annotation indicating that an annotation type prevents whole-program inference. * For example, if the definition of {@code @Inject} is meta-annotated with * {@code @IgnoreInWholeProgramInference}:<br> * <tt>@IgnoreInWholeProgramInference</tt><br> * <tt>@interface Inject { }</tt><br> * then no type qualifier will be inferred for any field annotated by {@code @Inject}. * * <p>This is appropriate for fields that are set reflectively, so there are no calls in client code * that type inference can learn from. Examples of qualifiers that should be meta-annotated with * {@code @IgnoreInWholeProgramInference} include <a * href="https://docs.oracle.com/javaee/7/api/javax/inject/Inject.html">{@code @Inject}</a>, <a * href="https://docs.oracle.com/javaee/7/api/javax/inject/Singleton.html">{@code @Singleton}</a>, * and <a * href="https://types.cs.washington.edu/plume-lib/api/plume/Option.html">{@code @Option}</a>. * * <p>2. As a field annotation indicating that no type qualifier will be inferred for the field it * annotates. * * @see * org.checkerframework.common.wholeprograminference.WholeProgramInferenceScenes#updateInferredFieldType * @checker_framework.manual #whole-program-inference-ignores-some-code Whole-program inference * ignores some code */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD}) public @interface IgnoreInWholeProgramInference {}
45.179487
108
0.76277
f52a6ab42a0816f433c6cf7f443f84d02f7f239e
7,922
package com.tkulpa.react.Zendrive; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.support.v4.app.NotificationCompat; //import com.zendrive.sdk.ZendriveLocationSettingsResult; /** * Utility to create notifications to show to the user when the Zendrive SDK has something * interesting to report. */ public class NotificationUtility { // Notification related constants public static final int FOREGROUND_MODE_NOTIFICATION_ID = 98; public static final int LOCATION_DISABLED_NOTIFICATION_ID = 99; public static final int LOCATION_PERMISSION_DENIED_NOTIFICATION_ID = 100; // channel keys (id) are used to sort the channels in the notification // settings page. Meaningful ids and descriptions tell the user // about which notifications are safe to toggle on/off for the application. private static final String FOREGROUND_CHANNEL_KEY = "Foreground"; private static final String LOCATION_CHANNEL_KEY = "Location"; /** * Create a notification when location permission is denied to the application. * @param context App context * @return the created notifcation. */ // public static Notification createLocationPermissionDeniedNotification(Context context) { // createNotificationChannels(context); // // TODO: The click intent should not point to location settings. Perhaps we can load // // the app permissions tab. // Intent callGPSSettingIntent = new Intent( // android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); // PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, // callGPSSettingIntent, 0); // Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.notification_template_icon_bg); // // return new NotificationCompat.Builder(context.getApplicationContext(), LOCATION_CHANNEL_KEY) // .setContentTitle(context.getResources().getString(R.string.location_permission_denied)) // .setTicker(context.getResources().getString(R.string.location_permission_denied)) // .setContentText(context.getResources().getString(R.string.grant_location_permission)) // .setSmallIcon(R.drawable.notification_template_icon_bg) // .setPriority(NotificationCompat.PRIORITY_MAX) // .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false)) // .setCategory(Notification.CATEGORY_ERROR) // .setContentIntent(pendingIntent) // .build(); // } /** * Create a notification when high accuracy location is disabled on the device. * @param context App context * @param settingsResult to get potential resolution from play services * @return the created notifcation. */ // public static Notification createLocationSettingDisabledNotification(Context context, // ZendriveLocationSettingsResult settingsResult) { // createNotificationChannels(context); // if (BuildConfig.DEBUG && settingsResult.isSuccess()) { // throw new AssertionError("Only expected failed settings result"); // } // // TODO: use the result from the callback and show appropriate message and intent // Intent callGPSSettingIntent = new Intent( // android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); // PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, // callGPSSettingIntent, 0); // Bitmap icon = BitmapFactory.decodeResource(context.getResources(), // R.drawable.notification_template_icon_bg); // return new NotificationCompat.Builder(context.getApplicationContext(), LOCATION_CHANNEL_KEY) // .setContentTitle(context.getResources().getString(R.string.location_disabled)) // .setTicker(context.getResources().getString(R.string.location_disabled)) // .setContentText(context.getResources().getString(R.string.enable_location)) // .setSmallIcon(R.drawable.notification_template_icon_bg) // .setPriority(NotificationCompat.PRIORITY_MAX) // .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false)) // .setContentIntent(pendingIntent) // .setCategory(Notification.CATEGORY_ERROR) // .build(); // } /** * Create a notification that is displayed when the Zendrive SDK * detects a possible drive. * * @param context App context * @return the created notifcation. */ public static Notification createMaybeInDriveNotification(Context context) { createNotificationChannels(context); // // suppresses deprecated warning for setPriority(PRIORITY_MIN) // //noinspection deprecation return new NotificationCompat.Builder(context, FOREGROUND_CHANNEL_KEY) .setSmallIcon(R.drawable.notification_template_icon_bg) .setContentTitle(context.getResources().getString(R.string.app_name)) .setDefaults(0) .setPriority(Notification.PRIORITY_MIN) .setCategory(Notification.CATEGORY_SERVICE) .setContentText(context.getResources().getString(R.string.possible_drive)).build(); } /** * Create a notification that is displayed when the Zendrive SDK * determines that the user is driving. * * @param context App context * @return the created notifcation. */ public static Notification createInDriveNotification(Context context) { createNotificationChannels(context); return new NotificationCompat.Builder(context, FOREGROUND_CHANNEL_KEY) .setSmallIcon(R.drawable.notification_template_icon_bg) .setContentTitle(context.getResources().getString(R.string.app_name)) .setCategory(Notification.CATEGORY_SERVICE) .setContentText(context.getResources().getString(R.string.drive_started)).build(); } private static void createNotificationChannels(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager manager = context.getSystemService(NotificationManager.class); NotificationChannel lowPriorityNotificationChannel = new NotificationChannel(FOREGROUND_CHANNEL_KEY, context.getResources().getString(R.string.trip_tracking), NotificationManager.IMPORTANCE_MIN); lowPriorityNotificationChannel.setShowBadge(false); manager.createNotificationChannel(lowPriorityNotificationChannel); NotificationChannel defaultNotificationChannel = new NotificationChannel (LOCATION_CHANNEL_KEY, context.getResources().getString(R.string.problems), NotificationManager.IMPORTANCE_DEFAULT); defaultNotificationChannel.setShowBadge(true); manager.createNotificationChannel(defaultNotificationChannel); } } // private static PendingIntent getNotificationClickIntent(Context context) { // Intent notificationIntent = new Intent(context.getApplicationContext(), SplashActivity.class); // notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // return PendingIntent.getActivity(context.getApplicationContext(), 0, // notificationIntent, 0); // } }
50.782051
124
0.69124
ff71b2f71c8f1da95a1429b32d35698e31163e75
1,041
package br.com.generation.Listas.HerancaPolimorfismo.Exercicio3; public class Item { private String nome; private int quantidade; private double preco; private static int totalItems = 0; public Item(String nome, int quantidade, double preco) { this.nome = nome; this.quantidade = quantidade; this.preco = preco; Item.totalItems += 1; } @Override public String toString() { String texto = "Nome: " + this.nome + " | " + "Quantidade: " + this.quantidade + " | Preço" + this.preco + "\n"; return texto; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public int getQuantidade() { return quantidade; } public void setQuantidade(int quantidade) { this.quantidade = quantidade; } public double getPreco() { return preco; } public void setPreco(double preco) { this.preco = preco; } public void mostrarTotal() { System.out.println("Total de itens no estoque: " + Item.totalItems); } }
20.82
73
0.650336
312a426ac78cb2bc7247ee79d7aaa26a0fc1aa60
116,859
/* * eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) 2017 eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * 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 * 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/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * Further, all user interfaces, including but not limited to citizen facing interfaces, * Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any * derived works should carry eGovernments Foundation logo on the top right corner. * * For the logo, please refer http://egovernments.org/html/logo/egov_logo.png. * For any further queries on attribution, including queries on brand guidelines, * please contact contact@egovernments.org * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org. * */ package org.egov.egf.web.actions.budget; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.apache.log4j.Logger; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.egov.commons.CChartOfAccounts; import org.egov.commons.CFinancialYear; import org.egov.commons.CFunction; import org.egov.commons.dao.FinancialYearDAO; import org.egov.eis.entity.Assignment; import org.egov.eis.service.EisCommonService; import org.egov.infra.admin.master.entity.AppConfigValues; import org.egov.infra.admin.master.service.AppConfigValueService; import org.egov.infra.config.core.ApplicationThreadLocals; import org.egov.infra.config.persistence.datasource.routing.annotation.ReadOnly; import org.egov.infra.exception.ApplicationRuntimeException; import org.egov.infra.microservice.models.Department; import org.egov.infra.validation.exception.ValidationError; import org.egov.infra.validation.exception.ValidationException; import org.egov.infra.web.struts.actions.BaseFormAction; import org.egov.infra.web.struts.annotation.ValidationErrorPage; import org.egov.infstr.services.PersistenceService; import org.egov.infstr.utils.EgovMasterDataCaching; import org.egov.model.budget.Budget; import org.egov.model.budget.BudgetDetail; import org.egov.model.budget.BudgetGroup; import org.egov.pims.commons.Designation; import org.egov.pims.commons.Position; import org.egov.services.budget.BudgetDetailService; import org.egov.services.budget.BudgetService; import org.egov.utils.Constants; import org.egov.utils.FinancialConstants; import org.egov.utils.ReportHelper; import org.hibernate.Query; import org.hibernate.type.LongType; import org.hibernate.type.StringType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.env.Environment; import net.sf.jasperreports.engine.JRException; @ParentPackage("egov") @Results(value = { @Result(name = "department-PDF", type = "stream", location = Constants.INPUT_STREAM, params = { Constants.INPUT_NAME, Constants.INPUT_STREAM, Constants.CONTENT_TYPE, "application/pdf", Constants.CONTENT_DISPOSITION, "no-cache;filename=BudgetReport.pdf" }), @Result(name = "department-XLS", type = "stream", location = Constants.INPUT_STREAM, params = { Constants.INPUT_NAME, Constants.INPUT_STREAM, Constants.CONTENT_TYPE, "application/xls", Constants.CONTENT_DISPOSITION, "no-cache;filename=BudgetReport.xls" }), @Result(name = "department-HTML", type = "stream", location = Constants.INPUT_STREAM, params = { Constants.INPUT_NAME, Constants.INPUT_STREAM, Constants.CONTENT_TYPE, "text/html" }), @Result(name = "functionwise-PDF", type = "stream", location = Constants.INPUT_STREAM, params = { Constants.INPUT_NAME, Constants.INPUT_STREAM, Constants.CONTENT_TYPE, "application/pdf", Constants.CONTENT_DISPOSITION, "no-cache;filename=BudgetReport-functionwise.pdf" }), @Result(name = "functionwise-XLS", type = "stream", location = Constants.INPUT_STREAM, params = { Constants.INPUT_NAME, Constants.INPUT_STREAM, Constants.CONTENT_TYPE, "application/xls", Constants.CONTENT_DISPOSITION, "no-cache;filename=BudgetReport-functionwise.xls" }), @Result(name = "functionwise-HTML", type = "stream", location = Constants.INPUT_STREAM, params = { Constants.INPUT_NAME, Constants.INPUT_STREAM, Constants.CONTENT_TYPE, "text/html" }), @Result(name = "functionwise-dept-HTML", type = "stream", location = Constants.INPUT_STREAM, params = { Constants.INPUT_NAME, Constants.INPUT_STREAM, Constants.CONTENT_TYPE, "text/html" }), @Result(name = "printFunctionwise", location = "budgetReport-printFunctionwise.jsp"), @Result(name = "print", location = "budgetReport-print.jsp"), @Result(name = "functionwise", location = "budgetReport-functionwise.jsp"), @Result(name = "atGlance", location = "budgetReport-atGlance.jsp"), @Result(name = "dept", location = "budgetReport-dept.jsp"), }) public class BudgetReportAction extends BaseFormAction { private static final String DEPTWISEPATH = "/reports/templates/departmentWiseBudgetReport.jasper"; private static final String FUNCTIONWISEPATH = "/reports/templates/budgetReportFunctionwise.jasper"; private static final String WORKINGCOPYFORFINALAPPROVER = "/reports/templates/budgetReportWorkingCopyForFinalApprover.jasper"; private static final String WORKINGCOPYWITHALLMOUNTS = "/reports/templates/budgetReportWorkingCopy.jasper"; private static final String WORKINGCOPYWITHONLYPROPOSALS = "/reports/templates/budgetReportWorkingCopyWithOnlyProposals.jasper"; private ReportHelper reportHelper; private static final long serialVersionUID = 1L; private InputStream inputStream; private BudgetReport budgetReport = new BudgetReport(); @Autowired private EisCommonService eisCommonService; private List budgetReportList = new ArrayList<>(); @Autowired private AppConfigValueService appConfigValuesService; private int majorCodeLength = 0; @Autowired private FinancialYearDAO financialYearDAO; @Autowired @Qualifier("budgetService") private BudgetService budgetService; private static final String EMPTYSTRING = ""; private static final String TOTALROW = "totalrow"; private static final String TOTALSTRING = "TOTAL"; private final Map<String, String> coaMap = new HashMap<String, String>(); private Map<String, String> refNoMap = new HashMap<String, String>(); private final Map<Object, BigDecimal> reAppropriationMap = new HashMap<Object, BigDecimal>(); private final List<BudgetReportView> reportStoreList = new ArrayList<BudgetReportView>(); private static Logger LOGGER = Logger.getLogger(BudgetReportAction.class); @Autowired @Qualifier("budgetDetailService") private BudgetDetailService budgetDetailService; private boolean onSaveOrForward = false; protected boolean canViewApprovedAmount = true;// shows both proposed and recommended like fmus protected boolean finalApprover = false;// shows only the recommended value like commissioner private final List<BudgetDetail> budgetDetailListForBE = new ArrayList<BudgetDetail>(); private List<BudgetDetail> budgetDetailListForRE = new ArrayList<BudgetDetail>(); private CFinancialYear financialYearForRE; private CFinancialYear financialYearForBE; private String path = FUNCTIONWISEPATH; private String isBERE = "RE"; private BudgetDetail budgetDetail; private Position pos; private Budget topBudget; private boolean departmentBudget = false; private String workFlowstateCondn = ""; @Autowired @Qualifier("persistenceService") private PersistenceService persistenceService; @Autowired private EgovMasterDataCaching masterDataCache; @Autowired private Environment environment; public boolean isDepartmentBudget() { return departmentBudget; } public void setDepartmentBudget(final boolean departmentBudget) { this.departmentBudget = departmentBudget; } public BudgetDetail getBudgetDetail() { return budgetDetail; } public void setBudgetDetail(final BudgetDetail budgetDetail) { this.budgetDetail = budgetDetail; } public void setBudgetService(final BudgetService budgetService) { this.budgetService = budgetService; } public void setFinancialYearDAO(final FinancialYearDAO financialYearDAO) { this.financialYearDAO = financialYearDAO; } public void setReportHelper(final ReportHelper reportHelper) { this.reportHelper = reportHelper; } public InputStream getInputStream() { return inputStream; } @Override public Object getModel() { return budgetReport; } @Action(value = "/budget/budgetReport-functionwise") public String functionwise() { return "functionwise"; } @Action(value = "/budget/budgetReport-atGlance") public String atGlance() { return "atGlance"; } public BudgetReportAction() { addRelatedEntity("department", Department.class); addRelatedEntity("function", CFunction.class); addRelatedEntity("financialYear", CFinancialYear.class); } @Override public void prepare() { super.prepare(); addDropdownData("departmentList", masterDataCache.get("egi-department")); addDropdownData("functionList", masterDataCache.get("egi-function")); addDropdownData("financialYearList", getPersistenceService().findAllBy( "from CFinancialYear where isActive=true order by finYearRange desc ")); setRelatedEntitesOn(); majorCodeLength = Integer.valueOf(getAppConfigValueFor(Constants.EGF, "coa_majorcode_length")); } @Action(value = "/budget/budgetReport-getFunctionwiseReport") public String getFunctionwiseReport() { if (budgetReport.getFinancialYear() == null || budgetReport.getFinancialYear().getId() == 0) { addActionError(getText("msg.please.select.financial.year")); return "functionwise"; } return "printFunctionwise"; } @Action(value = "/budget/budgetReport-ajaxGenerateFunctionWiseHtml") public String ajaxGenerateFunctionWiseHtml() throws IOException { if (topBudget != null && topBudget.getId() != null) topBudget = budgetService.find("from Budget where id=?", topBudget.getId()); if (departmentBudget) workFlowstateCondn = " and (bd.status.code='Approved')"; final Map<String, Object> paramMap = getParamMap(); inputStream = reportHelper.exportHtml(inputStream, path, paramMap, getDataForFunctionwise(), "pt"); return "functionwise-HTML"; } public String ajaxFunctionWiseConsolidated() throws IOException { final List<Object> dataForFunctionwiseForConsolidation = getDataForFunctionwiseForConsolidation(); final Map<String, Object> paramMap = getParamMap(); inputStream = reportHelper.exportHtml(inputStream, path, paramMap, dataForFunctionwiseForConsolidation, "pt"); return "functionwise-HTML"; } @Action(value = "/budget/budgetReport-generateFunctionWisePdf") public String generateFunctionWisePdf() throws JRException, IOException { final Map<String, Object> paramMap = getParamMap(); inputStream = reportHelper.exportPdf(inputStream, path, paramMap, getDataForFunctionwise()); return "functionwise-PDF"; } @Action(value = "/budget/budgetReport-generateFunctionWiseXls") public String generateFunctionWiseXls() throws JRException, IOException { final Map<String, Object> paramMap = getParamMap(); inputStream = reportHelper.exportXls(inputStream, path, paramMap, getDataForFunctionwise()); return "functionwise-XLS"; } public String getAtGlanceReport() { return "printAtGlance"; } @Action(value = "/budget/budgetReport-ajaxGenerateAtGlanceHtml") public String ajaxGenerateAtGlanceHtml() throws IOException { final Map<String, Object> paramMap = getParamMap(); paramMap.put("heading", "BUDGET AT GLANCE "); inputStream = reportHelper.exportHtml(inputStream, path, paramMap, getDataForGlance(), "pt"); return "functionwise-HTML"; } public String generateAtGlancePdf() throws JRException, IOException { final Map<String, Object> paramMap = getParamMap(); paramMap.put("heading", "BUDGET AT GLANCE "); inputStream = reportHelper.exportPdf(inputStream, path, paramMap, getDataForGlance()); return "functionwise-PDF"; } public String generateAtGlanceXls() throws JRException, IOException { final Map<String, Object> paramMap = getParamMap(); paramMap.put("heading", "BUDGET AT GLANCE "); inputStream = reportHelper.exportXls(inputStream, path, paramMap, getDataForGlance()); return "functionwise-XLS"; } private Map<String, Map<String, Object>> getSql() { final Map<String, Map<String, Object>> queryMap = new HashMap<>(); final Map<String, Object> queryParams = new HashMap<>(); StringBuilder sql = new StringBuilder(""); sql.append(" bd.budget.financialYear.id=:finYearId"); queryParams.put("finYearId", Long.valueOf(budgetReport.getFinancialYear().getId())); if (budgetReport.getDepartment() != null && budgetReport.getDepartment().getId() != null) { sql.append(" and bd.executingDepartment=:execDept"); queryParams.put("execDept", budgetReport.getDepartment().getCode()); } if (budgetReport.getFunction() != null && budgetReport.getFunction().getId() != null) { sql.append(" and bd.function.id=:functionId"); queryParams.put("functionId", Long.valueOf(budgetReport.getFunction().getId())); } queryMap.put(sql.toString(), queryParams); return queryMap; } private List<BudgetDetail> getMincodeData() { final String finalStatus = getFinalStatus(); final Map.Entry<String, Map<String, Object>> queryMapEntry = getSql().entrySet().iterator().next(); final StringBuilder sql = new StringBuilder(queryMapEntry.getKey()); final Map<String, Object> queryParams = queryMapEntry.getValue(); if (budgetReport.getType().equalsIgnoreCase("IE")) sql.append(" and bd.budgetGroup.minCode.type in ('I','E')"); else if (!budgetReport.getType().equalsIgnoreCase("All")) { sql.append(" and bd.budgetGroup.minCode.type =:minCodeType"); queryParams.put("minCodeType", budgetReport.getType().charAt(0)); } List<BudgetDetail> budgetDetailList = new ArrayList<BudgetDetail>(); StringBuilder queryString = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(" and bd.budget.isbere='RE' order by bd.executingDepartment,bd.function.name,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode"); if (isOnSaveOrForward()) { final Query qry1 = getPersistenceService().getSession().createQuery(queryString.toString()); queryParams.entrySet().forEach(entry -> qry1.setParameter(entry.getKey(), entry.getValue())); budgetDetailList = qry1.list(); if (budgetDetailList.isEmpty()) { StringBuilder query = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(" and bd.budget.isbere='BE' order by bd.executingDepartment,bd.function.name,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode"); final Query qry2 = getPersistenceService().getSession().createQuery(query.toString()); queryParams.entrySet().forEach(entry -> qry2.setParameter(entry.getKey(), entry.getValue())); budgetDetailList = qry2.list(); } } else { StringBuilder query1 = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(" and bd.budget.isbere='RE' and bd.approvedAmount is not null and bd.budget.status.code=:status") .append(" order by bd.executingDepartment,bd.function.name,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode"); final Query qry1 = getPersistenceService().getSession().createQuery(query1.toString()); qry1.setParameter("status", finalStatus, StringType.INSTANCE); queryParams.entrySet().forEach(entry -> qry1.setParameter(entry.getKey(), entry.getValue())); budgetDetailList = qry1.list(); isBERE = "RE"; if (budgetDetailList.isEmpty()) { StringBuilder query2 = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(" and bd.budget.isbere='BE' and bd.budget.status.code =:status") .append(" order by bd.executingDepartment,bd.function.name,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode"); final Query qry2 = getPersistenceService().getSession().createQuery(query2.toString()); qry2.setParameter("status", finalStatus, StringType.INSTANCE); queryParams.entrySet().forEach(entry -> qry2.setParameter(entry.getKey(), entry.getValue())); budgetDetailList = qry2.list(); isBERE = "BE"; } } return budgetDetailList; } @SuppressWarnings("unchecked") private void getMincodeDataForWorkingCopy() { Map.Entry<String, Map<String, Object>> queryMapEntry = getSqlForFinYear(financialYearForRE.getId()).entrySet().iterator().next(); StringBuilder sql = new StringBuilder(queryMapEntry.getKey()); Map<String, Object> queryParams = queryMapEntry.getValue(); if (budgetReport.getType().equalsIgnoreCase("IE")) sql.append(" and bd.budgetGroup.minCode.type in ('I','E')"); else if (!budgetReport.getType().equalsIgnoreCase("All")) { sql.append(" and bd.budgetGroup.minCode.type=:minorCodeType"); queryParams.put("minorCodeType", budgetReport.getType().charAt(0)); } sql.append(queryMapEntry.getKey()); StringBuilder query = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(workFlowstateCondn) .append(" and bd.budget.isbere='RE' order by bd.executingDepartment,bd.function,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode"); final Query qry = getPersistenceService().getSession().createQuery(query.toString()); queryParams.entrySet().forEach(entry -> qry.setParameter(entry.getKey(), entry.getValue())); budgetDetailListForRE = qry.list(); queryMapEntry = getSqlForFinYearBE(financialYearForBE.getId()).entrySet().iterator().next(); sql = new StringBuilder(queryMapEntry.getKey()); queryParams = queryMapEntry.getValue(); if (budgetReport.getType().equalsIgnoreCase("IE")) sql.append(" and bd.budgetGroup.minCode.type in ('I','E')"); else if (!budgetReport.getType().equalsIgnoreCase("All")) { sql.append(" and bd.budgetGroup.minCode.type=:minorCodeType"); queryParams.put("minorCodeType", budgetReport.getType().charAt(0)); } StringBuilder query2 = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(workFlowstateCondn) .append(" and bd.budget.isbere='BE' order by bd.executingDepartment,bd.function,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode"); final Query qry2 = getPersistenceService().getSession().createQuery(query2.toString()); queryParams.entrySet().forEach(entry -> qry2.setParameter(entry.getKey(), entry.getValue())); budgetDetailListForBE.addAll(qry2.list()); } @SuppressWarnings("unchecked") private List<BudgetDetail> getMajorcodeData() { final String finalStatus = getFinalStatus(); final Map.Entry<String, Map<String, Object>> queryMapEntry = getSql().entrySet().iterator().next(); final StringBuilder sql = new StringBuilder(queryMapEntry.getKey()); final Map<String, Object> queryParams = queryMapEntry.getValue(); if (budgetReport.getType().equalsIgnoreCase("IE")) sql.append(" and bd.budgetGroup.majorCode.type in ('I','E')"); else if (!budgetReport.getType().equalsIgnoreCase("All")) { sql.append(" and bd.budgetGroup.majorCode.type=:majorCodeType"); queryParams.put("majorCodeType", budgetReport.getType().charAt(0)); } List<BudgetDetail> budgetDetailList = new ArrayList<BudgetDetail>(); if (onSaveOrForward) { StringBuilder query = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(" order by bd.executingDepartment,bd.function.name,bd.budgetGroup.majorCode.type,bd.budgetGroup.majorCode.glcode"); final Query qry = getPersistenceService().getSession().createQuery(query.toString()); queryParams.entrySet().forEach(entry -> qry.setParameter(entry.getKey(), entry.getValue())); budgetDetailList = qry.list(); if (budgetDetailList.isEmpty()) { StringBuilder query1 = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(" and bd.budget.isbere='BE' order by bd.executingDepartment,bd.function.name,bd.budgetGroup.majorCode.type,") .append(" bd.budgetGroup.majorCode.glcode"); final Query qry1 = getPersistenceService().getSession().createQuery(query1.toString()); queryParams.entrySet().forEach(entry -> qry1.setParameter(entry.getKey(), entry.getValue())); budgetDetailList = qry1.list(); } } else { StringBuilder query2 = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(" and bd.budget.isbere='RE' and bd.budget.status.code=:status") .append(" order by bd.executingDepartment,bd.function.name,bd.budgetGroup.majorCode.type,bd.budgetGroup.majorCode.glcode"); final Query qry2 = getPersistenceService().getSession().createQuery(query2.toString()); queryParams.entrySet().forEach(entry -> qry2.setParameter(entry.getKey(), entry.getValue())); qry2.setParameter("status", finalStatus, StringType.INSTANCE); budgetDetailList = qry2.list(); if (budgetDetailList.isEmpty()) { StringBuilder query3 = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(" and bd.budget.isbere='BE' and bd.budget.status.code=:status") .append(" order by bd.executingDepartment,bd.function.name,bd.budgetGroup.majorCode.type,bd.budgetGroup.majorCode.glcode"); final Query qry3 = getPersistenceService().getSession().createQuery(query3.toString()); queryParams.entrySet().forEach(entry -> qry3.setParameter(entry.getKey(), entry.getValue())); qry3.setParameter("status", finalStatus, StringType.INSTANCE); budgetDetailList = qry3.list(); } } return budgetDetailList; } @SuppressWarnings("unchecked") private void getMajorcodeDataForWorkingCopy() { Map.Entry<String, Map<String, Object>> queryMapEntry = getSqlForFinYear(financialYearForRE.getId()).entrySet().iterator().next(); StringBuilder sql = new StringBuilder(queryMapEntry.getKey()); Map<String, Object> queryParams = queryMapEntry.getValue(); if (budgetReport.getType().equalsIgnoreCase("IE")) sql.append(" and bd.budgetGroup.majorCode.type in ('I','E')"); else if (!budgetReport.getType().equalsIgnoreCase("All")) { sql.append(" and bd.budgetGroup.majorCode.type=:majorCodeType"); queryParams.put("majorCodeType", budgetReport.getType().charAt(0)); } sql.append(queryMapEntry.getKey()); StringBuilder query = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(workFlowstateCondn) .append(" order by bd.executingDepartment,bd.function,bd.budgetGroup.majorCode.type,bd.budgetGroup.majorCode.glcode"); final Query qry = getPersistenceService().getSession().createQuery(query.toString()); queryParams.entrySet().forEach(entry -> qry.setParameter(entry.getKey(), entry.getValue())); budgetDetailListForRE.addAll(qry.list()); queryMapEntry = getSqlForFinYearBE(financialYearForBE.getId()).entrySet().iterator().next(); sql = new StringBuilder(queryMapEntry.getKey()); queryParams = queryMapEntry.getValue(); if (budgetReport.getType().equalsIgnoreCase("IE")) sql.append(" and bd.budgetGroup.majorCode.type in ('I','E')"); else if (!budgetReport.getType().equalsIgnoreCase("All")) { sql.append(" and bd.budgetGroup.majorCode.type=:majorCodeType"); queryParams.put("majorCodeType", budgetReport.getType().charAt(0)); } StringBuilder query1 = new StringBuilder(" from BudgetDetail bd where ") .append(sql) .append(workFlowstateCondn) .append(" and bd.budget.isbere='BE' order by bd.executingDepartment,bd.function,bd.budgetGroup.majorCode.type,bd.budgetGroup.majorCode.glcode"); final Query qry1 = getPersistenceService().getSession().createQuery(query1.toString()); queryParams.entrySet().forEach(entry -> qry1.setParameter(entry.getKey(), entry.getValue())); budgetDetailListForBE.addAll(qry1.list()); } private List<Object> getDataForFunctionwise() { if (onSaveOrForward) return getDataFunctionWiseForWorkingCopy(); List<BudgetDetail> budgetDetailList = null; budgetDetailList = getMincodeData(); budgetDetailList.addAll(getMajorcodeData()); if (budgetDetailList.isEmpty()) return budgetReportList; String deptCode = ""; Long functionId = 0L; String type = "", majorCode = "", glcode = "", glType = "", glName = "", tempMajorCode = ""; BigDecimal totalAmt = BigDecimal.ZERO; BigDecimal totalAppropriationAmt = BigDecimal.ZERO; BigDecimal reAppropriationAmt = BigDecimal.ZERO; boolean printed = true; boolean isFirst = true; boolean majorcodewise = false; refNoMap = getReferenceNumber("functionWiseBudgetReport"); getCOA(); getBudgetReappropriationAmt(); loadAmountForMajorcodewise(budgetReport.getFinancialYear(), budgetReport.getDepartment(), budgetReport.getFunction()); for (final BudgetDetail detail : budgetDetailList) { if (detail.getExecutingDepartment() == null || detail.getFunction() == null) continue; reAppropriationAmt = reAppropriationMap.get(detail.getId()) == null ? BigDecimal.ZERO : reAppropriationMap.get(detail .getId()); if (detail.getBudgetGroup().getMajorCode() == null) { glcode = getGlCode(detail); glType = detail.getBudgetGroup().getMinCode().getType().toString(); glName = getGlName(detail); } else { glcode = detail.getBudgetGroup().getMajorCode().getGlcode(); glType = detail.getBudgetGroup().getMajorCode().getType().toString(); glName = detail.getBudgetGroup().getMajorCode().getName(); majorcodewise = true; } tempMajorCode = glcode.substring(0, majorCodeLength); if (!detail.getExecutingDepartment().equals(deptCode)) // for dept heading { if (totalAmt.compareTo(BigDecimal.ZERO) != 0 && !isFirst) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); totalAmt = BigDecimal.ZERO; totalAppropriationAmt = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, microserviceUtils.getDepartmentByCode(detail.getExecutingDepartment()).getName(), EMPTYSTRING, null, null, null, "deptrow")); type = ""; functionId = null; majorCode = ""; } if (!glType.equals(type))// for type heading { if (totalAmt.compareTo(BigDecimal.ZERO) != 0 && !isFirst) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); totalAmt = BigDecimal.ZERO; totalAppropriationAmt = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, "FUNCTIONWISE " + BudgetReport.getValueFor(glType).toUpperCase() + " BUDGET SUMMARY", refNoMap.get(BudgetReport .getValueFor(glType)), null, null, null, "typerow")); functionId = null; majorCode = ""; } if (detail.getFunction().getId().compareTo(functionId!=null?functionId:0l)!=0) // for function heading { if (totalAmt.compareTo(BigDecimal.ZERO) != 0 && !isFirst) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); totalAmt = BigDecimal.ZERO; totalAppropriationAmt = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, "FUNCTION CENTRE-" + detail.getFunction().getName(), EMPTYSTRING, null, null, null, "functionrow")); final List<Object> majorCodeList = getAmountForMajorcodewise(detail.getExecutingDepartment(), detail.getFunction().getId(), glType); // majorcodewise total budgetReportList.addAll(majorCodeList); printed = false; majorCode = ""; } if (!tempMajorCode.equals(majorCode) && detail.getBudgetGroup().getMajorCode() == null)// majorcodewise - heading { if (printed) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); totalAmt = BigDecimal.ZERO; totalAppropriationAmt = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, refNoMap.get(tempMajorCode), tempMajorCode + "-" + coaMap.get(tempMajorCode), "", null, null, null, "majorcodeheadingrow")); } // detail if (detail.getExecutingDepartment() != null && detail.getFunction() != null && detail.getBudgetGroup().getMajorCode() == null) budgetReportList.add(new BudgetReportView(detail.getExecutingDepartment(), detail.getFunction() .getCode(), glcode, glName, "", detail.getApprovedAmount(), reAppropriationAmt, detail.getApprovedAmount().add(reAppropriationAmt), "detailrow")); if (detail.getExecutingDepartment() != null) deptCode = detail.getExecutingDepartment(); if (detail.getFunction() != null) functionId = detail.getFunction().getId(); type = glType; majorCode = tempMajorCode; totalAmt = totalAmt.add(detail.getApprovedAmount()); totalAppropriationAmt = totalAppropriationAmt.add(reAppropriationAmt); printed = true; isFirst = false; } if (totalAmt.compareTo(BigDecimal.ZERO)!=0 && !majorcodewise) budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); return budgetReportList; } /** * function ,department and budget will be passed here * @return */ private List<Object> getDataForFunctionwiseForConsolidation() { List<BudgetDetail> budgetDetailList = null; pos = getPosition(); if (budgetDetail.getId() != null) { budgetDetail = budgetDetailService.find("from BudgetDetail where id=?", budgetDetail.getId()); topBudget = budgetDetail.getBudget(); budgetReport.setFinancialYear(budgetDetail.getBudget().getFinancialYear()); budgetDetailList = budgetDetailService.findAllBy( "from BudgetDetail where budget.id=? and state.value=? and function=?", budgetDetail.getBudget().getId(), "END", budgetDetail.getFunction()); } else if (budgetDetail.getBudget().getId() != null) { topBudget = budgetService.find("from Budget where id=?", budgetDetail.getBudget().getId()); budgetReport.setFinancialYear(topBudget.getFinancialYear()); budgetDetailList = budgetDetailService.findAllBy( "from BudgetDetail where budget=? and( state.value=? or state.owner=?)", topBudget, "END", pos); } // budgetDetailList = // budgetDetailService.findAllBy("from BudgetDetail where budget=? where state.value=?",budgetDetail.getBudget(),"END"); if (budgetDetailList.isEmpty()) return budgetReportList; String deptCode = ""; Long functionId = 0L; String type = "", majorCode = "", glcode = "", glType = "", glName = "", tempMajorCode = ""; BigDecimal totalAmt = BigDecimal.ZERO; BigDecimal totalAppropriationAmt = BigDecimal.ZERO; final BigDecimal reAppropriationAmt = BigDecimal.ZERO; boolean printed = true; boolean isFirst = true; boolean majorcodewise = false; refNoMap = getReferenceNumber("functionWiseBudgetReport"); getCOA(); // getBudgetReappropriationAmt(); loadAmountForMajorcodewiseConsolidated(budgetReport.getFinancialYear(), budgetReport.getDepartment(), budgetReport.getFunction()); for (final BudgetDetail detail : budgetDetailList) { if (detail.getExecutingDepartment() == null || detail.getFunction() == null) continue; if (detail.getBudgetGroup().getMajorCode() == null) { glcode = getGlCode(detail); glType = detail.getBudgetGroup().getMinCode().getType().toString(); glName = getGlName(detail); } else { glcode = detail.getBudgetGroup().getMajorCode().getGlcode(); glType = detail.getBudgetGroup().getMajorCode().getType().toString(); glName = detail.getBudgetGroup().getMajorCode().getName(); majorcodewise = true; } tempMajorCode = glcode.substring(0, majorCodeLength); if (!detail.getExecutingDepartment().equals(deptCode)) // for dept heading { if (totalAmt.compareTo(BigDecimal.ZERO) != 0 && !isFirst) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); totalAmt = BigDecimal.ZERO; totalAppropriationAmt = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, microserviceUtils.getDepartmentByCode(detail.getExecutingDepartment()).getName(), EMPTYSTRING, null, null, null, "deptrow")); type = ""; functionId = null; majorCode = ""; } if (!glType.equals(type))// for type heading { if (totalAmt.compareTo(BigDecimal.ZERO) != 0 && !isFirst) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); totalAmt = BigDecimal.ZERO; totalAppropriationAmt = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, "FUNCTIONWISE " + BudgetReport.getValueFor(glType).toUpperCase() + " BUDGET SUMMARY", refNoMap.get(BudgetReport .getValueFor(glType)), null, null, null, "typerow")); functionId = null; majorCode = ""; } if (!detail.getFunction().getId().equals(functionId)) // for function heading { if (totalAmt.compareTo(BigDecimal.ZERO) != 0 && !isFirst) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); totalAmt = BigDecimal.ZERO; totalAppropriationAmt = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, "FUNCTION CENTRE-" + detail.getFunction().getName(), EMPTYSTRING, null, null, null, "functionrow")); final List<Object> majorCodeList = getAmountForMajorcodewise(detail.getExecutingDepartment(), detail.getFunction().getId(), glType); // majorcodewise total budgetReportList.addAll(majorCodeList); printed = false; majorCode = ""; } if (!tempMajorCode.equals(majorCode) && detail.getBudgetGroup().getMajorCode() == null)// majorcodewise - heading { if (printed) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); totalAmt = BigDecimal.ZERO; totalAppropriationAmt = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, refNoMap.get(tempMajorCode), tempMajorCode + "-" + coaMap.get(tempMajorCode), "", null, null, null, "majorcodeheadingrow")); } // detail if (detail.getExecutingDepartment() != null && detail.getFunction() != null && detail.getBudgetGroup().getMajorCode() == null) budgetReportList.add(new BudgetReportView(detail.getExecutingDepartment(), detail.getFunction() .getCode(), glcode, glName, "", detail.getApprovedAmount(), reAppropriationAmt, detail.getApprovedAmount().add(reAppropriationAmt), "detailrow")); if (detail.getExecutingDepartment() != null) deptCode = detail.getExecutingDepartment(); if (detail.getFunction() != null) functionId = detail.getFunction().getId(); type = glType; majorCode = tempMajorCode; totalAmt = totalAmt.add(detail.getApprovedAmount()); totalAppropriationAmt = totalAppropriationAmt.add(reAppropriationAmt); printed = true; isFirst = false; } if (totalAmt.compareTo(BigDecimal.ZERO)!=0 && !majorcodewise) budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, totalAmt, totalAppropriationAmt, totalAmt.add(totalAppropriationAmt), TOTALROW)); return budgetReportList; } public Budget getTopBudget() { return topBudget; } public void setTopBudget(final Budget topBudget) { this.topBudget = topBudget; } private Position getPosition() { Position pos; try { // TODO: Now employee is extending user so passing userid to get assingment -- changes done by Vaibhav pos = eisCommonService.getPrimaryAssignmentPositionForEmp(ApplicationThreadLocals.getUserId()); } catch (final ApplicationRuntimeException e) { throw new ApplicationRuntimeException("Unable to get Position for the user"); } return pos; } public void loadAmountForMajorcodewise(final CFinancialYear finyear, final Department dept, final CFunction function) { String finalStatus = getFinalStatus(); StringBuilder miscQuery = new StringBuilder(""); String floatingColumn = "sum(bd.approvedAmount)"; if (onSaveOrForward) { if (LOGGER.isInfoEnabled()) LOGGER.info("......Can view the approved Amount" + canViewApprovedAmount); if (!canViewApprovedAmount) { floatingColumn = "sum(bd.originalAmount)"; finalStatus = "%"; } } if (dept != null && dept.getId() != null) miscQuery.append(" and bd.executingDepartment=:execDept"); if (function != null && function.getId() != null) miscQuery.append(" and bd.function.id=:functionId"); StringBuilder queryString = new StringBuilder("select substr(bd.budgetGroup.minCode.glcode,0,").append(majorCodeLength) .append(") ,") .append(floatingColumn) .append(",bd.executingDepartment,bd.function.id,bd.budgetGroup.minCode.type,bd.id from BudgetDetail bd where ") .append("bd.budget.financialYear=:finYear and bd.budget.state in (from org.egov.infra.workflow.entity.State where type='Budget' and value=:status) ") .append(miscQuery) .append(" and bd.budget.isbere=:isBere") .append(" group by substr(bd.budgetGroup.minCode.glcode,0,").append(majorCodeLength) .append("),bd.executingDepartment,") .append("bd.function.id,bd.budgetGroup.minCode.type,bd.id") .append(" order by substr(bd.budgetGroup.minCode.glcode,0,").append(majorCodeLength) .append("),bd.executingDepartment,bd.function.id"); final Query qry = getPersistenceService().getSession().createQuery(queryString.toString()); if (dept != null && dept.getId() != null) qry.setParameter("execDept", dept.getCode(), StringType.INSTANCE); if (function != null && function.getId() != null) qry.setParameter("functionId", function.getId(), LongType.INSTANCE); qry.setParameter("finYear", finyear) .setParameter("status", finalStatus, StringType.INSTANCE) .setParameter("isBere", isBERE, StringType.INSTANCE); List<Object[]> amountList = qry.list(); BigDecimal reAppropriationAmt = BigDecimal.ZERO; for (final Object[] obj : amountList) if (obj[0] != null && obj[1] != null && obj[2] != null && obj[3] != null && obj[4] != null && !(BigDecimal.ZERO.compareTo(BigDecimal.valueOf(Double.valueOf(obj[1].toString()))) == 0)) { reAppropriationAmt = reAppropriationMap.get(obj[5]) == null ? BigDecimal.ZERO : reAppropriationMap.get(obj[5]); reportStoreList.add(new BudgetReportView(Integer.valueOf(obj[2] + EMPTYSTRING), Long .valueOf(obj[3] + EMPTYSTRING), obj[4] + EMPTYSTRING, obj[0] + EMPTYSTRING, (BigDecimal) obj[1], reAppropriationAmt, ((BigDecimal) obj[1]) .add(reAppropriationAmt))); } StringBuilder query = new StringBuilder("select substr(bd.budgetGroup.majorCode.glcode,0,").append(majorCodeLength) .append(") ,") .append(floatingColumn) .append(",bd.executingDepartment,bd.function.id,bd.budgetGroup.majorCode.type,bd.id from BudgetDetail bd where bd.budget.financialYear=:finYear") .append(" and bd.budget.state in (from org.egov.infra.workflow.entity.State where type='Budget' and value=:status) and bd.budget.isbere=:isBeRe") .append(" group by substr(bd.budgetGroup.majorCode.glcode,0,").append(majorCodeLength) .append("),bd.executingDepartment,bd.function.id,bd.budgetGroup.majorCode.type,bd.id") .append(" order by substr(bd.budgetGroup.majorCode.glcode,0,").append(majorCodeLength) .append(")"); Query qry1 = getPersistenceService().getSession().createQuery(query.toString()); qry1.setParameter("finYear", finyear) .setParameter("status", finalStatus, StringType.INSTANCE) .setParameter("isBeRe", isBERE, StringType.INSTANCE); amountList = qry1.list(); for (final Object[] obj : amountList) if (obj[0] != null && obj[1] != null && obj[2] != null && obj[3] != null && obj[4] != null && !(BigDecimal.ZERO.compareTo(BigDecimal.valueOf(Double.valueOf(obj[1].toString()))) == 0)) { reAppropriationAmt = reAppropriationMap.get(obj[5]) == null ? BigDecimal.ZERO : reAppropriationMap.get(obj[5]); reportStoreList.add(new BudgetReportView(Integer.valueOf(obj[2] + EMPTYSTRING), Long .valueOf(obj[3] + EMPTYSTRING), obj[4] + EMPTYSTRING, obj[0] + EMPTYSTRING, (BigDecimal) obj[1], reAppropriationAmt, ((BigDecimal) obj[1]) .add(reAppropriationAmt))); } } public void loadAmountForMajorcodewiseConsolidated(final CFinancialYear finyear, final Department dept, final CFunction function) { getFinalStatus(); StringBuilder miscQuery = new StringBuilder(""); final String floatingColumn = "sum(bd.approvedAmount)"; if (dept != null && dept.getId() != null) miscQuery.append(" and bd.executingDepartment=:execDept "); if (function != null && function.getId() != null) miscQuery.append(" and bd.function.id=:functionId "); StringBuilder queryString = new StringBuilder("select substr(bd.budgetGroup.minCode.glcode,0,") .append(majorCodeLength).append(") ,").append(floatingColumn) .append(",bd.executingDepartment,bd.function.id,bd.budgetGroup.minCode.type,bd.id from BudgetDetail bd where ") .append("bd.budget.financialYear=:finYear and( bd.state.value ='END' or bd.state.owner=:owner) and bd.budget=:budget") .append(miscQuery) .append(" and bd.budget.isbere=:isBeRe group by substr(bd.budgetGroup.minCode.glcode,0,") .append(majorCodeLength) .append("),bd.executingDepartment,") .append("bd.function.id,bd.budgetGroup.minCode.type,bd.id") .append(" order by substr(bd.budgetGroup.minCode.glcode,0,") .append(majorCodeLength) .append("),bd.executingDepartment,bd.function.id"); Query query = getPersistenceService().getSession().createQuery(queryString.toString()); if (dept != null && dept.getId() != null) query.setParameter("execDept", dept.getCode(), StringType.INSTANCE); if (function != null && function.getId() != null) query.setParameter("functionId", function.getId(), LongType.INSTANCE); query.setParameter("finYear", finyear).setParameter("owner", pos).setParameter("budget", topBudget) .setParameter("isBeRe", isBERE, StringType.INSTANCE); final List<Object[]> amountList = query.list(); BigDecimal reAppropriationAmt = BigDecimal.ZERO; for (final Object[] obj : amountList) if (obj[0] != null && obj[1] != null && obj[2] != null && obj[3] != null && obj[4] != null && !(BigDecimal.ZERO.compareTo(BigDecimal.valueOf(Double.valueOf(obj[1].toString()))) == 0)) { reAppropriationAmt = reAppropriationMap.get(obj[5]) == null ? BigDecimal.ZERO : reAppropriationMap.get(obj[5]); reportStoreList.add(new BudgetReportView(Integer.valueOf(obj[2] + EMPTYSTRING), Long.valueOf(obj[3] + EMPTYSTRING), obj[4] + EMPTYSTRING, obj[0] + EMPTYSTRING, (BigDecimal) obj[1], reAppropriationAmt, ((BigDecimal) obj[1]).add(reAppropriationAmt))); } /* * amountList = getPersistenceService() .findAllBy( "select substr(bd.budgetGroup.majorCode.glcode,0," + majorCodeLength + * ") ," + floatingColumn + * ",bd.executingDepartment,bd.function.id,bd.budgetGroup.majorCode.type,bd.id from BudgetDetail bd where bd.budget.financialYear=? and bd.budget.state in (from org.egov.infra.workflow.entity.State where type='Budget' and value='" * + finalStatus + "' ) and bd.budget.isbere='"+isBERE+"' group by substr(bd.budgetGroup.majorCode.glcode,0," + * majorCodeLength + * "),bd.executingDepartment,bd.function.id,bd.budgetGroup.majorCode.type,bd.id order by substr(bd.budgetGroup.majorCode.glcode,0," * + majorCodeLength + ")", finyear); for (Object[] obj : amountList) { if (obj[0] != null && obj[1] != null && obj[2] != * null && obj[3] != null && obj[4] != null && * !(BigDecimal.ZERO.compareTo(BigDecimal.valueOf(Double.valueOf(obj[1].toString())))==0)) { reAppropriationAmt = * reAppropriationMap.get(obj[5]) == null ? BigDecimal.ZERO : reAppropriationMap.get(obj[5]); reportStoreList.add(new * BudgetReportView(Integer.valueOf(obj[2] + EMPTYSTRING), Long.valueOf(obj[3] + EMPTYSTRING), obj[4] + EMPTYSTRING, * obj[0] + EMPTYSTRING, ((BigDecimal) obj[1]), reAppropriationAmt, ((BigDecimal) obj[1]).add(reAppropriationAmt))); } } */ } @SuppressWarnings("unchecked") public void loadAmountForMajorcodewiseForWorkingCopy(final CFinancialYear finyear, final Department dept, final CFunction function) { final String floatingColumn = "sum(bd.originalAmount),sum(bd.approvedAmount)"; getFinYearForRE(); Map.Entry<String, Map<String, Object>> queryMapEntry = getSqlForFinYear(financialYearForRE.getId()).entrySet() .iterator().next(); String miscQuery = queryMapEntry.getKey(); Map<String, Object> queryParams = queryMapEntry.getValue(); // find sum for RE StringBuilder queryString = new StringBuilder("select substr(bd.budgetGroup.minCode.glcode,0,") .append(majorCodeLength).append("),").append(floatingColumn) .append(",bd.executingDepartment,bd.function.id,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode,bd.id from BudgetDetail bd where ") .append(" ").append(miscQuery).append(workFlowstateCondn) .append(" and bd.budget.isbere='RE' group by substr(bd.budgetGroup.minCode.glcode,0,") .append(majorCodeLength).append("),bd.executingDepartment,") .append("bd.function.id,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode,bd.id order by substr(bd.budgetGroup.minCode.glcode,0,") .append(majorCodeLength).append("),").append("bd.executingDepartment,bd.function.id"); final Query qryStr = getPersistenceService().getSession().createQuery(queryString.toString()); queryParams.entrySet().forEach(entry -> qryStr.setParameter(entry.getKey(), entry.getValue())); final List<Object[]> amountListForRE = qryStr.list(); StringBuilder query = new StringBuilder("select substr(bd.budgetGroup.majorCode.glcode,0,") .append(majorCodeLength).append(") ,").append(floatingColumn) .append(",bd.executingDepartment,bd.function.id,bd.budgetGroup.majorCode.type,bd.id from BudgetDetail bd where ") .append(miscQuery).append(workFlowstateCondn) .append(" and bd.budget.isbere='RE' group by substr(bd.budgetGroup.majorCode.glcode,0,") .append(majorCodeLength).append("),bd.executingDepartment,bd.function.id,") .append("bd.budgetGroup.majorCode.type,bd.budgetGroup.majorCode.glcode,bd.budgetGroup.minCode.glcode,bd.id") .append(" order by substr(bd.budgetGroup.majorCode.glcode,0,").append(majorCodeLength).append(")"); final Query qry = getPersistenceService().getSession().createQuery(query.toString()); queryParams.entrySet().forEach(entry -> qry.setParameter(entry.getKey(), entry.getValue())); amountListForRE.addAll(qry.list()); queryMapEntry = getSqlForFinYearBE(financialYearForBE.getId()).entrySet().iterator().next(); miscQuery = queryMapEntry.getKey(); queryParams = queryMapEntry.getValue(); /** * order of retrieval 0-majorcode 1-sum(originalamount) 2-sum(approvedamount) * 3-department 4-function 5-type 6-glcode/id 7-id */ StringBuilder query1 = new StringBuilder("select substr(bd.budgetGroup.minCode.glcode,0,") .append(majorCodeLength).append(") ,").append(floatingColumn) .append(",bd.executingDepartment,bd.function.id,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode,bd.id from BudgetDetail bd where ") .append(" ").append(miscQuery).append(workFlowstateCondn) .append(" and bd.budget.isbere='BE' group by substr(bd.budgetGroup.minCode.glcode,0,") .append(majorCodeLength).append("),bd.executingDepartment,") .append("bd.function.id,bd.budgetGroup.minCode.type,bd.budgetGroup.minCode.glcode,bd.id") .append(" order by substr(bd.budgetGroup.minCode.glcode,0,").append(majorCodeLength) .append("),bd.executingDepartment,bd.function.id"); final Query qry1 = getPersistenceService().getSession().createQuery(query1.toString()); queryParams.entrySet().forEach(entry -> qry1.setParameter(entry.getKey(), entry.getValue())); final List<Object[]> amountListForBE = qry1.list(); StringBuilder query2 = new StringBuilder("select substr(bd.budgetGroup.majorCode.glcode,0,") .append(majorCodeLength).append(") ,").append(floatingColumn) .append(",bd.executingDepartment,bd.function.id,bd.budgetGroup.majorCode.type,bd.budgetGroup.majorCode.glcode,bd.id from BudgetDetail bd where ") .append(miscQuery).append(workFlowstateCondn) .append(" and bd.budget.isbere='BE' group by substr(bd.budgetGroup.majorCode.glcode,0,") .append(majorCodeLength).append("),bd.executingDepartment,bd.function.id,") .append("bd.budgetGroup.majorCode.type,bd.budgetGroup.majorCode.glcode,bd.id order by substr(bd.budgetGroup.majorCode.glcode,0,") .append(majorCodeLength).append(")"); final Query qry2 = getPersistenceService().getSession().createQuery(query2.toString()); queryParams.entrySet().forEach(entry -> qry2.setParameter(entry.getKey(), entry.getValue())); amountListForBE.addAll(qry2.list()); // Merge both and set to budget Report // u may require null check here // handle un equal be and re major code totals outer: for (final Object[] re : amountListForRE) inner: for (final Object[] be : amountListForBE) if (re[0].toString().equalsIgnoreCase(be[0].toString()) && re[3].toString().equalsIgnoreCase(be[3].toString()) && re[4].toString().equalsIgnoreCase(be[4].toString()) && re[6].toString().equalsIgnoreCase(be[6].toString())) { final BudgetReportView v1 = new BudgetReportView(); v1.setDeptId(Integer.valueOf(re[3].toString())); v1.setFunctionId((Long) re[4]); v1.setType(re[5].toString()); v1.setMajorCode(re[0].toString()); v1.setReProposalAmount((BigDecimal) re[1]); v1.setReRecomAmount((BigDecimal) re[2]); v1.setBeProposalAmount((BigDecimal) be[1]); v1.setBeRecomAmount((BigDecimal) be[2]); reportStoreList.add(v1); break inner; } } public List<Object> getAmountForMajorcodewise(final String deptCode, final Long functionId, final String type) { BigDecimal grandAmt = BigDecimal.ZERO; BigDecimal totalAmt = BigDecimal.ZERO; BigDecimal appropriationGrandAmt = BigDecimal.ZERO; BigDecimal appropriationTotalAmt = BigDecimal.ZERO; final List<Object> majorCodeList = new ArrayList<Object>(); final Map<String, BudgetReportView> entries = new TreeMap<String, BudgetReportView>(); for (final BudgetReportView reportStore : reportStoreList) if (deptCode.equals(reportStore.getDeptCode()) && functionId.equals(reportStore.getFunctionId()) && type.equals(reportStore.getType())) { if (entries.get(reportStore.getMajorCode()) == null) { totalAmt = BigDecimal.ZERO; appropriationTotalAmt = BigDecimal.ZERO; entries.put( reportStore.getMajorCode(), new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, reportStore.getMajorCode() + "-" + coaMap.get(reportStore.getMajorCode()), refNoMap.get(reportStore.getMajorCode()) == null ? EMPTYSTRING : refNoMap.get( reportStore.getMajorCode()).toString(), reportStore.getTempamount(), reportStore .getAppropriationAmount(), reportStore .getTempamount().add(reportStore.getAppropriationAmount()), "majorcoderow")); totalAmt = totalAmt.add(reportStore.getTempamount()); appropriationTotalAmt = appropriationTotalAmt.add(reportStore.getAppropriationAmount()); } else { totalAmt = totalAmt.add(reportStore.getTempamount()); appropriationTotalAmt = appropriationTotalAmt.add(reportStore.getAppropriationAmount()); entries.get(reportStore.getMajorCode()).setAmount(totalAmt); entries.get(reportStore.getMajorCode()).setAppropriationAmount(appropriationTotalAmt); entries.get(reportStore.getMajorCode()).setTotalAmount(totalAmt.add(appropriationTotalAmt)); } grandAmt = grandAmt.add(reportStore.getTempamount()); appropriationGrandAmt = appropriationGrandAmt.add(reportStore.getAppropriationAmount()); } for (final Entry<String, BudgetReportView> row : entries.entrySet()) majorCodeList.add(row.getValue()); if (totalAmt.compareTo(BigDecimal.ZERO)!=0) majorCodeList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, grandAmt, appropriationGrandAmt, grandAmt .add(appropriationGrandAmt), TOTALROW)); return majorCodeList; } public List<Object> getAmountForMajorcodewiseForWorkingCopy(final String deptCode, final Long functionId, final String type) { BigDecimal reProposalTotalAmountLocal = BigDecimal.ZERO; BigDecimal beProposalTotalAmountLocal = BigDecimal.ZERO; BigDecimal reRecomTotalAmountLocal = BigDecimal.ZERO; BigDecimal beRecomTotalAmountLocal = BigDecimal.ZERO; BigDecimal reProposalTotalAmountLocalGrand = BigDecimal.ZERO; BigDecimal beProposalTotalAmountLocalGrand = BigDecimal.ZERO; BigDecimal reRecomTotalAmountLocalGrand = BigDecimal.ZERO; BigDecimal beRecomTotalAmountLocalGrand = BigDecimal.ZERO; final List<Object> majorCodeList = new ArrayList<Object>(); final Map<String, BudgetReportView> entries = new TreeMap<String, BudgetReportView>(); for (final BudgetReportView reportStore : reportStoreList) if (deptCode.equals(reportStore.getDeptCode()) && functionId.equals(reportStore.getFunctionId()) && type.equals(reportStore.getType())) { if (entries.get(reportStore.getMajorCode()) == null) { reProposalTotalAmountLocal = BigDecimal.ZERO; beProposalTotalAmountLocal = BigDecimal.ZERO; reRecomTotalAmountLocal = BigDecimal.ZERO; beRecomTotalAmountLocal = BigDecimal.ZERO; final BudgetReportView v2 = new BudgetReportView(); v2.setNarration("1414"); v2.setNarration(reportStore.getMajorCode() + "-" + coaMap.get(reportStore.getMajorCode())); v2.setReference(refNoMap.get(reportStore.getMajorCode()) == null ? EMPTYSTRING : refNoMap.get( reportStore.getMajorCode()).toString()); v2.setBeProposalAmount(reportStore.getBeProposalAmount()); v2.setReProposalAmount(reportStore.getReProposalAmount()); v2.setBeRecomAmount(reportStore.getBeRecomAmount()); v2.setReRecomAmount(reportStore.getReRecomAmount()); entries.put(reportStore.getMajorCode(), v2); reProposalTotalAmountLocal = reProposalTotalAmountLocal.add(reportStore.getReProposalAmount()); beProposalTotalAmountLocal = beProposalTotalAmountLocal.add(reportStore.getBeProposalAmount()); beRecomTotalAmountLocal = beRecomTotalAmountLocal.add(reportStore.getBeRecomAmount()); reRecomTotalAmountLocal = reRecomTotalAmountLocal.add(reportStore.getReRecomAmount()); } else { reProposalTotalAmountLocal = reProposalTotalAmountLocal.add(reportStore.getReProposalAmount()); beProposalTotalAmountLocal = beProposalTotalAmountLocal.add(reportStore.getBeProposalAmount()); beRecomTotalAmountLocal = beRecomTotalAmountLocal.add(reportStore.getBeRecomAmount()); reRecomTotalAmountLocal = reRecomTotalAmountLocal.add(reportStore.getReRecomAmount()); entries.get(reportStore.getMajorCode()).setReProposalAmount(reProposalTotalAmountLocal); entries.get(reportStore.getMajorCode()).setBeProposalAmount(beProposalTotalAmountLocal); entries.get(reportStore.getMajorCode()).setReRecomAmount(reRecomTotalAmountLocal); entries.get(reportStore.getMajorCode()).setBeRecomAmount(beRecomTotalAmountLocal); } reProposalTotalAmountLocalGrand = reProposalTotalAmountLocalGrand.add(reportStore.getReProposalAmount()); beProposalTotalAmountLocalGrand = beProposalTotalAmountLocalGrand.add(reportStore.getBeProposalAmount()); beRecomTotalAmountLocalGrand = beRecomTotalAmountLocalGrand.add(reportStore.getBeRecomAmount()); reRecomTotalAmountLocalGrand = reRecomTotalAmountLocalGrand.add(reportStore.getReRecomAmount()); // grandAmt = grandAmt.add(reportStore.getTempamount()); } for (final Entry<String, BudgetReportView> row : entries.entrySet()) majorCodeList.add(row.getValue()); final BudgetReportView v3 = new BudgetReportView(); v3.setBeProposalAmount(beProposalTotalAmountLocalGrand); v3.setReProposalAmount(reProposalTotalAmountLocalGrand); v3.setBeRecomAmount(beRecomTotalAmountLocalGrand); v3.setReRecomAmount(reRecomTotalAmountLocalGrand); v3.setRowStyle(TOTALROW); v3.setNarration(TOTALSTRING); majorCodeList.add(v3); return majorCodeList; } public void getCOA() { final List<CChartOfAccounts> coaList = getPersistenceService().findAllBy( "from CChartOfAccounts where length(glcode)=?", majorCodeLength); for (final CChartOfAccounts coa : coaList) coaMap.put(coa.getGlcode(), coa.getName()); } @Action(value = "/budget/budgetReport-departmentWiseReport") public String departmentWiseReport() { return "dept"; } @ValidationErrorPage(value = "dept") @Action(value = "/budget/budgetReport-printDepartmentWiseReport") public String printDepartmentWiseReport() { try { validateFinancialYear(); } catch (final ValidationException e) { throw new ValidationException(Arrays.asList(new ValidationError(e.getErrors().get(0).getMessage(), e.getErrors().get(0).getMessage()))); } /* * catch (final Exception e) { throw new * ValidationException(Arrays.asList(new * ValidationError(e.getMessage(), e.getMessage()))); } */ return "print"; } @Action(value = "/budget/budgetReport-generateDepartmentWiseXls") public String generateDepartmentWiseXls() throws JRException, IOException { validateFinancialYear(); populateData(); inputStream = reportHelper.exportXls(inputStream, DEPTWISEPATH, getParamMap(), budgetReportList); return "department-XLS"; } @Action(value = "/budget/budgetReport-generateDepartmentWisePdf") public String generateDepartmentWisePdf() throws JRException, IOException { validateFinancialYear(); populateData(); inputStream = reportHelper.exportPdf(inputStream, DEPTWISEPATH, getParamMap(), budgetReportList); return "department-PDF"; } @Action(value = "/budget/budgetReport-ajaxGenerateDepartmentWiseHtml") public String ajaxGenerateDepartmentWiseHtml() { populateData(); inputStream = reportHelper.exportHtml(inputStream, DEPTWISEPATH, getParamMap(), budgetReportList, "pt"); return "department-HTML"; } public BudgetReport getBudgetReport() { return budgetReport; } public void setBudgetReport(final BudgetReport budgetReport) { this.budgetReport = budgetReport; } protected void setRelatedEntitesOn() { if (budgetReport.getDepartment() == null || budgetReport.getDepartment().getCode() == null) budgetReport.setDepartment(null); else budgetReport.setDepartment(microserviceUtils.getDepartmentByCode(budgetReport.getDepartment().getCode())); if (budgetReport.getFinancialYear() != null) budgetReport.setFinancialYear((CFinancialYear) getPersistenceService().find("from CFinancialYear where id=?", budgetReport.getFinancialYear().getId())); } protected void validateFinancialYear() { if (budgetReport.getFinancialYear() == null || budgetReport.getFinancialYear().getId() == null) throw new ValidationException(Arrays.asList(new ValidationError("report.financialyear.not.selected", "report.financialyear.not.selected"))); } protected String getBudgetType(final String finalStatus) { String isBeRe = "BE"; final Budget budget = (Budget) persistenceService .find("from Budget where financialYear.id=? and parent is null and isPrimaryBudget=true and isActiveBudget=true and isBeRe='RE' and status.code=?", budgetReport.getFinancialYear().getId(), finalStatus); if (budget != null) isBeRe = "RE"; return isBeRe; } protected void addEmptyRow() { budgetReportList.add(new BudgetReportView("", "", "", null, null, null)); } protected String getQueryForSelectedType(final String code, final Map<String, Object> params) { if (budgetReport.getType() == null) return ""; if (!"ALL".equalsIgnoreCase(budgetReport.getType())) if ("IE".equalsIgnoreCase(budgetReport.getType())) return String.format("and (bd.budgetGroup.%s.type='I' or bd.budgetGroup.%s.type='E') ", code, code); else { params.put("type", budgetReport.getType().toCharArray()[0]); return String.format("and bd.budgetGroup.%s.type=:type", code); } return ""; } @ReadOnly protected Map<String, Object> getParamMap() { Map<String, Object> paramMap = new HashMap<String, Object>(); String ulbGrade = microserviceUtils.getHeaderNameForTenant().toUpperCase(); paramMap.put("ulbName", environment.getProperty(ulbGrade,ulbGrade)); paramMap.put("finYear", budgetReport.getFinancialYear().getFinYearRange()); if (onSaveOrForward) paramMap = getReportConfigs(paramMap); if (budgetReport.getType() != null) paramMap.put("type", BudgetReport.getValueFor(budgetReport.getType())); return paramMap; } /** * */ private Map<String, Object> getReportConfigs(final Map<String, Object> paramMap) { if (financialYearForRE == null) { final Long finYearForRE = getFinYearForRE(); if (finYearForRE == budgetReport.getFinancialYear().getId()) { final CFinancialYear finYear = getFinYear("next"); financialYearForBE = finYear; } else financialYearForBE = budgetReport.getFinancialYear(); } final List<AppConfigValues> list = appConfigValuesService.getConfigValuesByModuleAndKey(Constants.EGF, "budget_toplevel_approver_designation"); final String value = list.get(0).getValue(); // TODO: Now employee is extending user so passing userid to get assingment -- changes done by Vaibhav final Assignment empAssignment = eisCommonService.getLatestAssignmentForEmployeeByToDate(ApplicationThreadLocals.getUserId(), new Date()); final Designation designation = empAssignment.getDesignation(); if (designation.getName().equalsIgnoreCase(value)) finalApprover = true; canViewApprovedAmount = budgetDetailService.canViewApprovedAmount(persistenceService, null); if (!canViewApprovedAmount && !finalApprover) path = WORKINGCOPYWITHONLYPROPOSALS; else if (finalApprover) path = WORKINGCOPYFORFINALAPPROVER; else path = WORKINGCOPYWITHALLMOUNTS; if (departmentBudget) path = WORKINGCOPYFORFINALAPPROVER; paramMap.put("financialYearForRE", financialYearForRE.getFinYearRange()); paramMap.put("financialYearForBE", financialYearForBE.getFinYearRange()); paramMap.put("heading", " FUNCTIONWISE BUDGET SUMMARY "); return paramMap; } protected Map<String, String> getReferenceNumber(final String appConfigKey) { final Map<String, String> referenceNo = new HashMap<String, String>(); //TODO THIS HAS TO BE CHANGED, THIS WILL RETURN UNDESIRED RESULT final List<AppConfigValues> appConfigValues = appConfigValuesService.getConfigValuesByModuleAndKeyLike(FinancialConstants.MODULE_NAME_APPCONFIG, appConfigKey + "-%"); for (final AppConfigValues appConfigVal : appConfigValues) referenceNo.put(appConfigVal.getConfig().getKeyName().split("-")[1], appConfigVal.getValue()); return referenceNo; } protected String getFinalStatus() { return getAppConfigValueFor(Constants.EGF, "budget_final_approval_status"); } protected String getAppConfigValueFor(final String module, final String key) { return appConfigValuesService.getConfigValuesByModuleAndKey(module, key).get(0).getValue(); } @ReadOnly protected void populateData() { final String finalStatus = getFinalStatus(); final String isBeRe = getBudgetType(finalStatus); String deptQuery = ""; if (budgetReport.getDepartment() != null && budgetReport.getDepartment().getCode() != null && budgetReport.getDepartment().getCode() != "" && !"".equals(budgetReport.getDepartment().getCode())) deptQuery = " and bd.executingDepartment=:execDept "; getBudgetReappropriationAmt(); final String budgetType = BudgetReport.getValueFor(budgetReport.getType()); if (budgetType != null && !"ALL".equals(budgetReport.getType())) budgetReportList.add(new BudgetReportView("", budgetType.toUpperCase() + " BUDGET SUMMARY", "", null, null, null)); // budgetdetails for all mincode final LinkedList<BudgetDetail> budgetDetails = new LinkedList<BudgetDetail>(); fetchBudgetDetails(budgetDetails, deptQuery, finalStatus, isBeRe, "minCode"); // budgetdetails for all majorcode fetchBudgetDetails(budgetDetails, deptQuery, finalStatus, isBeRe, "majorCode"); populateSummarySection(budgetDetails, isBeRe); addRowsToReport(budgetDetails, isBeRe); } public Map<String, BigDecimal> getMajorCodeToAmountMap(final List<BudgetDetail> budgetDetails) { final Map<String, BigDecimal> map = new HashMap<String, BigDecimal>(); for (final BudgetDetail entry : budgetDetails) { String glCode = ""; if (entry.getBudgetGroup().getMajorCode() == null) glCode = entry.getBudgetGroup().getMinCode().getMajorCode(); else glCode = entry.getBudgetGroup().getMajorCode().getMajorCode(); final BigDecimal approvedAmount = entry.getApprovedAmount() == null ? BigDecimal.ZERO : entry.getApprovedAmount(); final BigDecimal totalAmount = approvedAmount; if (map.get(glCode) != null) map.put(glCode, map.get(glCode).add(totalAmount)); else map.put(glCode, totalAmount); } return map; } public String getUniqueMajorCodesAsString(final Map<String, BigDecimal> majorCodeToAmountMap) { String result = ""; final Set<String> uniqueMajorCodes = majorCodeToAmountMap.keySet(); for (final String row : uniqueMajorCodes) if (row != null) result = result.concat("'").concat(row).concat("',"); if (result.length() > 0) result = result.substring(0, result.length() - 1); return result; } public BigDecimal getMajorCodeTotals(final Map<String, BigDecimal> majorCodeToAmountMap) { BigDecimal sum = BigDecimal.ZERO; for (final Entry<String, BigDecimal> entry : majorCodeToAmountMap.entrySet()) if (entry.getValue() != null) sum = sum.add(entry.getValue()); return sum; } public BigDecimal getMajorCodeApproriationTotals(final Map<String, BigDecimal> majorCodeToApproriationAmountMap) { BigDecimal sum = BigDecimal.ZERO; for (final Entry<String, BigDecimal> entry : majorCodeToApproriationAmountMap.entrySet()) if (entry.getValue() != null) sum = sum.add(entry.getValue()); return sum; } void populateSummarySection(final List<BudgetDetail> budgetDetails, final String isBeRe) { final Map<String, BigDecimal> majorCodeToAmountMap = getMajorCodeToAmountMap(budgetDetails); final Map<String, BigDecimal> majorCodeToAppropriationAmountMap = getMajorCodeToAppropriationAmountMap(budgetDetails); final Map<String, String> referenceNo = getReferenceNumber("departmentWiseBudgetReport"); final String uniqueMajorCodesAsString = getUniqueMajorCodesAsString(majorCodeToAmountMap); if ("".equals(uniqueMajorCodesAsString)) { budgetReportList.add(new BudgetReportView("", "No records found", "", null, null, null)); return; } final List<CChartOfAccounts> chartOfAccounts = getPersistenceService().findAllBy( "from CChartOfAccounts where glCode in (?)", uniqueMajorCodesAsString); for (final CChartOfAccounts account : chartOfAccounts) { final BigDecimal approved = majorCodeToAmountMap.get(account.getMajorCode()); final BigDecimal reApp = majorCodeToAppropriationAmountMap.get(account.getMajorCode()); if ("RE".equalsIgnoreCase(isBeRe) && !getConsiderReAppropriationAsSeperate()) budgetReportList.add(new BudgetReportView("", account.getMajorCode() + "-" + account.getName(), referenceNo .get(account.getMajorCode()), approved.add(reApp), BigDecimal.ZERO, approved.add(reApp))); else budgetReportList.add(new BudgetReportView("", account.getMajorCode() + "-" + account.getName(), referenceNo .get(account.getMajorCode()), approved, reApp, approved.add(reApp))); } if (!chartOfAccounts.isEmpty()) { final BigDecimal majorCodeApprovedTotals = getMajorCodeTotals(majorCodeToAmountMap); final BigDecimal majorCodeApproriationTotals = getMajorCodeApproriationTotals(majorCodeToAppropriationAmountMap); if ("RE".equalsIgnoreCase(isBeRe) && !getConsiderReAppropriationAsSeperate()) budgetReportList.add(new BudgetReportView("", "Total", "", majorCodeApprovedTotals .add(majorCodeApproriationTotals), BigDecimal.ZERO, majorCodeApprovedTotals.add(majorCodeApproriationTotals))); else budgetReportList.add(new BudgetReportView("", "Total", "", majorCodeApprovedTotals, majorCodeApproriationTotals, majorCodeApprovedTotals .add(majorCodeApproriationTotals))); } addEmptyRow(); } private Map<String, BigDecimal> getMajorCodeToAppropriationAmountMap(final List<BudgetDetail> budgetDetails) { final Map<String, BigDecimal> map = new HashMap<String, BigDecimal>(); for (final BudgetDetail entry : budgetDetails) { String glCode = ""; if (entry.getBudgetGroup().getMajorCode() == null) glCode = entry.getBudgetGroup().getMinCode().getMajorCode(); else glCode = entry.getBudgetGroup().getMajorCode().getMajorCode(); final BigDecimal reAppAmount = reAppropriationMap.get(entry.getId()); final BigDecimal totalAmount = reAppAmount == null ? BigDecimal.ZERO : reAppAmount; if (map.get(glCode) != null) map.put(glCode, map.get(glCode).add(totalAmount)); else map.put(glCode, totalAmount); } return map; } /* * Assumes budgetDetails are sorted by deptId,glCode */ void addRowsToReport(List<BudgetDetail> budgetDetails, final String isBeRe) { String deptCode = ""; BudgetReportView row = new BudgetReportView(null, null, null, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO); String glcode = null; String glName; BigDecimal sum = BigDecimal.ZERO; BigDecimal appropriationSum = BigDecimal.ZERO; BigDecimal approvedAmount = BigDecimal.ZERO; BigDecimal reAppAmount = BigDecimal.ZERO; budgetDetails = budgetDetailService.sortByDepartmentName(budgetDetails); // not interested in major code details for (final BudgetDetail budgetDetail : budgetDetails) { // if(budgetDetail.getBudgetGroup().getMajorCode()!=null){ // continue; // } // details for next department have started if (budgetDetail.getExecutingDepartment() != null && !deptCode.equals(budgetDetail.getExecutingDepartment())) { if (!deptCode.equals("")) if ("RE".equalsIgnoreCase(isBeRe) && !getConsiderReAppropriationAsSeperate()) budgetReportList.add(new BudgetReportView("", "Total", "", sum.add(appropriationSum), BigDecimal.ZERO, sum.add(appropriationSum))); else budgetReportList.add(new BudgetReportView("", "Total", "", sum, appropriationSum, sum .add(appropriationSum))); sum = BigDecimal.ZERO; appropriationSum = BigDecimal.ZERO; addEmptyRow(); budgetReportList.add(new BudgetReportView("", microserviceUtils.getDepartmentByCode(budgetDetail.getExecutingDepartment()).getName().toUpperCase(), "", null, null, null)); glcode = null; } if(budgetDetail.getExecutingDepartment() != null){ deptCode = budgetDetail.getExecutingDepartment(); } // next glcode within same department if (!getGlCode(budgetDetail).equals(glcode)) { glcode = getGlCode(budgetDetail); glName = getGlName(budgetDetail); row = new BudgetReportView(glcode, glName, "", BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO); budgetReportList.add(row); approvedAmount = BigDecimal.ZERO; reAppAmount = BigDecimal.ZERO; } BigDecimal tempApprAmnt = budgetDetail.getApprovedAmount() == null ? BigDecimal.ZERO : budgetDetail.getApprovedAmount(); approvedAmount = approvedAmount.add(tempApprAmnt); BigDecimal tempReAppAmnt = reAppropriationMap.get(budgetDetail.getId()) == null ? BigDecimal.ZERO : reAppropriationMap.get(budgetDetail.getId()); reAppAmount = reAppAmount.add(tempReAppAmnt); if ("RE".equalsIgnoreCase(isBeRe) && !getConsiderReAppropriationAsSeperate()) { row.setAmount(approvedAmount.add(reAppAmount == null ? BigDecimal.ZERO : reAppAmount)); row.setAppropriationAmount(BigDecimal.ZERO); row.setTotalAmount(approvedAmount.add(reAppAmount == null ? BigDecimal.ZERO : reAppAmount)); } else { row.setAmount(approvedAmount); row.setAppropriationAmount(reAppAmount == null ? BigDecimal.ZERO : reAppAmount); row.setTotalAmount(approvedAmount.add(reAppAmount == null ? BigDecimal.ZERO : reAppAmount)); } sum = sum.add(tempApprAmnt); appropriationSum = appropriationSum.add(tempReAppAmnt); } if (!budgetDetails.isEmpty()) if ("RE".equalsIgnoreCase(isBeRe) && !getConsiderReAppropriationAsSeperate()) budgetReportList.add(new BudgetReportView("", "Total", "", sum.add(appropriationSum), BigDecimal.ZERO, sum .add(appropriationSum))); else budgetReportList.add(new BudgetReportView("", "Total", "", sum, appropriationSum, sum.add(appropriationSum))); } private String getGlName(final BudgetDetail budgetDetail) { final BudgetGroup budgetGroup = budgetDetail.getBudgetGroup(); return budgetGroup.getMinCode() == null ? budgetGroup.getMajorCode().getName() : budgetGroup.getMinCode().getName(); } private String getGlCode(final BudgetDetail budgetDetail) { final BudgetGroup budgetGroup = budgetDetail.getBudgetGroup(); return budgetGroup.getMinCode() == null ? budgetGroup.getMajorCode().getGlcode() : budgetGroup.getMinCode().getGlcode(); } void fetchBudgetDetails(final List<BudgetDetail> budgetDetails, final String deptQuery, final String finalStatus, final String budgetType, final String code) { final Map<String, Object> params = new HashMap<>(); final Query query = persistenceService.getSession() .createQuery(new StringBuilder(" from BudgetDetail bd where bd.budget.financialYear.id=:finYearId ") .append(deptQuery).append(" and bd.budget.isbere=:isBeRe and bd.budget.status.code =:status ") .append(getQueryForSelectedType(code, params)) .append(String.format(" order by bd.budgetGroup.%s.glcode", code)).toString()) .setParameter("finYearId", budgetReport.getFinancialYear().getId(), LongType.INSTANCE) .setParameter("isBeRe", budgetType, StringType.INSTANCE) .setParameter("status", finalStatus, StringType.INSTANCE); if (!deptQuery.equals("")) { query.setParameter("execDept", budgetReport.getDepartment().getCode(), StringType.INSTANCE); } persistenceService.populateQueryWithParams(query, params); final List<BudgetDetail> results = query.list(); budgetDetails.addAll(results); } private void getBudgetReappropriationAmt() { final String status = getFinalStatus(); final List<Object[]> list = getPersistenceService() .findAllBy( "select sum(br.additionAmount)-sum(br.deductionAmount),br.budgetDetail.id from BudgetReAppropriation br where br.status = (select id from EgwStatus where moduletype='BudgetReAppropriation' " + "and description='Approved') group by br.budgetDetail.id"); if (!list.isEmpty() && list.size() != 0) for (final Object[] obj : list) reAppropriationMap.put(obj[1], (BigDecimal) obj[0]); } public boolean isOnSaveOrForward() { return onSaveOrForward; } public void setOnSaveOrForward(final boolean onSaveOrForward) { this.onSaveOrForward = onSaveOrForward; } public BudgetDetailService getBudgetDetailService() { return budgetDetailService; } public void setBudgetDetailService(final BudgetDetailService budgetDetailService) { this.budgetDetailService = budgetDetailService; } // ----------------------------------------------working copy starts here private List<Object> getDataFunctionWiseForWorkingCopy() { getMincodeDataForWorkingCopy(); getMajorcodeDataForWorkingCopy(); if (budgetDetailListForRE.isEmpty()) return budgetReportList; String deptCode = ""; Long functionId = 0L; String type = "", majorCode = "", glcode = "", glType = "", glName = "", tempMajorCode = ""; BigDecimal reProposalTotalLocal = BigDecimal.ZERO; BigDecimal beProposalTotalLocal = BigDecimal.ZERO; BigDecimal reRecomTotalLocal = BigDecimal.ZERO; BigDecimal beRecomTotalLocal = BigDecimal.ZERO; boolean printed = true; boolean isFirst = true; boolean majorcodewise = false; refNoMap = getReferenceNumber("functionWiseBudgetReport"); getCOA(); getBudgetReappropriationAmt(); loadAmountForMajorcodewiseForWorkingCopy(budgetReport.getFinancialYear(), budgetReport.getDepartment(), budgetReport.getFunction()); for (final BudgetDetail detail : budgetDetailListForRE) { BudgetDetail beDetail = new BudgetDetail(); for (final BudgetDetail detail1 : budgetDetailListForBE) if (detail.getExecutingDepartment().equals(detail1.getExecutingDepartment()) && detail.getFunction().getId() == detail1.getFunction().getId() && detail.getBudgetGroup().getId() == detail1.getBudgetGroup().getId()) { beDetail = detail1; break; } if (detail.getExecutingDepartment() == null || detail.getFunction() == null) continue; // reAppropriationAmt = // reAppropriationMap.get(detail.getId())==null?BigDecimal.ZERO:reAppropriationMap.get(detail.getId()); if (detail.getBudgetGroup().getMajorCode() == null) { glcode = getGlCode(detail); glType = detail.getBudgetGroup().getMinCode().getType().toString(); glName = getGlName(detail); } else { glcode = detail.getBudgetGroup().getMajorCode().getGlcode(); glType = detail.getBudgetGroup().getMajorCode().getType().toString(); glName = detail.getBudgetGroup().getMajorCode().getName(); majorcodewise = true; } tempMajorCode = glcode.substring(0, majorCodeLength); if (!detail.getExecutingDepartment().equals(deptCode)) // for // dept // heading { if (reProposalTotalLocal.compareTo(BigDecimal.ZERO) != 0 && !isFirst) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, reProposalTotalLocal, beProposalTotalLocal, reRecomTotalLocal, beRecomTotalLocal, TOTALROW)); reProposalTotalLocal = BigDecimal.ZERO; beProposalTotalLocal = BigDecimal.ZERO; reRecomTotalLocal = BigDecimal.ZERO; beRecomTotalLocal = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, microserviceUtils.getDepartmentByCode(detail.getExecutingDepartment()).getName(), EMPTYSTRING, null, null, null, "deptrow")); type = ""; functionId = null; majorCode = ""; } if (!glType.equals(type))// for type heading { if (reProposalTotalLocal.compareTo(BigDecimal.ZERO) != 0 && !isFirst) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, reProposalTotalLocal, reRecomTotalLocal, beProposalTotalLocal, beRecomTotalLocal, TOTALROW)); reProposalTotalLocal = BigDecimal.ZERO; beProposalTotalLocal = BigDecimal.ZERO; reRecomTotalLocal = BigDecimal.ZERO; beRecomTotalLocal = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, "FUNCTIONWISE " + BudgetReport.getValueFor(glType).toUpperCase() + " BUDGET SUMMARY", refNoMap.get(BudgetReport.getValueFor(glType)), null, null, null, "typerow")); functionId = null; majorCode = ""; } if (!detail.getFunction().getId().equals(functionId)) // for // function // heading { if (reProposalTotalLocal.compareTo(BigDecimal.ZERO) != 0 && !isFirst) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, reProposalTotalLocal, reRecomTotalLocal, beProposalTotalLocal, beRecomTotalLocal, TOTALROW)); reProposalTotalLocal = BigDecimal.ZERO; beProposalTotalLocal = BigDecimal.ZERO; reRecomTotalLocal = BigDecimal.ZERO; beRecomTotalLocal = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, "FUNCTION CENTRE-" + detail.getFunction().getName(), EMPTYSTRING, null, null, null, "functionrow")); final List<Object> majorCodeList = getAmountForMajorcodewiseForWorkingCopy(detail.getExecutingDepartment(), detail.getFunction() .getId(), glType); // majorcodewise total budgetReportList.addAll(majorCodeList); printed = false; majorCode = ""; } if (!tempMajorCode.equals(majorCode) && detail.getBudgetGroup().getMajorCode() == null)// majorcodewise // - // heading { if (printed) { budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, reProposalTotalLocal, reRecomTotalLocal, beProposalTotalLocal, beRecomTotalLocal, TOTALROW)); reProposalTotalLocal = BigDecimal.ZERO; beProposalTotalLocal = BigDecimal.ZERO; reRecomTotalLocal = BigDecimal.ZERO; beRecomTotalLocal = BigDecimal.ZERO; } budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, refNoMap.get(tempMajorCode), tempMajorCode + "-" + coaMap.get(tempMajorCode), "", null, null, null, "majorcodeheadingrow")); } // detail if (detail.getExecutingDepartment() != null && detail.getFunction() != null && detail.getBudgetGroup().getMajorCode() == null) if (onSaveOrForward && !canViewApprovedAmount) budgetReportList.add(new BudgetReportView(detail.getExecutingDepartment(), detail.getFunction() .getCode(), glcode, glName, EMPTYSTRING, detail.getOriginalAmount(), detail.getApprovedAmount(), beDetail.getOriginalAmount(), beDetail.getApprovedAmount(), "detailrow")); else budgetReportList.add(new BudgetReportView(detail.getExecutingDepartment(), detail.getFunction() .getCode(), glcode, glName, EMPTYSTRING, detail.getOriginalAmount(), detail.getApprovedAmount(), beDetail.getOriginalAmount(), beDetail.getApprovedAmount(), "detailrow")); if (detail.getExecutingDepartment() != null) deptCode = detail.getExecutingDepartment(); if (detail.getFunction() != null) functionId = detail.getFunction().getId(); type = glType; majorCode = tempMajorCode; reProposalTotalLocal = reProposalTotalLocal.add(detail.getOriginalAmount()); beProposalTotalLocal = beProposalTotalLocal.add(beDetail.getOriginalAmount()); reRecomTotalLocal = reRecomTotalLocal.add(detail.getApprovedAmount()); beRecomTotalLocal = beRecomTotalLocal.add(beDetail.getApprovedAmount()); printed = true; isFirst = false; } if (reProposalTotalLocal.compareTo(BigDecimal.ZERO)!=0 && !majorcodewise) budgetReportList.add(new BudgetReportView(EMPTYSTRING, EMPTYSTRING, EMPTYSTRING, TOTALSTRING, EMPTYSTRING, reProposalTotalLocal, reRecomTotalLocal, beProposalTotalLocal, beRecomTotalLocal, TOTALROW)); return budgetReportList; } /** * 1.get whole Sum for the function 2.get DepartmentWise sum for the function 3.Get Individual amount * * * @return */ private List getDataForGlance() { final List<BudgetReportView> budgetAtGlanceList = new ArrayList<BudgetReportView>(); budgetAtGlanceList.addAll(getFunctionwiseSumForGlance()); budgetAtGlanceList.addAll(getBudgetWiseSumAndDetail()); return budgetAtGlanceList; } /** * get Sum for Each Budget/Department(Budget and Department are same) and details * */ private List<BudgetReportView> getBudgetWiseSumAndDetail() { // getSumforEachDepartment final List<BudgetReportView> ReportList = new ArrayList<BudgetReportView>(); final LinkedHashMap<String, BudgetReportView> function_deptSumMap = new LinkedHashMap<String, BudgetReportView>(); // Fetch For RE List params = new ArrayList(); StringBuffer query = new StringBuffer("select function.name,executingDepartment.deptCode,sum(originalAmount),sum(approvedAmount) ") .append("from BudgetDetail bd where bd.budget.financialYear.id=?") .append(" and bd.budget.isbere='RE' "); params.add(budgetReport.getFinancialYear().getId()); if (budgetReport.getFunction() != null && budgetReport.getFunction().getId() != null && budgetReport.getFunction().getId() != 0) { query.append(" and bd.function.id=?"); params.add(budgetReport.getFunction().getId()); } query.append(" group by function.name,executingDepartment.deptCode order by function.name,executingDepartment.deptCode"); List<Object[]> findAllBy = persistenceService.findAllBy(query.toString(), params); for (final Object[] o : findAllBy) { final BudgetReportView bv = new BudgetReportView(); bv.setNarration((String) o[0]); bv.setDeptCode((String) o[1]); bv.setFunctionCode(""); bv.setReProposalAmount(o[2] != null ? new BigDecimal(o[2].toString()) : BigDecimal.ZERO); bv.setReRecomAmount(o[3] != null ? new BigDecimal(o[3].toString()) : BigDecimal.ZERO); bv.setRowStyle("majorcodeheadingrow"); function_deptSumMap.put((String) o[0] + "-" + (String) o[1], bv); } // Fetch For BE params = new ArrayList(); query = new StringBuffer("select function.name,executingDepartment.deptCode,sum(originalAmount),sum(approvedAmount) ") .append("from BudgetDetail bd where bd.budget.financialYear.id=?") .append(" and bd.budget.isbere='BE' "); params.add(getFinYear("next").getId()); if (budgetReport.getFunction() != null && budgetReport.getFunction().getId() != null && budgetReport.getFunction().getId() != 0) { query.append(" and bd.function.id=?"); params.add(budgetReport.getFunction().getId()); } query.append(" group by function.name, executingDepartment.deptCode order by function.name,executingDepartment.deptCode"); findAllBy = persistenceService.findAllBy(query.toString(), params); for (final Object[] o : findAllBy) { final String key = (String) o[0] + "-" + (String) o[1]; BudgetReportView bv = function_deptSumMap.get(key); // if RE dont have a function But BE has (only old data) if (bv == null) { bv = new BudgetReportView(); bv.setNarration((String) o[0]); bv.setDeptCode((String) o[1]); bv.setFunctionCode(""); bv.setBeProposalAmount(o[2] != null ? new BigDecimal(o[2].toString()) : BigDecimal.ZERO); bv.setBeRecomAmount(o[3] != null ? new BigDecimal(o[3].toString()) : BigDecimal.ZERO); function_deptSumMap.put((String) o[0] + "-" + (String) o[1], bv); continue; } else { bv.setBeProposalAmount(o[2] != null ? new BigDecimal(o[2].toString()) : BigDecimal.ZERO); bv.setBeRecomAmount(o[3] != null ? new BigDecimal(o[3].toString()) : BigDecimal.ZERO); } } // getDetails params = new ArrayList(); query = new StringBuffer(" from BudgetDetail bd where bd.budget.financialYear.id=?") .append(" and bd.budget.isbere='RE' "); params.add(budgetReport.getFinancialYear().getId()); if (budgetReport.getFunction() != null && budgetReport.getFunction().getId() != null && budgetReport.getFunction().getId() != 0) { query.append(" and bd.function.id=?"); params.add(budgetReport.getFunction().getId()); } query.append(" order by function.name,executingDepartment.deptCode"); final List<BudgetDetail> details = persistenceService.findAllBy(query.toString(), params); final LinkedHashMap<String, List<BudgetReportView>> function_dept_DetailedMap = new LinkedHashMap<String, List<BudgetReportView>>(); final LinkedHashMap<String, List<BudgetDetail>> function_dept_DetailedBudgetMap = new LinkedHashMap<String, List<BudgetDetail>>(); String key = ""; String glcode; String glName; for (final BudgetDetail detail : details) { key = detail.getFunction().getName() + "-" + detail.getExecutingDepartment(); if (function_dept_DetailedBudgetMap.get(key) == null) { final List<BudgetDetail> fun_dept_dtlList = new ArrayList<BudgetDetail>(); function_dept_DetailedBudgetMap.put(key, fun_dept_dtlList); } function_dept_DetailedBudgetMap.get(key).add(detail); } // Fetch For BE params = new ArrayList(); query = new StringBuffer("from BudgetDetail bd where bd.budget.financialYear.id=?") .append(" and bd.budget.isbere='BE' "); params.add(getFinYear("next").getId()); if (budgetReport.getFunction() != null && budgetReport.getFunction().getId() != null && budgetReport.getFunction().getId() != 0) { query.append(" and bd.function.id=?"); params.add(budgetReport.getFunction().getId()); } query.append(" order by function.name, executingDepartment.deptCode"); final List<BudgetDetail> beDetails = persistenceService.findAllBy(query.toString(), params); for (final BudgetDetail beDetail : beDetails) { key = beDetail.getFunction().getName() + "-" + beDetail.getExecutingDepartment(); for (final BudgetDetail reDetail : function_dept_DetailedBudgetMap.get(key)) if (reDetail == null) { if (beDetail.getBudgetGroup().getMajorCode() == null) { glcode = getGlCode(beDetail); beDetail.getBudgetGroup().getMinCode().getType().toString(); glName = getGlName(beDetail); } else { glcode = beDetail.getBudgetGroup().getMajorCode().getGlcode(); beDetail.getBudgetGroup().getMajorCode().getType().toString(); glName = beDetail.getBudgetGroup().getMajorCode().getName(); } final BudgetReportView bv = new BudgetReportView(); bv.setNarration(glName); bv.setDeptCode(beDetail.getExecutingDepartment()); bv.setGlCode(glcode); bv.setFunctionCode(reDetail.getFunction().getCode()); bv.setReProposalAmount(reDetail.getOriginalAmount()); bv.setReRecomAmount(reDetail.getApprovedAmount()); bv.setRowStyle("typerow"); bv.setBeProposalAmount(beDetail.getOriginalAmount()); bv.setBeRecomAmount(beDetail.getApprovedAmount()); function_dept_DetailedMap.get(key).add(bv); break; } else if (beDetail.compareTo(reDetail)) { if (function_dept_DetailedMap.get(key) == null) { final List<BudgetReportView> fun_dept_dtlList = new ArrayList<BudgetReportView>(); function_dept_DetailedMap.put(key, fun_dept_dtlList); } if (beDetail.getBudgetGroup().getMajorCode() == null) { glcode = getGlCode(beDetail); beDetail.getBudgetGroup().getMinCode().getType().toString(); glName = getGlName(beDetail); } else { glcode = beDetail.getBudgetGroup().getMajorCode().getGlcode(); beDetail.getBudgetGroup().getMajorCode().getType().toString(); glName = beDetail.getBudgetGroup().getMajorCode().getName(); } final BudgetReportView bv = new BudgetReportView(); bv.setNarration(glName); bv.setDeptCode(beDetail.getExecutingDepartment()); bv.setGlCode(glcode); bv.setFunctionCode(reDetail.getFunction().getCode()); bv.setReProposalAmount(reDetail.getOriginalAmount()); bv.setReRecomAmount(reDetail.getApprovedAmount()); bv.setBeProposalAmount(beDetail.getOriginalAmount()); bv.setBeRecomAmount(beDetail.getApprovedAmount()); function_dept_DetailedMap.get(key).add(bv); break; } } // Now add Individual into reportListfu for (final String tempKey : function_deptSumMap.keySet()) { final BudgetReportView bvHead = new BudgetReportView(); bvHead.setNarration(function_deptSumMap.get(tempKey).getNarration()); bvHead.setRowStyle("majorcodeheadingrow"); ReportList.add(bvHead); // ReportList.add(function_deptSumMap.get(tempKey)); ReportList.addAll(function_dept_DetailedMap.get(tempKey)); final BudgetReportView bvTotal = new BudgetReportView(); bvTotal.setNarration("TOTAL"); bvTotal.setBeProposalAmount(function_deptSumMap.get(tempKey).getBeProposalAmount()); bvTotal.setReProposalAmount(function_deptSumMap.get(tempKey).getReProposalAmount()); bvTotal.setBeRecomAmount(function_deptSumMap.get(tempKey).getBeRecomAmount()); bvTotal.setReRecomAmount(function_deptSumMap.get(tempKey).getReRecomAmount()); bvTotal.setRowStyle(TOTALROW); ReportList.add(bvTotal); } return ReportList; } /** * */ @SuppressWarnings("unchecked") private List<BudgetReportView> getFunctionwiseSumForGlance() { final List<BudgetReportView> ReportList = new ArrayList<BudgetReportView>(); // Fetch For RE List params = new ArrayList(); StringBuffer query = new StringBuffer("select function.name,sum(originalAmount),sum(approvedAmount) ") .append(" from BudgetDetail bd where bd.budget.financialYear.id=?") .append(" and bd.budget.isbere='RE' "); params.add(budgetReport.getFinancialYear().getId()); if (budgetReport.getFunction() != null && budgetReport.getFunction().getId() != null && budgetReport.getFunction().getId() != 0) { query.append(" and bd.function.id=?") .append(" group by function.name order by function.name"); params.add(budgetReport.getFunction().getId()); } List<Object[]> findAllBy = persistenceService.findAllBy(query.toString(), params); for (final Object[] o : findAllBy) { final BudgetReportView bv = new BudgetReportView(); bv.setNarration((String) o[0]); bv.setFunctionCode(""); bv.setReProposalAmount(o[1] != null ? new BigDecimal(o[1].toString()) : BigDecimal.ZERO); bv.setReRecomAmount(o[2] != null ? new BigDecimal(o[2].toString()) : BigDecimal.ZERO); bv.setRowStyle("functionrow"); ReportList.add(bv); } // Fetch For BE params = new ArrayList(); query = new StringBuffer("select function.name,sum(originalAmount),sum(approvedAmount)") .append(" from BudgetDetail bd where bd.budget.financialYear.id=?") .append(" and bd.budget.isbere='BE' "); params.add(getFinYear("next").getId()); if (budgetReport.getFunction() != null && budgetReport.getFunction().getId() != null && budgetReport.getFunction().getId() != 0) { query.append(" and bd.function.id=?"); params.add(budgetReport.getFunction().getId()); } query.append(" group by function.name"); findAllBy = persistenceService.findAllBy(query.toString(), params); for (final BudgetReportView bv : ReportList) for (final Object[] o : findAllBy) if (bv.getNarration().equalsIgnoreCase((String) o[0])) { bv.setBeProposalAmount(o[1] != null ? new BigDecimal(o[1].toString()) : BigDecimal.ZERO); bv.setBeRecomAmount(o[2] != null ? new BigDecimal(o[2].toString()) : BigDecimal.ZERO); break; } return ReportList; } /** * @param string --- "previous" for previous FinancialYearId --- "next" for next FinancialyearId * @return */ private CFinancialYear getFinYear(final String option) { final Calendar cal = Calendar.getInstance(); CFinancialYear finYear = null; if (option.equalsIgnoreCase("previous")) { cal.setTime(budgetReport.getFinancialYear().getStartingDate()); cal.add(Calendar.DATE, -1); finYear = (CFinancialYear) persistenceService.find("from CFinancialYear c where c.endingDate=?", cal.getTime()); if (finYear == null) throw new ValidationException(Arrays.asList(new ValidationError("next.financial.year.not.defined", "Previous financial year not defined"))); } else if (option.equalsIgnoreCase("next")) { cal.setTime(budgetReport.getFinancialYear().getEndingDate()); cal.add(Calendar.DATE, 1); finYear = (CFinancialYear) persistenceService.find("from CFinancialYear c where c.startingDate=?", cal.getTime()); if (finYear == null) throw new ValidationException(Arrays.asList(new ValidationError("next.financial.year.not.defined", "Next financial year not defined"))); } return finYear; } /** * @param finYearForRE * @return */ private Map<String, Map<String, Object>> getSqlForFinYear(final Long finYearForRE) { final Map<String, Map<String, Object>> queryMap = new HashMap<>(); final Map<String, Object> queryParams = new HashMap<>(); final StringBuilder sql = new StringBuilder(""); sql.append(" bd.budget.financialYear.id=:finYearId"); queryParams.put("finYearId", finYearForRE); if (budgetReport.getDepartment() != null && budgetReport.getDepartment().getId() != null) { sql.append(" and bd.executingDepartment=:execDept"); queryParams.put("execDept", budgetReport.getDepartment().getCode()); } if (budgetReport.getFunction() != null && budgetReport.getFunction().getId() != null) { sql.append(" and bd.function.id=:functionId"); queryParams.put("functionId", budgetReport.getFunction().getId()); } if (topBudget != null) { sql.append(" and bd.budget.id=:budgetId"); queryParams.put("budgetId", topBudget.getId()); } queryMap.put(sql.toString(), queryParams); return queryMap; } private Map<String, Map<String, Object>> getSqlForFinYearBE(final Long finYearForRE) { final Map<String, Map<String, Object>> queryMap = new HashMap<>(); final Map<String, Object> queryParams = new HashMap<>(); final StringBuilder sql = new StringBuilder(""); sql.append(" bd.budget.financialYear.id=:finYearId"); queryParams.put("finYearId", finYearForRE); if (budgetReport.getDepartment() != null && budgetReport.getDepartment().getId() != null) { sql.append(" and bd.executingDepartment.id=:execDept"); queryParams.put("execDept", budgetReport.getDepartment().getCode()); } if (budgetReport.getFunction() != null && budgetReport.getFunction().getId() != null) { sql.append(" and bd.function.id=:functionId"); queryParams.put("functionId", budgetReport.getFunction().getId()); } if (topBudget != null) { sql.append(" and bd.budget.referenceBudget.id=:budgetId"); queryParams.put("budgetId", topBudget.getId()); } queryMap.put(sql.toString(), queryParams); return queryMap; } private Long getFinYearForRE() { final Long finId = budgetReport.getFinancialYear().getId(); final Long budgetCount = (Long) persistenceService.find( "select count(*) from Budget b where b.financialYear.id=? and b.isbere='RE'", finId); if (budgetCount == 0) { final Date startingDate = budgetReport.getFinancialYear().getStartingDate(); final Calendar cal = Calendar.getInstance(); cal.setTime(startingDate); cal.add(Calendar.DATE, -1); final CFinancialYear prevFinyear = (CFinancialYear) persistenceService.find( "from CFinancialYear c where c.endingDate=?", cal.getTime()); if (prevFinyear == null) throw new ValidationException(Arrays.asList(new ValidationError("next.financial.year.not.defined", "Next financial year not defined"))); else { financialYearForRE = prevFinyear; return prevFinyear.getId(); } } else { financialYearForRE = budgetReport.getFinancialYear(); return budgetReport.getFinancialYear().getId(); } } public void setEisCommonService(final EisCommonService eisCommonService) { this.eisCommonService = eisCommonService; } private boolean getConsiderReAppropriationAsSeperate() { final List<AppConfigValues> appList = appConfigValuesService.getConfigValuesByModuleAndKey(Constants.EGF, "CONSIDER_RE_REAPPROPRIATION_AS_SEPARATE"); String appValue = "-1"; appValue = appList.get(0).getValue(); return "Y".equalsIgnoreCase(appValue); } }
54.70927
238
0.640524
12c7e541e131b5487856eb9e67c432d55c0e7d23
3,758
package de.geolykt.starloader.api.gui.screen; import org.jetbrains.annotations.NotNull; import de.geolykt.starloader.api.gui.Renderable; /** * A graphical component that can be added as a child object of a implementation of the {@link Screen} interface. * Due to how galimulator's component hierarchy works, not everything that looks like a component can be used, though * the SLAPI will lead efforts into making those available via this interface. */ public interface ScreenComponent extends Renderable { /** * Obtains the expected height of this component. * * @return The height of the component */ public int getHeight(); /** * Obtains the line wrapping metadata information that is assigned to this screen. * It should be honoured by the screen implementation unless the screen implementation is * making use of galimulator's dialog API at which time this method will be ignored * due to technical limitations. * * @return The assigned {@link LineWrappingInfo}. */ public @NotNull LineWrappingInfo getLineWrappingInfo(); /** * Obtains the most parent screen that this component belongs to. * As a rule of thumb, this should return the parent screen of the parent * component, unless they are located on two different screens for whatever reason. * * @return The parent screen */ public @NotNull Screen getParentScreen(); /** * Obtains the expected width of this component. * * @return The width of the component */ public int getWidth(); /** * Returns false if the other screen component is of another type as this component, otherwise true. * This is used for the {@link LineWrappingInfo#isWrapDifferentType()} method among other display-related things. * The implementation of this method should follow following guidelines: * <ul> * <li> It should be reflective: If this method is invoked on x with x as an argument, then it should return true.</li> * <li> It should be symmetric: If this method is invoked on x with y as an argument, then it should return the same * compared to when this method is invoked on y with x as an argument. </li> * <li> It should be transitive: If x.isSameType(y) is true and x.isSameType(z) is true, then y.isSameType(z) should * also be true.</li> * <li> It should (mostly) be consistent: Unless internal properties of the component(s) change, repeated invocations of * x.isSameType(y) should return the same return value. </li> * <li> It should be unintrusive: Invocations to this method should not change the state of the component. </li> * </ul> *<br/> * While most often a simple instanceof suffices, this may not always be the case. The simplest example would be * multiple implementations of the {@link TextScreenComponent}. Additionally the symmetric and transitive properties * of this method may be hard to achieve if the component's implementations stem from two different source extensions, * as the implementations may not be aware of each other, while still implementing a similar type. Thus usage of this * method should be performed with a grain of salt. * * @param component The component to compare this component to * @return Whether this component is of a similar type to the other component */ public boolean isSameType(@NotNull ScreenComponent component); @Override @Deprecated(forRemoval = true, since = "1.4.0") public default void render(float x, float y) { throw new UnsupportedOperationException("The camera of the parent object needs to be known in order to render the component."); } }
47.56962
135
0.709952
dd91588b81f2f2bac09765839bcf576a06bbfcf7
17,198
package be.peopleware.bean_IV; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import be.peopleware.exception_I.LocalizedMessageException; import be.peopleware.exception_I._Test_LocalizedMessageException; import be.peopleware.i18n_I.DefaultResourceBundleLoadStrategy; import be.peopleware.test_I.Test; import be.peopleware.test_I.java.lang._Test_String; import be.peopleware.test_I.java.lang._Test_Throwable; /** * @author Jan Dockx * @author PeopleWare n.v. */ public class _Test_PropertyException extends _Test_LocalizedMessageException { /* <section name="Meta Information"> */ //------------------------------------------------------------------ /** {@value} */ public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$ /** {@value} */ public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$ /** {@value} */ public static final String CVS_STATE = "$State$"; //$NON-NLS-1$ /** {@value} */ public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$ /* </section> */ public static void main(final String[] args) { Test.main(new String[] {"be.peopleware.bean_II._Test_PropertyException"}); //$NON-NLS-1$ } protected void testClassMethods() { test_PropertyException_Object_String_String_Throwable_(); } protected void testInstanceMethods() { super.testInstanceMethods(); test_getLocalizedMessageResourceBundleBasename__(); test_getLocalizedMessageKeys__(); test_hasProperties_Object_String_String_Throwable_(); test_hasProperties_Class_String_String_Throwable_(); test_hasSameValues_PropertyException_(); } /* <section name="test cases"> */ //------------------------------------------------------------------- protected final LocalizedMessageException create_LocalizedMessageException(final String message, final Throwable t) { return create_PropertyException(new Object(), "testPropertyName", //$NON-NLS-1$ message, t); } protected PropertyException create_PropertyException(final Object origin, final String propertyName, final String message, final Throwable cause) { return new PropertyException(origin, propertyName, message, cause); } protected boolean pre_PropertyException(final Object origin, final String propertyName, final String message, final Throwable cause) { return (origin != null) && ((propertyName != null) ? (!propertyName.equals("")) : true) //$NON-NLS-1$ && ((message != null) ? (!message.equals("")) : true); //$NON-NLS-1$ } public Set getCases() { Set result = new HashSet(); Iterator iterString1 = new _Test_String().getCasesWithNull().iterator(); while (iterString1.hasNext()) { String propertyName = (String)iterString1.next(); Iterator iterString2 = new _Test_String().getCasesWithNull().iterator(); while (iterString2.hasNext()) { String message = (String)iterString2.next(); Throwable cause = new Throwable(); try { Object origin = new Object(); if (pre_PropertyException(origin, propertyName, message, cause)) { result.add(create_PropertyException(origin, propertyName, message, cause)); } } catch (Throwable t) { assert true : "If create throws an exception we are not intrested."; //$NON-NLS-1$ } } } return result; } /* </section> */ /*<section name="type invariants">*/ //------------------------------------------------------------------- protected void validateTypeInvariants(final LocalizedMessageException subject) { super.validateTypeInvariants(subject); PropertyException pe = (PropertyException)subject; validate(pe.getOriginType() != null); validate((pe.getOrigin() != null) ? (pe.getOriginType() == pe.getOrigin().getClass()) : true); validate(pe.getPropertyName() == null || !pe.getPropertyName().equals("")); //$NON-NLS-1$ validate(pe.getMessage() == null || !pe.getMessage().equals("")); //$NON-NLS-1$ } /*</section>*/ /* <section name="class methods"> */ //------------------------------------------------------------------- protected final void test_PropertyException_Object_String_String_Throwable_() { Iterator iterString1 = new _Test_String().getCasesWithNull().iterator(); while (iterString1.hasNext()) { String propertyName = (String)iterString1.next(); Iterator iterString2 = new _Test_String().getCasesWithNull().iterator(); while (iterString2.hasNext()) { String message = (String)iterString2.next(); Iterator iterThrowable = new _Test_Throwable().getCasesWithNull().iterator(); while (iterThrowable.hasNext()) { Throwable cause = (Throwable)iterThrowable.next(); test_PropertyException_Object_String_String_Throwable_(new Object(), propertyName, message, cause); } } } } protected void test_PropertyException_Object_String_String_Throwable_( final Object origin, final String propertyName, final String message, final Throwable cause) { if (pre_PropertyException_Object_String_String_Throwable_(origin, propertyName, message, cause)) { try { PropertyException subject = new PropertyException(origin, propertyName, message, cause); validate(subject.getOrigin() == origin); validate((propertyName != null) ? subject.getPropertyName().equals(propertyName) : subject.getPropertyName() == null); validate((message != null) ? subject.getMessage().equals(message) : subject.getMessage() == null); validate(subject.getCause() == cause); validate(subject.getLocalizedMessageResourceBundleLoadStrategy().getClass() == DefaultResourceBundleLoadStrategy.class); validateTypeInvariants(subject); } catch (Throwable t) { unexpectedThrowable(t); } } } protected boolean pre_PropertyException_Object_String_String_Throwable_( final Object origin, final String propertyName, final String message, final Throwable cause) { return (origin != null) && ((propertyName != null) ? (!propertyName.equals("")) : true) //$NON-NLS-1$ && ((message != null) ? (!message.equals("")) : true); //$NON-NLS-1$ } /* </section> */ /* <section name="instance methods"> */ //------------------------------------------------------------------- protected final void test_getLocalizedMessageResourceBundleBasename__() { Iterator iterPE = getCases().iterator(); while (iterPE.hasNext()) { PropertyException pe = (PropertyException)iterPE.next(); test_getLocalizedMessageResourceBundleBasename__(pe); } } protected void test_getLocalizedMessageResourceBundleBasename__( final PropertyException subject) { try { String result = subject.getLocalizedMessageResourceBundleBasename(); validate(result.equals(subject.getOriginType().getName())); validateTypeInvariants(subject); } catch (Throwable t) { unexpectedThrowable(t); } } protected final void test_getLocalizedMessageKeys__() { Iterator iterPE = getCases().iterator(); while (iterPE.hasNext()) { PropertyException pe = (PropertyException)iterPE.next(); test_getLocalizedMessageResourceBundleBasename__(pe); } } protected void test_getLocalizedMessageKeys__(final PropertyException subject) { try { String[] result = subject.getLocalizedMessageKeys(); validate(result != null); validate(result.length == ((subject.getMessage() != null) ? 2 : 1)); validate(result[0] != null); validate((subject.getPropertyName() != null) && (subject.getMessage() != null) ? result[0].equals(getClass().getName() + "." + subject.getPropertyName() //$NON-NLS-1$ + "." + subject.getMessage()) //$NON-NLS-1$ : true); validate((subject.getPropertyName() == null) && (subject.getMessage() != null) ? result[0].equals(getClass().getName() + "." + subject.getMessage()) //$NON-NLS-1$ : true); validate((subject.getPropertyName() != null) && (subject.getMessage() == null) ? result[0].equals(getClass().getName() + "." + subject.getPropertyName()) //$NON-NLS-1$ : true); validate((subject.getPropertyName() == null) && (subject.getMessage() == null) ? result[0].equals(getClass().getName()) : true); validate((subject.getMessage() != null) ? (result[1] != null) && result[1].equals("message." + subject.getMessage()) //$NON-NLS-1$ : true); validateTypeInvariants(subject); } catch (Throwable t) { unexpectedThrowable(t); } } protected final void test_hasSameValues_PropertyException_() { Set cases = getCases(); Iterator iterSubject = cases.iterator(); while (iterSubject.hasNext()) { PropertyException subject = (PropertyException)iterSubject.next(); Set others = getCasesWithNull(); others.addAll(cases); Iterator iterOther = others.iterator(); while (iterOther.hasNext()) { PropertyException other = (PropertyException)iterOther.next(); test_hasSameValues_PropertyException_(subject, other); } } } protected void test_hasSameValues_PropertyException_( final PropertyException subject, final PropertyException other) { try { boolean result = subject.hasSameValues(other); validate(result == ((other != null) && subject.hasProperties(other.getOrigin(), other.getPropertyName(), other.getMessage(), other.getCause()))); validateTypeInvariants(subject); if (other != null) { validateTypeInvariants(other); } } catch (Throwable t) { unexpectedThrowable(t); } } protected final void test_hasProperties_Object_String_String_Throwable_() { Iterator iterSubject = getCases().iterator(); while (iterSubject.hasNext()) { PropertyException subject = (PropertyException)iterSubject.next(); HashSet objects = new HashSet(); objects.add(new Object()); objects.add(null); Iterator iterOrigin = objects.iterator(); while (iterOrigin.hasNext()) { Object origin = iterOrigin.next(); Iterator iterPropertyName = new _Test_String().getCasesWithNull().iterator(); while (iterPropertyName.hasNext()) { String propertyName = (String)iterPropertyName.next(); Iterator iterMessage = new _Test_String().getCasesWithNull().iterator(); while (iterMessage.hasNext()) { String message = (String)iterMessage.next(); HashSet causes = new HashSet(); causes.add(null); causes.add(new Throwable()); causes.add(subject.getCause()); Iterator iterCause = causes.iterator(); while (iterCause.hasNext()) { Throwable cause = (Throwable)iterCause.next(); test_hasProperties_Object_String_String_Throwable_(subject, origin, propertyName, message, cause); } } } } } } protected void test_hasProperties_Object_String_String_Throwable_( final PropertyException subject, final Object origin, final String propertyName, final String message, final Throwable cause) { try { boolean result = subject.hasProperties(origin, propertyName, message, cause); validate(result == ((subject.getOrigin() == origin) && ((subject.getPropertyName() == null) ? propertyName == null : subject.getPropertyName().equals(propertyName)) && ((subject.getCause() == null) ? cause == null : subject.getCause().equals(cause)) && ((subject.getMessage() == null) ? message == null : subject.getMessage().equals(message)))); validateTypeInvariants(subject); } catch (Throwable t) { unexpectedThrowable(t); } } protected final void test_hasProperties_Class_String_String_Throwable_() { Iterator iterSubject = getCases().iterator(); while (iterSubject.hasNext()) { PropertyException subject = (PropertyException)iterSubject.next(); HashSet types = new HashSet(); types.add(Object.class); types.add(PropertyException.class); types.add(null); Iterator iterOriginType = types.iterator(); while (iterOriginType.hasNext()) { Class originType = (Class)iterOriginType.next(); Iterator iterPropertyName = new _Test_String().getCasesWithNull().iterator(); while (iterPropertyName.hasNext()) { String propertyName = (String)iterPropertyName.next(); Iterator iterMessage = new _Test_String().getCasesWithNull().iterator(); while (iterMessage.hasNext()) { String message = (String)iterMessage.next(); HashSet causes = new HashSet(); causes.add(null); causes.add(new Throwable()); causes.add(subject.getCause()); Iterator iterCause = causes.iterator(); while (iterCause.hasNext()) { Throwable cause = (Throwable)iterCause.next(); test_hasProperties_Object_String_String_Throwable_(subject, originType, propertyName, message, cause); } } } } } } protected void test_hasProperties_Class_String_String_Throwable_( final PropertyException subject, final Class originType, final String propertyName, final String message, final Throwable cause) { try { boolean result = subject.hasProperties(originType, propertyName, message, cause); validate(result == ((subject.getOriginType() == originType) && ((subject.getPropertyName() == null) ? propertyName == null : subject.getPropertyName().equals(propertyName)) && ((subject.getCause() == null) ? cause == null : subject.getCause().equals(cause)) && ((subject.getMessage() == null) ? message == null : subject.getMessage().equals(message)))); validateTypeInvariants(subject); } catch (Throwable t) { unexpectedThrowable(t); } } /* </section> */ }
38.997732
92
0.532504
e579f6916bf1c912b3dc730849fdfc7948502eb6
12,686
package com.tencent.weibo.api; import org.apache.http.message.BasicNameValuePair; import com.tencent.weibo.beans.OAuth; import com.tencent.weibo.utils.QArrayList; import com.tencent.weibo.utils.QHttpClient; /** * 关系链相关API * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%85%B3%E7%B3%BB%E9%93%BE%E7%9B%B8%E5%85%B3">腾讯微博开放平台上关系链相关的API文档<a> */ public class FriendsAPI extends BasicAPI { private String friendsFansListUrl=apiBaseUrl+"/friends/fanslist"; private String friendsIdolListUrl=apiBaseUrl+"/friends/idollist"; private String friendsAddUrl=apiBaseUrl+"/friends/add"; private String friendsDelUrl=apiBaseUrl+"/friends/del"; private String friendsCheckUrl=apiBaseUrl+"/friends/check"; private String friendsUserFansListUrl=apiBaseUrl+"/friends/user_fanslist"; private String friendsUserIdolListUrl=apiBaseUrl+"/friends/user_idollist"; private String friendsUserSpecialListUrl=apiBaseUrl+"/friends/user_speciallist"; private String friendsFansListSUrl=apiBaseUrl+"/friends/fanslist_s"; /** * 使用完毕后,请调用 shutdownConnection() 关闭自动生成的连接管理器 * @param OAuthVersion 根据OAuthVersion,配置通用请求参数 */ public FriendsAPI(String OAuthVersion) { super(OAuthVersion); } /** * @param OAuthVersion 根据OAuthVersion,配置通用请求参数 * @param qHttpClient 使用已有的连接管理器 */ public FriendsAPI(String OAuthVersion, QHttpClient qHttpClient) { super(OAuthVersion, qHttpClient); } /** * 我的听众列表 * * @param oAuth 标准参数 * @param format 返回数据的格式 是(json或xml) * @param reqnum 请求个数(1-30) * @param startindex 起始位置(第一页填0,继续向下翻页:填:【reqnum*(page-1)】) * @param mode 获取模式,默认为0 * <li>mode=0,旧模式,新粉丝在前,只能拉取1000个 * <li>mode=1,新模式,拉取全量粉丝,老粉丝在前 * @param install 过滤安装应用好友(可选) <br> * 0-不考虑该参数,1-获取已安装应用好友,2-获取未安装应用好友 * @return * @throws Exception * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%B8%90%E6%88%B7%E7%9B%B8%E5%85%B3/%E6%88%91%E7%9A%84%E5%90%AC%E4%BC%97%E5%88%97%E8%A1%A8">腾讯微博开放平台上关于此条API的文档</a> */ public String fanslist(OAuth oAuth, String format, String reqnum, String startindex, String mode, String install) throws Exception { QArrayList paramsList = new QArrayList(); paramsList.add(new BasicNameValuePair("format", format)); paramsList.add(new BasicNameValuePair("reqnum", reqnum)); paramsList.add(new BasicNameValuePair("startindex", startindex)); paramsList.add(new BasicNameValuePair("mode", mode)); paramsList.add(new BasicNameValuePair("install", install)); return requestAPI.getResource(friendsFansListUrl, paramsList, oAuth); } /** * 我收听的人列表 * * @param oAuth 标准参数 * @param format 返回数据的格式 是(json或xml) * @param reqnum 请求个数(1-30) * @param startindex 起始位置(第一页填0,继续向下翻页:填:【reqnum*(page-1)】) * @param install 过滤安装应用好友(可选) <br> * 0-不考虑该参数,1-获取已安装应用好友,2-获取未安装应用好友 * @return * @throws Exception * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%B8%90%E6%88%B7%E7%9B%B8%E5%85%B3/%E6%88%91%E6%94%B6%E5%90%AC%E7%9A%84%E4%BA%BA%E5%88%97%E8%A1%A8">腾讯微博开放平台上关于此条API的文档</a> */ public String idollist(OAuth oAuth, String format, String reqnum, String startindex, String install) throws Exception { QArrayList paramsList = new QArrayList(); paramsList.add(new BasicNameValuePair("format", format)); paramsList.add(new BasicNameValuePair("reqnum", reqnum)); paramsList.add(new BasicNameValuePair("startindex", startindex)); paramsList.add(new BasicNameValuePair("install", install)); return requestAPI.getResource(friendsIdolListUrl, paramsList, oAuth); } /** * 收听某个用户<br> * * @param oAuth 标准参数 * @param format 返回数据的格式 是(json或xml) * @param name 他人的帐户名列表,用","隔开 * @param fopenids 你需要读取的用户openid列表,用下划线“_”隔开,例如:B624064BA065E01CB73F835017FE96FA_B624064BA065E01CB73F835017FE96FB(可选,最多30个) <br> * name和fopenids至少选一个,若同时存在则以name值为主 * @return * @throws Exception * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%B8%90%E6%88%B7%E7%9B%B8%E5%85%B3/%E6%94%B6%E5%90%AC%E6%9F%90%E4%B8%AA%E7%94%A8%E6%88%B7">腾讯微博开放平台上关于此条API的文档</a> */ public String add(OAuth oAuth, String format, String name,String fopenids ) throws Exception { QArrayList paramsList = new QArrayList(); paramsList.add(new BasicNameValuePair("format", format)); paramsList.add(new BasicNameValuePair("name", name)); paramsList.add(new BasicNameValuePair("fopenids", fopenids )); return requestAPI.postContent(friendsAddUrl, paramsList, oAuth); } /** * 取消收听某个用户 * * @param oAuth 标准参数 * @param format 回数据的格式 是(json或xml) * @param name 他人的帐户名 * @param fopenid 他人的openid(可选) <br> * name和fopenid至少选一个,若同时存在则以name值为主 * @return * @throws Exception * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%B8%90%E6%88%B7%E7%9B%B8%E5%85%B3/%E5%8F%96%E6%B6%88%E6%94%B6%E5%90%AC%E6%9F%90%E4%B8%AA%E7%94%A8%E6%88%B7">腾讯微博开放平台上关于此条API的文档</a> */ public String del(OAuth oAuth, String format, String name,String fopenid) throws Exception { QArrayList paramsList = new QArrayList(); paramsList.add(new BasicNameValuePair("format", format)); paramsList.add(new BasicNameValuePair("name", name)); paramsList.add(new BasicNameValuePair("fopenid", fopenid)); return requestAPI.postContent(friendsDelUrl, paramsList, oAuth); } /** * 检测是否我的听众或我收听的人 * * @param oAuth 标准参数 * @param format 返回数据的格式 是(json或xml) * @param names names 其他人的帐户名列表,用逗号“,”分隔,如aaa,bbb(最多30个,可选) * @param fopenids 其他人的的用户openid列表,用“_”隔开,例如:B624064BA065E01CB73F835017FE96FA_B624064BA065E01CB73F835017FE96FB(可选,最多30个) <br> * names和fopenids至少选一个,若同时存在则以names值为主 * @param flag 0 检测听众,1检测收听的人 2 两种关系都检测 * @return * @throws Exception * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%B8%90%E6%88%B7%E7%9B%B8%E5%85%B3/%E6%A3%80%E6%B5%8B%E6%98%AF%E5%90%A6%E6%88%91%E7%9A%84%E5%90%AC%E4%BC%97%E6%88%96%E6%94%B6%E5%90%AC%E7%9A%84%E4%BA%BA">腾讯微博开放平台上关于此条API的文档</a> */ public String check(OAuth oAuth, String format, String names,String fopenids,String flag) throws Exception { QArrayList paramsList = new QArrayList(); paramsList.add(new BasicNameValuePair("format", format)); paramsList.add(new BasicNameValuePair("names", names)); paramsList.add(new BasicNameValuePair("fopenids", fopenids)); paramsList.add(new BasicNameValuePair("flag", flag)); return requestAPI.getResource(friendsCheckUrl, paramsList, oAuth); } /** * 获取其他用户听众列表 * * @param oAuth 标准参数 * @param format 返回数据的格式 是(json或xml) * @param reqnum 请求个数(1-30) * @param startindex 起始位置(第一页填0,继续向下翻页:填【reqnum*(page-1)】) * @param name 用户帐户名 * @param fopenid 他人的openid(可选) <br> * name和fopenid至少选一个,若同时存在则以name值为主 * @param mode 获取模式,默认为0 * <li>mode=0,旧模式,新粉丝在前,只能拉取1000个 * <li>mode=1,新模式,拉取全量粉丝,老粉丝在前 * @param install 过滤安装应用好友(可选) <br> * 0-不考虑该参数,1-获取已安装应用好友,2-获取未安装应用好友 * @return * @throws Exception * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%B8%90%E6%88%B7%E7%9B%B8%E5%85%B3/%E5%85%B6%E4%BB%96%E5%B8%90%E6%88%B7%E5%90%AC%E4%BC%97%E5%88%97%E8%A1%A8">腾讯微博开放平台上关于此条API的文档</a> */ public String userFanslist(OAuth oAuth, String format, String reqnum, String startindex,String name,String fopenid,String mode,String install) throws Exception { QArrayList paramsList = new QArrayList(); paramsList.add(new BasicNameValuePair("format", format)); paramsList.add(new BasicNameValuePair("reqnum", reqnum)); paramsList.add(new BasicNameValuePair("startindex", startindex)); paramsList.add(new BasicNameValuePair("name", name)); paramsList.add(new BasicNameValuePair("fopenid", fopenid)); paramsList.add(new BasicNameValuePair("mode", mode)); paramsList.add(new BasicNameValuePair("install", install)); return requestAPI.getResource(friendsUserFansListUrl, paramsList, oAuth); } /** * 其他帐户收听的人列表 * * @param oAuth * @param format 返回数据的格式 是(json或xml) * @param reqnum 请求个数(1-30) * @param startindex 起始位置(第一页填0,继续向下翻页:填【reqnum*(page-1)】) * @param name 用户帐户名 * @param fopenid 他人的openid(可选) <br> * name和fopenid至少选一个,若同时存在则以name值为主 * @param install 过滤安装应用好友(可选) <br> * 0-不考虑该参数,1-获取已安装应用好友,2-获取未安装应用好友 * @return * @throws Exception * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%B8%90%E6%88%B7%E7%9B%B8%E5%85%B3/%E5%85%B6%E4%BB%96%E5%B8%90%E6%88%B7%E6%94%B6%E5%90%AC%E7%9A%84%E4%BA%BA%E5%88%97%E8%A1%A8">腾讯微博开放平台上关于此条API的文档</a> */ public String userIdollist(OAuth oAuth, String format, String reqnum, String startindex,String name, String fopenid,String install) throws Exception { QArrayList paramsList = new QArrayList(); paramsList.add(new BasicNameValuePair("format", format)); paramsList.add(new BasicNameValuePair("reqnum", reqnum)); paramsList.add(new BasicNameValuePair("startindex", startindex)); paramsList.add(new BasicNameValuePair("name", name)); paramsList.add(new BasicNameValuePair("fopenid", fopenid)); paramsList.add(new BasicNameValuePair("install", install)); return requestAPI.getResource(friendsUserIdolListUrl, paramsList, oAuth); } /** * 其他帐户特别收听的人列表 * * @param oAuth * @param format 返回数据的格式(json或xml) * @param reqnum 请求个数(1-30) * @param startindex 起始位置(第一页填0,继续向下翻页:填【reqnum*(page-1)】) * @param name 用户帐户名(可选) * @param fopenid 他人的openid(可选) <br> * name和fopenid至少选一个,若同时存在则以name值为主 * @param install 过滤安装应用好友(可选) <br> * 0-不考虑该参数,1-获取已安装应用好友,2-获取未安装应用好友 * @return * @throws Exception * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%B8%90%E6%88%B7%E7%9B%B8%E5%85%B3/%E5%85%B6%E4%BB%96%E5%B8%90%E6%88%B7%E7%89%B9%E5%88%AB%E6%94%B6%E5%90%AC%E7%9A%84%E4%BA%BA%E5%88%97%E8%A1%A8">腾讯微博开放平台上关于此条API的文档</a> */ public String userSpeciallist(OAuth oAuth, String format, String reqnum, String startindex,String name, String fopenid,String install) throws Exception { QArrayList paramsList = new QArrayList(); paramsList.add(new BasicNameValuePair("format", format)); paramsList.add(new BasicNameValuePair("reqnum", reqnum)); paramsList.add(new BasicNameValuePair("startindex", startindex)); paramsList.add(new BasicNameValuePair("name", name)); paramsList.add(new BasicNameValuePair("fopenid", fopenid)); paramsList.add(new BasicNameValuePair("install", install)); return requestAPI.getResource(friendsUserSpecialListUrl, paramsList, oAuth); } /** * 我的粉丝列表,简单信息(200个) * @param oAuth * @param format 返回数据的格式 是(json或xml) * @param reqnum 请求个数(1-200) * @param startindex 起始位置(第一页填0,继续向下翻页:填:【reqnum*(page-1)】) * @param install 过滤安装应用好友(可选) <br> * 0-不考虑该参数,1-获取已安装应用好友,2-获取未安装应用好友 * @return * @throws Exception * @see <a href="http://wiki.open.t.qq.com/index.php/%E5%B8%90%E6%88%B7%E7%9B%B8%E5%85%B3/%E6%88%91%E7%9A%84%E5%90%AC%E4%BC%97%E5%88%97%E8%A1%A8%EF%BC%8C%E7%AE%80%E5%8D%95%E4%BF%A1%E6%81%AF%EF%BC%88200%E4%B8%AA%EF%BC%89">腾讯微博开放平台上关于此条API的文档</a> */ public String fanslistS(OAuth oAuth, String format, String reqnum, String startindex,String install) throws Exception { QArrayList paramsList = new QArrayList(); paramsList.add(new BasicNameValuePair("format", format)); paramsList.add(new BasicNameValuePair("reqnum", reqnum)); paramsList.add(new BasicNameValuePair("startindex", startindex)); paramsList.add(new BasicNameValuePair("install", install)); return requestAPI.getResource(friendsFansListSUrl, paramsList, oAuth); } public void setAPIBaseUrl(String apiBaseUrl) { this.apiBaseUrl=apiBaseUrl; friendsFansListUrl=apiBaseUrl+"/friends/fanslist"; friendsIdolListUrl=apiBaseUrl+"/friends/idollist"; friendsAddUrl=apiBaseUrl+"/friends/add"; friendsDelUrl=apiBaseUrl+"/friends/del"; friendsCheckUrl=apiBaseUrl+"/friends/check"; friendsUserFansListUrl=apiBaseUrl+"/friends/user_fanslist"; friendsUserIdolListUrl=apiBaseUrl+"/friends/user_idollist"; friendsUserSpecialListUrl=apiBaseUrl+"/friends/user_speciallist"; friendsFansListSUrl=apiBaseUrl+"/friends/fanslist_s"; } }
43.00339
248
0.67744
81a8324319b47de6c525402308d5c6f911d05361
1,372
package ru.job4j.calculator; /** * Сlass Calculator. * * @author Evgeny Shevchenko (xxx-zet-xxx@yandex.ru) * @version 001 * @since 07.11.2018 */ public class Calculator { private double result; /** * Method add. * Adds two numbers. * @param first type double. * @param second type double. */ public void add(double first, double second) { this.result = first + second; } /** * Method subtract. * Subtracts from the first number of the second number. * @param first type double. * @param second type double. */ public void subtract(double first, double second) { this.result = first - second; } /** * Method div. * Divides the first number by the second. * @param first type double. * @param second type double. */ public void div(double first, double second) { this.result = first / second; } /** * Method multiple. * Multiplies the first number by the second. * @param first type double. * @param second type double. */ public void multiple(double first, double second) { this.result = first * second; } /** * Method gerResult. * Returns the result. * @return result type double. */ public double getResult() { return this.result; } }
22.129032
60
0.586006
14b109be2c4ca68840d9be9aae4ae73f06bdea7a
365
// This is a generated file. Not intended for manual editing. package com.nasmlanguage.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface NASMIStruc extends PsiElement { @NotNull List<NASMExpr> getExprList(); @NotNull PsiElement getIendTag(); @NotNull PsiElement getIstrucTag(); }
18.25
61
0.758904
13d19513916f245ca8d025e384b7bc8e084652f6
887
package com.loserico.junit.spring; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringLiftcycleTest { @Test public void testLifecycle() { System.out.println("Spring容器初始化"); System.out.println("====================================="); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "com/loserico/commons/junit/spring/lifecycle-context.xml"); System.out.println("Spring容器初始化完毕"); System.out.println("====================================="); System.out.println("从容器中获取Bean"); LoserService service = context.getBean("loserService", LoserService.class); System.out.println("Loser Name=" + service.getName()); System.out.println("====================================="); context.close(); System.out.println("Spring容器关闭"); } }
27.71875
79
0.630214
329dec1b6ebe607fb29488dd1cfccb58356ab842
1,635
package de.netbeacon.xeniadiscord.util; import de.netbeacon.xeniadiscord.modulemanagement.loader.CoreModuleLoader; import de.netbeacon.xeniadiscord.modulemanagement.loader.ModuleLoader; import de.netbeacon.xeniadiscord.util.extperm.ExtPermManager; import de.netbeacon.xeniadiscord.util.log.Log; import de.netbeacon.xeniadiscord.util.webhooks.twitch.TwitchHookManagement; public class ShutdownHook { public ShutdownHook(){ Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("[INFO] Shutdownhook executed"); new Log().addEntry("ShutdownHook", "Shutdownhook executed", 0); unloadmodules(); savefiles(); } }); } private void savefiles(){ System.out.println("[INFO] Saving files..."); try{ System.out.println("> ExtPerm"); new ExtPermManager().writetofile(); }catch (Exception ignore){} try{ System.out.println("> Blacklist"); new BlackListUtility().writetofile(); }catch (Exception ignore){} try{ System.out.println("> TwitchHooks"); new TwitchHookManagement(null).writetofile(); }catch (Exception ignore){} try{ System.out.println("> Log"); new Log().export(); }catch (Exception ignore){} } private void unloadmodules(){ System.out.println("[INFO] Unloading modules..."); new CoreModuleLoader(false).disable(); new ModuleLoader(false).disable(); } }
30.849057
79
0.606116
801afebbd2bc27d62a53f65984c3a80faf60538c
49,731
/******************************************************************************* * Copyright (c) 2020-2021 Matt Tropiano * This program and the accompanying materials are made available under * the terms of the MIT License, which accompanies this distribution. ******************************************************************************/ package net.mtrop.doom.tools; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.regex.Pattern; import net.mtrop.doom.Wad; import net.mtrop.doom.WadFile; import net.mtrop.doom.exception.TextureException; import net.mtrop.doom.exception.WadException; import net.mtrop.doom.object.BinaryObject; import net.mtrop.doom.texture.Animated; import net.mtrop.doom.texture.CommonTexture; import net.mtrop.doom.texture.CommonTextureList; import net.mtrop.doom.texture.DoomTextureList; import net.mtrop.doom.texture.PatchNames; import net.mtrop.doom.texture.StrifeTextureList; import net.mtrop.doom.texture.Switches; import net.mtrop.doom.texture.TextureSet; import net.mtrop.doom.texture.TextureSet.Texture; import net.mtrop.doom.tools.common.Common; import net.mtrop.doom.tools.exception.OptionParseException; import net.mtrop.doom.tools.wtexport.TextureTables; import net.mtrop.doom.util.NameUtils; import net.mtrop.doom.util.TextureUtils; /** * Main class for TexMove. * @author Matthew Tropiano */ public final class WTExportMain { private static final int ERROR_NONE = 0; private static final int ERROR_BAD_FILE = 1; private static final int ERROR_NO_FILES = 2; private static final int ERROR_BAD_OPTIONS = 4; private static final int ERROR_UNKNOWN = -1; private static final Pattern PATCH_MARKER = Pattern.compile("P[0-9]*_(START|END)"); private static final Pattern FLAT_MARKER = Pattern.compile("F[0-9]*_(START|END)"); private static final String SWITCH_HELP = "--help"; private static final String SWITCH_HELP2 = "-h"; private static final String SWITCH_VERSION = "--version"; private static final String SWITCH_BASE = "--base-wad"; private static final String SWITCH_BASE2 = "-b"; private static final String SWITCH_OUTPUT = "--output"; private static final String SWITCH_OUTPUT2 = "-o"; private static final String SWITCH_CREATE = "--create"; private static final String SWITCH_CREATE2 = "-c"; private static final String SWITCH_ADDITIVE = "--add"; private static final String SWITCH_ADDITIVE2 = "-a"; private static final String SWITCH_NULLTEX = "--null-texture"; private static final String SWITCH_NOANIMATED = "--no-animated"; private static final String SWITCH_NOSWITCH = "--no-switches"; /** * Context. */ public static class Options { private PrintStream stdout; private PrintStream stderr; private InputStream stdin; private boolean help; private boolean version; private boolean quiet; /** Path to base wad. */ private File baseWad; /** Path to output wad. */ private File outWad; /** No animated. */ private boolean noAnimated; /** No switches. */ private boolean noSwitches; /** Additive output? */ private Boolean additive; /** Null comparator. */ private NullComparator nullComparator; /** File List. */ private List<String> filePaths; /** List of texture names. */ private List<String> extractTextureList; /** List of flat names. */ private List<String> extractFlatList; private Options() { this.stdout = null; this.stderr = null; this.stdin = null; this.quiet = false; this.baseWad = null; this.outWad = null; this.noAnimated = false; this.noSwitches = false; this.additive = null; this.nullComparator = new NullComparator(null); this.filePaths = new ArrayList<>(); this.extractTextureList = new ArrayList<>(); this.extractFlatList = new ArrayList<>(); } void println(Object msg) { if (!quiet) stdout.println(msg); } void printf(String fmt, Object... args) { if (!quiet) stdout.printf(fmt, args); } void errln(Object msg) { if (!quiet) stderr.println(msg); } void errf(String fmt, Object... args) { if (!quiet) stderr.printf(fmt, args); } char readChar() throws IOException { return (char)stdin.read(); } public Options setStdout(OutputStream out) { this.stdout = new PrintStream(out, true);; return this; } public Options setStderr(OutputStream err) { this.stderr = new PrintStream(err, true); return this; } public Options setStdin(InputStream stdin) { this.stdin = stdin; return this; } public Options setBaseWad(File baseWad) { this.baseWad = baseWad; return this; } public Options setOutWad(File outWad) { this.outWad = outWad; return this; } public Options setNoAnimated(boolean noAnimated) { this.noAnimated = noAnimated; return this; } public Options setNoSwitches(boolean noSwitches) { this.noSwitches = noSwitches; return this; } public Options setAdditive(Boolean additive) { this.additive = additive; return this; } public Options setNullTexture(String texture) { this.nullComparator = new NullComparator(texture); return this; } public Options addFilePath(String path) { filePaths.add(path); return this; } public Options addTexture(String name) { extractTextureList.add(name.toUpperCase()); return this; } public Options addFlat(String name) { extractFlatList.add(name.toUpperCase()); return this; } } private static class Context implements Callable<Integer> { /** Options. */ private Options options; /** Base Unit. */ private WadUnit baseUnit; /** WAD priority queue. */ private List<WadUnit> wadPriority; /** List of texture names (need this list because order matters). */ private List<String> textureList; /** List of flat names (need this list because order matters). */ private List<String> flatList; /** Set of texture names (dupe test). */ private Set<String> textureSet; /** Set of flat names (dupe test). */ private Set<String> flatSet; private Context(Options options) { this.options = options; this.baseUnit = null; this.wadPriority = new LinkedList<WadUnit>(); this.textureSet = new HashSet<>(); this.flatSet = new HashSet<>(); this.textureList = new ArrayList<>(); this.flatList = new ArrayList<>(); } /** * Scans a WAD file, building a texture library profile of it. * @param path the path to the WAD. * @param isBase if true, does not add to the WAD priority, otherwise, it is set as the base. * @return true if the WAD was read and accounted for, false on error. */ private boolean scanWAD(File path, boolean isBase) { options.printf("Scanning %s...\n", path); WadFile wf = openWadFile(path, false); if (wf == null) return false; WadUnit unit = new WadUnit(wf); try { if (!scanTexturesAndPNames(unit, wf)) return false; } catch (IOException e) { options.printf("ERROR: \"%s\" could not be read.\n", path.getPath()); return false; } options.println(" Scanning patch entries..."); if (!scanNamespace("P", "PP", PATCH_MARKER, unit, wf, unit.patchIndices, null)) return false; if (!scanNamespace("PP", "P", null, unit, wf, unit.patchIndices, null)) return false; options.printf(" %d patches.\n", unit.patchIndices.size()); options.println(" Scanning flat entries..."); if (!scanNamespace("F", "FF", FLAT_MARKER, unit, wf, unit.flatIndices, unit.flatList)) return false; if (!scanNamespace("FF", "F", null, unit, wf, unit.flatIndices, unit.flatList)) return false; options.printf(" %d flats.\n", unit.flatIndices.size()); options.println(" Scanning texture namespace entries..."); if (!scanNamespace("TX", null, null, unit, wf, unit.texNamespaceIndices, unit.textureList)) return false; options.printf(" %d namespace textures.\n", unit.texNamespaceIndices.size()); for (TextureSet.Texture tex : unit.textureSet) if (!unit.textureList.contains(tex.getName())) unit.textureList.add(tex.getName()); try { if (!scanAnimated(unit, wf)) return false; } catch (IOException e) { options.printf("ERROR: \"%s\" could not be read: an ANIMATED or SWITCHES lump may be corrupt.\n", path.getPath()); return false; } if (!isBase) wadPriority.add(unit); else baseUnit = unit; return true; } /** * Scan for TEXTUREx and PNAMES. * @param unit the WAD unit. * @param wf the corresponding WadFile. * @return true if successful, false if not. * @throws IOException if a read error occurs. */ private boolean scanTexturesAndPNames(WadUnit unit, WadFile wf) throws IOException { options.println(" Scanning TEXTUREx/PNAMES..."); PatchNames patchNames = null; CommonTextureList<?> textureList1 = null; CommonTextureList<?> textureList2 = null; byte[] textureData = null; // Scan TEXTURE1 ===================================== try { textureData = wf.getData("TEXTURE1"); } catch (WadException e) { options.printf("ERROR: %s: %s\n", wf.getFilePath(), e.getMessage()); return false; } catch (IOException e) { options.printf("ERROR: %s: %s\n", wf.getFilePath(), e.getMessage()); return false; } if (textureData != null) { // figure out if Strife or Doom Texture Lump. if (TextureUtils.isStrifeTextureData(textureData)) { textureList1 = BinaryObject.create(StrifeTextureList.class, textureData); unit.strife = true; } else { textureList1 = BinaryObject.create(DoomTextureList.class, textureData); unit.strife = false; } unit.tex1names = new HashSet<String>(textureList1.size()); for (CommonTexture<?> ct : textureList1) unit.tex1names.add(ct.getName()); options.printf(" %d entries in TEXTURE1.\n", textureList1.size()); } else { unit.tex1names = Collections.emptySet(); } // Scan TEXTURE2 ===================================== try { textureData = wf.getData("TEXTURE2"); } catch (WadException e) { options.printf("ERROR: %s: %s\n", wf.getFilePath(), e.getMessage()); return false; } catch (IOException e) { options.printf("ERROR: %s: %s\n", wf.getFilePath(), e.getMessage()); return false; } if (textureData != null) { // figure out if Strife or Doom Texture Lump. if (TextureUtils.isStrifeTextureData(textureData)) { textureList2 = BinaryObject.create(StrifeTextureList.class, textureData); unit.strife = true; } else { textureList2 = BinaryObject.create(DoomTextureList.class, textureData); unit.strife = true; } options.printf(" %d entries in TEXTURE2.\n", textureList2.size()); unit.tex2exists = true; } try { if (!wf.contains("PNAMES")) { options.printf("ERROR: %s: TEXTUREx without PNAMES!\n", wf.getFilePath()); return false; } patchNames = wf.getDataAs("PNAMES", PatchNames.class); } catch (WadException e) { options.printf("ERROR: %s: %s\n", wf.getFilePath(), e.getMessage()); return false; } catch (IOException e) { options.printf("ERROR: %s: %s\n", wf.getFilePath(), e.getMessage()); return false; } options.printf(" %d entries in PNAMES.\n", patchNames.size()); if (textureList1 == null) textureList1 = unit.strife ? new StrifeTextureList() : new DoomTextureList(); if (textureList2 != null) unit.textureSet = new TextureSet(patchNames, textureList1, textureList2); else unit.textureSet = new TextureSet(patchNames, textureList1); return true; } /** * Scan for ANIMATED. Add combinations of textures to animated mapping. * @param unit the WAD unit. * @param wf the corresponding WadFile. * @return true if successful, false if not. * @throws IOException if a read error occurs. */ private boolean scanAnimated(WadUnit unit, WadFile wf) throws IOException { if (!options.noAnimated) { if (wf.contains("ANIMATED")) { options.println(" Scanning ANIMATED..."); unit.animated = wf.getDataAs("ANIMATED", Animated.class); processAnimated(unit, unit.animated); } processAnimated(unit, TextureTables.ALL_ANIMATED); } if (!options.noSwitches) { if (wf.contains("SWITCHES")) { options.println(" Scanning SWITCHES..."); unit.switches = wf.getDataAs("SWITCHES", Switches.class); for (Switches.Entry entry : unit.switches) { unit.switchMap.put(entry.getOffName(), entry.getOnName()); unit.switchMap.put(entry.getOnName(), entry.getOffName()); } } } return true; } private void processAnimated(WadUnit unit, Animated animated) { for (Animated.Entry entry : animated) { if (entry.isTexture()) { String[] seq = getTextureSequence(unit, entry.getFirstName(), entry.getLastName()); if (seq != null) for (String s : seq) unit.animatedTexture.put(s, seq); } else { String[] seq = getFlatSequence(unit, entry.getFirstName(), entry.getLastName()); if (seq != null) for (String s : seq) unit.animatedFlat.put(s, seq); } } } /** * Get animated texture sequence. * @param unit the WAD unit. * @param firstName the first name of the sequence. * @param lastName the last name of the sequence. * @return true if successful, false if not. */ private String[] getTextureSequence(WadUnit unit, String firstName, String lastName) { Deque<String> out = new LinkedList<>(); int index = unit.textureList.indexOf(firstName); if (index >= 0) { int index2 = unit.textureList.indexOf(lastName); if (index2 >= 0) { int min = Math.min(index, index2); int max = Math.max(index, index2); for (int i = min; i <= max; i++) out.add(unit.textureList.get(i)); } else return null; } else return null; String[] outList = new String[out.size()]; out.toArray(outList); return outList; } /** * Get animated flat sequence. * @param unit the WAD unit. * @param firstName the first name of the sequence. * @param lastName the last name of the sequence. * @return the textures between firstName and lastName. */ private String[] getFlatSequence(WadUnit unit, String firstName, String lastName) { Deque<String> out = new LinkedList<String>(); int index = unit.flatList.indexOf(firstName); if (index >= 0) { int index2 = unit.flatList.indexOf(lastName); if (index2 >= 0) { int min = Math.min(index, index2); int max = Math.max(index, index2); for (int i = min; i <= max; i++) out.add(unit.flatList.get(i)); } else return null; } else return null; String[] outList = new String[out.size()]; out.toArray(outList); return outList; } /** * Scans namespace entries. * @param name the actual namespace prefix. * @param equivName an equivalent namespace prefix. * @param ignorePattern a RegEx pattern for what entries to ignore on scan. * @param unit associated the WAD unit. * @param wf the WadFile to scan. * @param outputMap the output mapping of entry name to WAD entry index. * @param outputList the output list of entry names (no duplicates). * @return true if successful, false if a scan error occurs. */ private boolean scanNamespace(String name, String equivName, Pattern ignorePattern, WadUnit unit, WadFile wf, HashMap<String, Integer> outputMap, List<String> outputList) { // scan patch namespace int start = wf.indexOf(name+"_START"); if (start < 0) start = wf.indexOf(equivName+"_START"); if (start >= 0) { int end = wf.indexOf(name+"_END"); if (end < 0) end = wf.indexOf(equivName+"_END"); if (end >= 0) { for (int i = start + 1; i < end; i++) { String ename = wf.getEntry(i).getName(); if (ignorePattern != null && ignorePattern.matcher(ename).matches()) continue; if (!outputMap.containsKey(ename)) { outputMap.put(ename, i); if (outputList != null) outputList.add(ename); } } } else { options.printf("ERROR: %s: %s_START without %s_END!\n", unit.wad, name.toUpperCase(), name.toUpperCase()); return false; } } return true; } /** * Adds a string (usually some kind of entry) to a list and set, if it does not exist in the set. * Addition adds it to the provided set and the end of the provided list. * @param outputSet the output set. * @param outputList the output list. * @param entry the entry name. * @return true if added, false if not (name exists in the set). */ private static boolean addToLists(Set<String> outputSet, List<String> outputList, String entry) { if (!outputSet.contains(entry)) { outputSet.add(entry); outputList.add(entry); return true; } return false; } // Adds a texture to the main list (and associated ones, if possible). private void readAndAddTextures(String textureName) { if (!NameUtils.isValidTextureName(textureName)) { options.errln("ERROR: Texture \""+textureName+"\" has an invalid name. Skipping."); return; } if (!textureSet.contains(textureName)) { for (WadUnit unit : wadPriority) { // Check if animated, and if so, do NOT copy that texture over first - just copy over the animation sequence. // Copying the texture first can break animations from the middle. if (unit.animatedTexture.containsKey(textureName)) { if (!options.noAnimated) readAndAddAnimatedTextures(unit, textureName); } if (!options.noSwitches) readAndAddSwitchTextures(unit, textureName); // Break early if added. if (textureSet.contains(textureName)) break; } // attempt to add anyway - if it was already copied from the previous code, nothing happens. addToLists(textureSet, textureList, textureName); } } private void readAndAddAnimatedTextures(WadUnit unit, String textureName) { if (unit.animatedTexture.containsKey(textureName)) { for (String s : unit.animatedTexture.get(textureName)) if (addToLists(textureSet, textureList, s) && !options.noSwitches) readAndAddSwitchTextures(unit, s); } } private void readAndAddSwitchTextures(WadUnit unit, String textureName) { if (unit.switchMap.containsKey(textureName)) { if (addToLists(textureSet, textureList, textureName) && !options.noAnimated) readAndAddAnimatedTextures(unit, textureName); if (addToLists(textureSet, textureList, unit.switchMap.get(textureName)) && !options.noAnimated) readAndAddAnimatedTextures(unit, unit.switchMap.get(textureName)); } else if (TextureTables.SWITCH_TABLE.containsKey(textureName)) { if (addToLists(textureSet, textureList, textureName) && !options.noAnimated) readAndAddAnimatedTextures(unit, textureName); if (addToLists(textureSet, textureList, TextureTables.SWITCH_TABLE.get(textureName)) && !options.noAnimated) readAndAddAnimatedTextures(unit, TextureTables.SWITCH_TABLE.get(textureName)); } } private void readAndAddFlats(String textureName) { // Check if animated, and if so, do NOT copy that texture over first - just copy over the animation sequence. // Copying the texture first can break animations from the middle. if (!options.noAnimated) { for (WadUnit unit : wadPriority) { if (unit.animatedFlat.containsKey(textureName)) for (String s : unit.animatedFlat.get(textureName)) addToLists(flatSet, flatList, s); // Break early if added. if (flatSet.contains(textureName)) break; } } addToLists(flatSet, flatList, textureName); } /** * Searches for the flat to extract. * @param unitList the list to sequentially search for the desired flat. * @param flatName the flat name. * @return the unit that contains it, or null if not found. */ private WadUnit searchForFlat(List<WadUnit> unitList, String flatName) { for (WadUnit unit : unitList) { if (unit.flatIndices.containsKey(flatName)) return unit; } return null; } /** * Searches for the texture to extract. * @param unitList the list to sequentially search for the desired texture. * @param textureName the texture name. * @return the unit that contains it, or null if not found. */ private WadUnit searchForTexture(List<WadUnit> unitList, String textureName) { for (WadUnit unit : unitList) { if (unit.textureSet.contains(textureName)) return unit; } return null; } /** * Searches for the texture to extract within the "texture" namespace. * @param unitList the list to sequentially search for the desired texture. * @param textureName the texture name. * @return the unit that contains it, or null if not found. */ private WadUnit searchForNamespaceTexture(List<WadUnit> unitList, String textureName) { for (WadUnit unit : unitList) { if (unit.texNamespaceIndices.containsKey(textureName)) return unit; } return null; } /** * Extracts flats and adds them to the provided {@link ExportSet}. * @param exportSet the export set. * @return true if successful, false on read error. */ private boolean extractFlats(ExportSet exportSet) { options.println(" Extracting flats..."); for (String flat : flatList) { WadUnit unit = null; if ((unit = searchForFlat(wadPriority, flat)) != null) { // does a matching texture entry exist? if (unit.flatIndices.containsKey(flat)) { Integer pidx = unit.flatIndices.get(flat); if (pidx != null) { try { options.printf(" Extracting flat %s (%s)...\n", flat, unit.wad.getFileName()); EntryData data = new EntryData(flat, unit.wad.getData(pidx)); exportSet.flatData.add(data); exportSet.flatHash.add(flat); } catch (IOException e) { options.printf("ERROR: %s: Could not read entry %s.", unit.wad.getFilePath(), flat); return false; } } } } } return true; } /** * Extracts textures and adds them to the provided {@link ExportSet}. * @param exportSet the export set. * @return true if successful, false on read error. */ private boolean extractTextures(ExportSet exportSet) { options.println(" Extracting textures..."); for (String textureName : textureList) { WadUnit unit = null; // found texture. if ((unit = searchForTexture(wadPriority, textureName)) != null) { // for figuring out if we've found a replaced/added patch. boolean foundPatches = false; TextureSet.Texture entry = unit.textureSet.getTextureByName(textureName); for (int i = 0; i < entry.getPatchCount(); i++) { TextureSet.Patch p = entry.getPatch(i); String pname = p.getName(); // does a matching patch exist? if (unit.patchIndices.containsKey(pname)) { foundPatches = true; Integer pidx = unit.patchIndices.get(pname); if (pidx != null && !exportSet.patchHash.contains(pname)) { try { options.printf(" Extracting patch %s (%s)...\n", pname, unit.wad.getFileName()); EntryData data = new EntryData(pname, unit.wad.getData(pidx)); exportSet.patchData.add(data); exportSet.patchHash.add(pname); } catch (IOException e) { options.printf("ERROR: %s: Could not read entry %s.\n", unit.wad.getFilePath(), pname); return false; } } } } // if we've found patches or the texture is new, better extract the texture. if (foundPatches || !exportSet.textureSet.contains(textureName)) { options.printf(" Copying texture %s (%s)...\n", textureName, unit.wad.getFileName()); // check if potential overwrite. if (exportSet.textureSet.contains(textureName)) exportSet.textureSet.removeTextureByName(textureName); TextureSet.Texture newtex = exportSet.textureSet.createTexture(textureName); newtex.setHeight(entry.getHeight()); newtex.setWidth(entry.getWidth()); for (TextureSet.Patch p : entry) { TextureSet.Patch newpatch = newtex.createPatch(p.getName()); newpatch.setOriginX(p.getOriginX()); newpatch.setOriginY(p.getOriginY()); } exportSet.textureHash.add(textureName); } } // unit not found else if ((unit = searchForNamespaceTexture(wadPriority, textureName)) != null) { // does a matching texture entry exist? if (unit.texNamespaceIndices.containsKey(textureName)) { Integer pidx = unit.texNamespaceIndices.get(textureName); if (pidx != null) { try { options.printf(" Extracting namespace texture %s (%s)...\n", textureName, unit.wad.getFileName()); EntryData data = new EntryData(textureName, unit.wad.getData(pidx)); exportSet.textureData.add(data); } catch (IOException e) { options.printf("ERROR: %s: Could not read entry %s.\n", unit.wad.getFilePath(), textureName); return false; } } } } } return true; } /** * Merges ANIMATED and SWITCHES from inputs to an ExportSet, adding the entries if it finds the corresponding textures/flats. * @param exportSet the export set. * @return true if successful, false on read error. */ private boolean mergeAnimatedAndSwitches(ExportSet exportSet) { if (!options.noAnimated) { options.println(" Merging ANIMATED..."); for (WadUnit unit : wadPriority) { // did we pull any animated textures? if so, copy the entries. for (Animated.Entry entry : unit.animated) { if (entry.isTexture()) { if (exportSet.textureSet.contains(entry.getFirstName())) { exportSet.animatedData.addEntry(Animated.texture(entry.getLastName(), entry.getFirstName(), entry.getTicks(), entry.getAllowsDecals())); options.printf(" Texture %s to %s (%d tics)...\n", entry.getFirstName(), entry.getLastName(), entry.getTicks()); } } else { if (exportSet.flatHash.contains(entry.getFirstName())) { exportSet.animatedData.addEntry(Animated.flat(entry.getLastName(), entry.getFirstName(), entry.getTicks())); options.printf(" Flat %s to %s (%d tics)...\n", entry.getFirstName(), entry.getLastName(), entry.getTicks()); } else if (baseUnit.flatIndices.containsKey(entry.getFirstName())) { exportSet.animatedData.addEntry(Animated.flat(entry.getLastName(), entry.getFirstName(), entry.getTicks())); options.printf(" Flat %s to %s (%d tics)...\n", entry.getFirstName(), entry.getLastName(), entry.getTicks()); } } } } } if (!options.noSwitches) { options.println(" Merging SWITCHES..."); for (WadUnit unit : wadPriority) { // did we pull any switch textures? if so, copy the entries. for (Switches.Entry entry : unit.switches) { if (exportSet.textureSet.contains(entry.getOffName())) { exportSet.switchesData.addEntry(entry.getOffName(), entry.getOnName(), entry.getGame()); options.printf(" Switch %s / %s (%s)...\n", entry.getOffName(), entry.getOnName(), entry.getGame().name()); } else if (exportSet.textureSet.contains(entry.getOnName())) { exportSet.switchesData.addEntry(entry.getOffName(), entry.getOnName(), entry.getGame()); options.printf(" Switch %s / %s (%s)...\n", entry.getOffName(), entry.getOnName(), entry.getGame().name()); } } } } return true; } /** * Dumps the contents of the ExportSet to a WAD file. * @param exportSet the export set. * @param wf the output WAD file. * @return true. * @throws IOException if a write error occurs. */ private boolean dumpToOutputWad(ExportSet exportSet, WadFile wf) throws IOException { options.println("Sorting entries..."); exportSet.textureSet.sort(options.nullComparator); // Some data can be sorted - it's referred to by the stuff that has a specific order. Collections.sort(exportSet.patchData); options.println("Dumping entries..."); List<CommonTextureList<?>> tlist = new ArrayList<>(); PatchNames pnames; // if Strife-formatted source, export to Strife. if (baseUnit.strife) { pnames = new PatchNames(); StrifeTextureList tex1 = new StrifeTextureList(); StrifeTextureList tex2 = baseUnit.tex2exists ? new StrifeTextureList() : null; Set<String> tex1names = tex2 != null ? baseUnit.tex1names : null; exportSet.textureSet.export(pnames, tex1, tex2, tex1names); tlist.add(tex1); if (tex2 != null) tlist.add(tex2); } // if not, Doom format. else { pnames = new PatchNames(); DoomTextureList tex1 = new DoomTextureList(); DoomTextureList tex2 = baseUnit.tex2exists ? new DoomTextureList() : null; Set<String> tex1names = tex2 != null ? baseUnit.tex1names : null; exportSet.textureSet.export(pnames, tex1, tex2, tex1names); tlist.add(tex1); if (tex2 != null) tlist.add(tex2); } for (int i = 0; i < tlist.size(); i++) { String tentry = String.format("TEXTURE%01d", i+1); int idx = wf.indexOf(tentry); if (idx >= 0) wf.replaceEntry(idx, tlist.get(i).toBytes()); else wf.addData(tentry, tlist.get(i).toBytes()); } int idx = wf.indexOf("PNAMES"); if (idx >= 0) wf.replaceEntry(idx, pnames.toBytes()); else wf.addData("PNAMES", pnames.toBytes()); if (!options.noAnimated && !exportSet.animatedData.isEmpty()) { idx = wf.indexOf("ANIMATED"); if (idx >= 0) wf.replaceEntry(idx, exportSet.animatedData); else wf.addData("ANIMATED", exportSet.animatedData); } if (!options.noSwitches && exportSet.switchesData.getEntryCount() > 0) { idx = wf.indexOf("SWITCHES"); if (idx >= 0) wf.replaceEntry(idx, exportSet.switchesData); else wf.addData("SWITCHES", exportSet.switchesData); } dumpListToOutputWad(exportSet.patchData, "PP", wf); dumpListToOutputWad(exportSet.flatData, "FF", wf); dumpListToOutputWad(exportSet.textureData, "TX", wf); return true; } /** * Bulk-writes a list of entries to a WAD file. * @param entries the list of entry data to write, in order of writing. * @param namespace the WAD namespace to write (affixes START and END). * @param wf the output WAD file. * @return true. * @throws IOException if a write error occurs. */ private boolean dumpListToOutputWad(List<EntryData> entries, String namespace, WadFile wf) throws IOException { if (entries.size() == 0) return true; String[] names = new String[entries.size() + 2]; byte[][] data = new byte[entries.size() + 2][]; names[0] = namespace + "_START"; data[0] = Wad.NO_DATA; for (int i = 0; i < entries.size(); i++) { names[1 + i] = entries.get(i).key; data[1 + i] = entries.get(i).value; } names[names.length - 1] = namespace + "_END"; data[data.length - 1] = Wad.NO_DATA; try (WadFile.Adder adder = wf.createAdder()) { for (int i = 0; i < names.length; i++) adder.addData(names[i], data[i]); } return true; } /** * Extracts the necessary stuff for output. * This is the entry point for pulling and extracting. * @param options the Options object. * @return true if successful, false if an error occurs. */ private boolean extractToOutputWad(Options options) { File outFile = options.outWad; WadFile outWadFile = options.additive ? openWadFile(outFile, true) : newWadFile(outFile); if (outWadFile == null) return false; File baseFile = options.baseWad; WadFile baseWadFile = openWadFile(baseFile, false); if (baseWadFile == null) { Common.close(outWadFile); return false; } ExportSet exportSet = new ExportSet(); try { exportSet.textureSet = TextureUtils.importTextureSet(baseWadFile); extractTextures(exportSet); extractFlats(exportSet); mergeAnimatedAndSwitches(exportSet); dumpToOutputWad(exportSet, outWadFile); } catch (TextureException | IOException e) { options.printf("ERROR: %s: %s\n", baseWadFile.getFilePath(), e.getMessage()); return false; } finally { Common.close(baseWadFile); Common.close(outWadFile); } return true; } /** * Attempts to make a new WAD file. * @param f the file path. * @return the created, open WadFile. */ private WadFile newWadFile(File f) { WadFile outWad = null; try { outWad = WadFile.createWadFile(f); } catch (SecurityException e) { options.printf("ERROR: \"%s\" could not be created. Access denied.\n", f.getPath()); return null; } catch (IOException e) { options.printf("ERROR: \"%s\" could not be created.\n", f.getPath()); return null; } return outWad; } /** * Attempts to open an existing WAD file. * @param f the file path. * @param create if true, create it if it does not exist. * @return the created, open WadFile. */ private WadFile openWadFile(File f, boolean create) { WadFile outWad = null; try { if (f.exists()) outWad = new WadFile(f); else if (create) outWad = WadFile.createWadFile(f); else options.printf("ERROR: \"%s\" could not be opened.\n", f.getPath()); } catch (SecurityException e) { options.printf("ERROR: \"%s\" could not be read. Access denied.\n", f.getPath()); return null; } catch (WadException e) { options.printf("ERROR: \"%s\" is not a WAD file.\n", f.getPath()); return null; } catch (IOException e) { options.printf("ERROR: \"%s\" could not be read.\n", f.getPath()); return null; } return outWad; } /** * Reads the texture/flat list from the STDIN mapping on Options. * @throws OptionParseException if the list is misordered or malformed. * @throws IOException if a read error occurs. */ private void readList() throws OptionParseException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(options.stdin)); final String TEXTURES = ":textures"; final String FLATS = ":flats"; final String END = ":end"; final int STATE_NONE = 0; final int STATE_TEXTURES = 1; final int STATE_FLATS = 2; String line = null; int state = STATE_NONE; boolean keepGoing = true; while (keepGoing && ((line = reader.readLine()) != null)) { line = line.trim(); // skip blank lines if (line.length() == 0) continue; // skip commented lines. if (line.charAt(0) == '#') continue; if (line.equalsIgnoreCase(TEXTURES)) { state = STATE_TEXTURES; continue; } else if (line.equalsIgnoreCase(FLATS)) { state = STATE_FLATS; continue; } else if (line.equalsIgnoreCase(END)) { keepGoing = false; continue; } switch (state) { case STATE_NONE: reader.close(); throw new OptionParseException("ERROR: Name before '-textures' or '-flats'."); case STATE_TEXTURES: options.addTexture(line); break; case STATE_FLATS: options.addFlat(line); break; } } reader.close(); } @Override public Integer call() { if (options.help) { splash(options.stdout); usage(options.stdout); options.stdout.println(); help(options.stdout); return ERROR_NONE; } if (options.version) { splash(options.stdout); return ERROR_NONE; } if (options.filePaths == null || options.filePaths.isEmpty()) { options.errln("ERROR: No input WAD(s) specified."); usage(options.stdout); return ERROR_NO_FILES; } if (Common.isEmpty(options.baseWad)) { options.errln("ERROR: No base WAD specified."); usage(options.stdout); return ERROR_NO_FILES; } if (Common.isEmpty(options.outWad)) { options.errln("ERROR: No output WAD specified."); usage(options.stdout); return ERROR_NO_FILES; } if (options.additive == null) { options.errln("ERROR: Must specify --create or --add for output."); usage(options.stdout); return ERROR_NO_FILES; } if (!options.help && !options.version && !options.filePaths.isEmpty() && !Common.isEmpty(options.outWad) && options.additive != null) { // Read list from Standard In options.println("Read texture/flat list..."); try { readList(); } catch (OptionParseException e) { options.errln("ERROR: " + e.getLocalizedMessage()); return ERROR_BAD_OPTIONS; } catch (IOException e) { options.errln("ERROR: " + e.getLocalizedMessage()); return ERROR_BAD_OPTIONS; } } /* STEP 1 : Scan all incoming WADs so we know where crap is. */ // scan base. if (!scanWAD(options.baseWad, true)) return ERROR_BAD_FILE; // scan patches. for (String f : options.filePaths) if (!scanWAD(new File(f), false)) return ERROR_BAD_FILE; /* STEP 2 : Compile list of what we want. */ for (String t : options.extractTextureList) readAndAddTextures(t); for (String f : options.extractFlatList) readAndAddFlats(f); /* STEP 3 : Extract the junk and put it in the output wad. */ if (options.nullComparator.nullName != null) options.println("Using "+ options.nullComparator.nullName.toUpperCase() + " as the null texture in TEXTURE1..."); if (!extractToOutputWad(options)) return ERROR_BAD_FILE; options.println("Done!"); return ERROR_NONE; } } /** * Comparator class for Null Texture name (shuffles the null texture to the top). */ private static class NullComparator implements Comparator<Texture> { /** Null texture set. */ private static final Set<String> NULL_NAMES = new HashSet<String>() { private static final long serialVersionUID = 7124019549131283301L; { add("AASTINKY"); add("AASHITTY"); add("BADPATCH"); add("ABADONE"); } }; private String nullName; private NullComparator(String nullName) { this.nullName = nullName; } @Override public int compare(Texture o1, Texture o2) { if (nullName == null) { return NULL_NAMES.contains(o1.getName()) ? -1 : NULL_NAMES.contains(o2.getName()) ? 1 : 0; } else { return o1.getName().equalsIgnoreCase(nullName) ? -1 : o2.getName().equalsIgnoreCase(nullName) ? 1 : 0; } } } private static class ExportSet { private Set<String> patchHash; private Set<String> flatHash; private Set<String> textureHash; private TextureSet textureSet; private List<EntryData> patchData; private List<EntryData> flatData; private List<EntryData> textureData; private Animated animatedData; private Switches switchesData; public ExportSet() { this.flatHash = new HashSet<>(); this.patchHash = new HashSet<>(); this.textureHash = new HashSet<>(); this.textureSet = null; this.patchData = new ArrayList<EntryData>(); this.flatData = new ArrayList<EntryData>(); this.textureData = new ArrayList<EntryData>(); this.animatedData = new Animated(); this.switchesData = new Switches(); } } /** Pair for grouping WAD and entry index. */ private static class EntryData implements Comparable<EntryData> { private String key; private byte[] value; EntryData(String key, byte[] value) { this.key = key; this.value = value; } @Override public int compareTo(EntryData o) { return key.compareTo(o.key); } } /** * A WAD-Texture unit that is stored in a queue * for figuring out from where textures should be extracted. */ private static class WadUnit { /** WAD path. */ WadFile wad; /** Names in TEXTURE1. */ Set<String> tex1names; /** Texture Set. */ TextureSet textureSet; /** Texture 2 */ boolean tex2exists; /** Is Strife-formatted list? */ boolean strife; /** Patch ENTRY indices. */ HashMap<String, Integer> patchIndices; /** Flat ENTRY indices. */ HashMap<String, Integer> flatIndices; /** Namespace texture ENTRY indices. */ HashMap<String, Integer> texNamespaceIndices; /** Animated texture map. */ HashMap<String, String[]> animatedTexture; /** Animated texture map. */ HashMap<String, String[]> animatedFlat; /** Switches map. */ HashMap<String, String> switchMap; // NOTE: The following lists are NOT sorted for a reason. // In order to grab the correct textures between the indices of the Animated // textures, the order must be preserved ALWAYS! // In the future, there should maybe be a better type of check to speed some things // up, but I'm leaving it for now since I'm really f'in tired and it works. -MTrop /** Texture names. */ List<String> textureList; /** Flat names. */ List<String> flatList; Animated animated; Switches switches; private WadUnit(WadFile file) { this.wad = file; this.textureSet = null; this.tex1names = null; this.tex2exists = false; this.flatIndices = new HashMap<String, Integer>(); this.patchIndices = new HashMap<String, Integer>(); this.texNamespaceIndices = new HashMap<String, Integer>(); this.animatedTexture = new HashMap<String, String[]>(); this.animatedFlat = new HashMap<String, String[]>(); this.switchMap = new HashMap<String, String>(); this.textureList = new ArrayList<>(); this.flatList = new ArrayList<>(); this.animated = new Animated(); this.switches = new Switches(); } } /** * Reads command line arguments and sets options. * @param out the standard output print stream. * @param err the standard error print stream. * @param in the standard input buffered reader. * @param args the arguments. * @return the parsed options. * @throws OptionParseException if an error happens parsing the arguments. */ public static Options options(PrintStream out, PrintStream err, InputStream in, String ... args) throws OptionParseException { Options options = new Options(); options.stdout = out; options.stderr = err; options.stdin = in; final int STATE_INIT = 0; final int STATE_BASE = 1; final int STATE_OUT = 2; final int STATE_NULLTEX = 3; int state = STATE_INIT; int i = 0; while (i < args.length) { String arg = args[i]; switch (state) { case STATE_INIT: { if (arg.equals(SWITCH_HELP) || arg.equals(SWITCH_HELP2)) options.help = true; else if (arg.equals(SWITCH_VERSION)) options.version = true; else if (arg.equals(SWITCH_NOANIMATED)) options.setNoAnimated(true); else if (arg.equals(SWITCH_NOSWITCH)) options.setNoSwitches(true); else if (arg.equals(SWITCH_CREATE) || arg.equals(SWITCH_CREATE2)) options.setAdditive(false); else if (arg.equals(SWITCH_ADDITIVE) || arg.equals(SWITCH_ADDITIVE2)) options.setAdditive(true); else if (arg.equals(SWITCH_BASE) || arg.equals(SWITCH_BASE2)) state = STATE_BASE; else if (arg.equals(SWITCH_OUTPUT) || arg.equals(SWITCH_OUTPUT2)) state = STATE_OUT; else if (arg.equals(SWITCH_NULLTEX)) state = STATE_NULLTEX; else options.addFilePath(arg); } break; case STATE_BASE: { options.setBaseWad(new File(arg)); state = STATE_INIT; } break; case STATE_OUT: { options.setOutWad(new File(arg)); state = STATE_INIT; } break; case STATE_NULLTEX: { options.setNullTexture(arg); state = STATE_INIT; } break; } i++; } return options; } /** * Calls the utility using a set of options. * @param options the options to call with. * @return the error code. */ public static int call(Options options) { try { return (int)(asCallable(options).call()); } catch (Exception e) { e.printStackTrace(options.stderr); return ERROR_UNKNOWN; } } /** * Creates a {@link Callable} for this utility. * @param options the options to use. * @return a Callable that returns the process error. */ public static Callable<Integer> asCallable(Options options) { return new Context(options); } public static void main(String[] args) { if (args.length == 0) { splash(System.out); usage(System.out); System.exit(-1); return; } try { System.exit(call(options(System.out, System.err, System.in, args))); } catch (OptionParseException e) { System.err.println(e.getMessage()); System.exit(ERROR_BAD_OPTIONS); } } /** * Prints the splash. * @param out the print stream to print to. */ private static void splash(PrintStream out) { out.println("WTEXport v" + Version.WTEXPORT + " by Matt Tropiano (using DoomStruct v" + Version.DOOMSTRUCT + ")"); } /** * Prints the usage. * @param out the print stream to print to. */ private static void usage(PrintStream out) { out.println("Usage: wtexport [--help | -h | --version]"); out.println(" [files] --base-wad [base] --output [target] [--create | --add] [switches]"); } // Prints the usage message. private static void help(PrintStream out) { out.println(" --help Prints help and exits."); out.println(" -h"); out.println(); out.println(" --version Prints version, and exits."); out.println(); out.println("[files]:"); out.println(" <filenames> A valid WAD file (that contains the textures to"); out.println(" extract). Accepts wildcards for multiple WAD files."); out.println(); out.println(" --base-wad [base] The WAD file to use for reference for extraction."); out.println(" -b [base] Any texture resources found in this file are NOT"); out.println(" extracted, except for the TEXTUREx and PNAMES lumps"); out.println(" to use as a base. (Usually an IWAD)"); out.println(); out.println(" --output [wad] The output WAD file."); out.println(" -o [wad]"); out.println(); out.println(" --create If specified, the specified output WAD file is"); out.println(" -c created, TEXTUREx and PNAMES lumps are overwritten, and the"); out.println(" extracted contents are APPENDED to it. If the output"); out.println(" file already exists, it is replaced COMPLETELY"); out.println(" (be careful)!"); out.println(); out.println(" --add If specified, if the output WAD exists, the target's"); out.println(" -a TEXTUREx and PNAMES lumps are overwritten, and the"); out.println(" extracted contents are APPENDED to it. If the WAD"); out.println(" does not exist, it is created."); out.println(); out.println("[switches]:"); out.println(" --null-texture [tex] If specified, the next argument is the null"); out.println(" texture that is always sorted first."); out.println(); out.println(" --no-animated If specified, do not include other textures in"); out.println(" a texture's animation sequence, and ignore ANIMATED"); out.println(" lumps."); out.println(); out.println(" --no-switches If specified, do not include other textures in"); out.println(" a texture's switch sequence, and ignore SWITCHES"); out.println(" lumps."); out.println(); out.println("Input List"); out.println("=========="); out.println(); out.println("The input list of textures and flats are a newline-separated list read from"); out.println("STDIN, with the texture and flat list separated by \":textures\" and \":flats\""); out.println("entries, terminated by \":end\". Blank lines and lines prefixed with \"#\""); out.println("are ignored."); out.println(); out.println("Example:"); out.println(); out.println(":textures"); out.println("GRENWAL1"); out.println("GRENWAL2"); out.println("GRENWAL3"); out.println("GRENWAL4"); out.println("RAILING"); out.println("XXMETL02"); out.println("XXMETL03"); out.println(); out.println(":flats"); out.println("# This is a comment."); out.println("ICHOR01"); out.println("ICHOR02"); out.println("ICHOR03"); out.println("ICHOR04"); out.println(); out.println(":end"); out.println(); out.println("The utility WTEXSCAN already produces a list formatted this way."); } }
29.339823
172
0.642557
c86ffaa1030cb8056239d1fa0b09b883f28537af
8,526
package com.hendrix.collection; import java.io.Serializable; import java.util.AbstractSet; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Set; /** * FrequencySet is an implementation of a Set. * frequency set allows to add and remove the same object as many times. * it's frequency data will be updated, the complete removal of a member thus * only happens when it's frequency is zero. * * the implementation uses most of {@code HashSet} implementations (but not as extended * class because of some performance technical issues). * * <ul> * <li/>use {@code add(), remove(), increaseFrequencyOf()} to update frequency of element. * <li/>use {@code frequencyOf} to query frequency of element. * <li/>use {@code iterator.remove()} to update frequency of element while iteration. * * @author Tomer Shalev */ @SuppressWarnings("UnusedDeclaration") public class FrequencySet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable { private static final long serialVersionUID = -5022323554453321676L; transient HashMap<E, Integer> backingMap; /** * Constructs a new empty instance of {@link FrequencySet}. */ public FrequencySet() { this(new HashMap<E, Integer>()); } /** * Constructs a new instance of {@code HashSet} with the specified capacity. * * @param capacity * the initial capacity of this {@code HashSet}. */ public FrequencySet(int capacity) { this(new HashMap<E, Integer>(capacity)); } /** * Constructs a new instance of {@code HashSet} with the specified capacity * and load factor. * * @param capacity * the initial capacity. * @param loadFactor * the initial load factor. */ public FrequencySet(int capacity, float loadFactor) { this(new HashMap<E, Integer>(capacity, loadFactor)); } /** * Constructs a new instance of {@code HashSet} containing the unique * elements in the specified collection. * * @param collection * the collection of elements to add. */ public FrequencySet(Collection<? extends E> collection) { this(new HashMap<E, Integer>(collection.size() < 6 ? 11 : collection .size() * 2)); for (E e : collection) { add(e); } } FrequencySet(HashMap<E, Integer> backingMap) { this.backingMap = backingMap; } /** * Adds the specified object to this {@code FrequencySet}. * if the object is already a member then it's frequency data * will be updated accordingly. * * @param object * the object to add. * @return {@code true} when this {@code HashSet} did not already contain * the object, {@code false} otherwise */ @Override public boolean add(E object) { return backingMap.put(object, frequencyOf(object) + 1) == null; } /** * query the frequency that the same object appears in the {@code FrequencySet}. * * @param e the member whose frequency is of interest * * @return the member's frequency */ public Integer frequencyOf(E e) { Integer value = backingMap.get(e); return value==null ? 0 : value; } /** * Removes all elements from this {@code HashSet}, leaving it empty. * * @see #isEmpty * @see #size */ @Override public void clear() { backingMap.clear(); } /** * Returns a new {@code HashSet} with the same elements and size as this * {@code HashSet}. * * @return a shallow copy of this {@code HashSet}. * @see Cloneable */ @Override @SuppressWarnings("unchecked") public Object clone() { try { FrequencySet<E> clone = (FrequencySet<E>) super.clone(); clone.backingMap = (HashMap<E, Integer>) backingMap.clone(); return clone; } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } /** * Searches this {@code HashSet} for the specified object. * * @param object * the object to search for. * @return {@code true} if {@code object} is an element of this * {@code HashSet}, {@code false} otherwise. */ @Override public boolean contains(Object object) { return backingMap.containsKey(object); } /** * Returns true if this {@code HashSet} has no elements, false otherwise. * * @return {@code true} if this {@code HashSet} has no elements, * {@code false} otherwise. * @see #size */ @Override public boolean isEmpty() { return backingMap.isEmpty(); } /** * Returns an Iterator on the elements of this {@code FrequencySet}. * removing elements through the iterator will decrease their frequency * as expected. * * @return an Iterator on the elements of this {@code FrequencySet}. * @see java.util.Iterator */ @Override public Iterator<E> iterator() { return new FrequencyIterator(); } private class FrequencyIterator implements Iterator<E> { private Iterator<E> backingIterator; private E current; private FrequencyIterator() { backingIterator = backingMap.keySet().iterator(); } /** * Returns true if there is at least one more element, false otherwise. * * @see #next */ @Override public boolean hasNext() { return backingIterator.hasNext(); } /** * Returns the next object and advances the iterator. * * @return the next object. * @throws java.util.NoSuchElementException if there are no more elements. * @see #hasNext */ @Override public E next() { return backingIterator.next(); } /** * Removes the last object returned by {@code next} from the collection. * This method can only be called once between each call to {@code next}. * * @throws UnsupportedOperationException if removing is not supported by the collection being * iterated. * @throws IllegalStateException if {@code next} has not been called, or {@code remove} has * already been called after the last call to {@code next}. */ @Override public void remove() { int newFrequency = decreaseFrequencyOf(current); if(newFrequency==0) backingIterator.remove(); } } /** * increase the frequency of a member * * @param e the member * * @return the new member's frequency */ public int increaseFrequencyOf(E e) { int value = frequencyOf(e); int newValue = value + 1; backingMap.put(e, newValue); return newValue; } /** * decrease the frequency of a member * * @param e the member * * @return the new member's frequency */ private int decreaseFrequencyOf(E e) { int value = frequencyOf(e); int newValue = value - 1; backingMap.put(e, newValue); return newValue; } /** * decrease the frequency of this member by 1. * if it's previous frequency was 1, then the member will * be completely removed from the set. * * @param object * the object to remove. * @return {@code true} if the object was removed, {@code false} otherwise. */ @Override public boolean remove(Object object) { E key = (E)object; if(key==null) return false; int frequency = decreaseFrequencyOf(key); if(frequency >= 1){ return true; } return backingMap.remove(object) != null; } /** * Returns the number of unique elements in this {@code FrequencySet}. * * @return the number of elements in this {@code FrequencySet}. */ @Override public int size() { return backingMap.size(); } HashMap<E, FrequencySet<E>> createBackingMap(int capacity, float loadFactor) { return new HashMap<E, FrequencySet<E>>(capacity, loadFactor); } }
28.610738
107
0.58738
5b7b84983027f6ae67533be13a43618fc90641c5
11,156
package net.floodlightcontroller.iphandler; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import org.projectfloodlight.openflow.protocol.OFFlowRemoved; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFPacketIn; import org.projectfloodlight.openflow.protocol.OFPacketOut; import org.projectfloodlight.openflow.protocol.OFType; import org.projectfloodlight.openflow.protocol.OFVersion; import org.projectfloodlight.openflow.protocol.action.OFAction; import org.projectfloodlight.openflow.protocol.match.Match; import org.projectfloodlight.openflow.protocol.match.MatchField; import org.projectfloodlight.openflow.types.ArpOpcode; import org.projectfloodlight.openflow.types.EthType; import org.projectfloodlight.openflow.types.IPv4Address; import org.projectfloodlight.openflow.types.MacAddress; import org.projectfloodlight.openflow.types.OFPort; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IListener.Command; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.packet.ARP; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.IPv4; public class IPHandler implements IFloodlightModule, IOFMessageListener { protected static Logger log = LoggerFactory.getLogger(IPHandler.class); protected IFloodlightProviderService floodlightProviderService; private ConcurrentHashMap<IOFSwitch, HashMap<IPv4Address,ArrayList<NumMacPair>>> controllerDeviceTable; private ConcurrentHashMap<IOFSwitch, HashMap<IPv4Address,HashMap<MacAddress,MacAddress>>> controllerMacTable; private <T> T search(Iterator<T> itr,T obj) { T tmp; while(itr.hasNext()) { tmp = itr.next(); if(obj.equals(tmp)) { return obj; } } return null; } private <T extends Comparable<T>> T min(Iterator<T> itr) { T tmp = null; if(itr.hasNext()) tmp = itr.next(); else return null; T min = tmp; while(itr.hasNext()) { tmp = itr.next(); if(tmp.compareTo(min)<0) { min = tmp; } } return min; } @Override public String getName() { // TODO Auto-generated method stub return "IP Handler"; } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { // TODO Auto-generated method stub return false; } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { // TODO Auto-generated method stub return false; } private Command processFlowRemovedMessage(IOFSwitch sw, OFFlowRemoved msg) { return Command.CONTINUE; } private Command processPacketInMessage(IOFSwitch sw, OFPacketIn pi, FloodlightContext cntx) { HashMap<IPv4Address,ArrayList<NumMacPair>> deviceTable = controllerDeviceTable.get(sw); if(deviceTable==null) { deviceTable = new HashMap<>(); controllerDeviceTable.put(sw, deviceTable); } HashMap<IPv4Address,HashMap<MacAddress,MacAddress>> macTable = controllerMacTable.get(sw); if(macTable==null) { macTable = new HashMap<>(); controllerMacTable.put(sw, macTable); } OFPort inPort = (pi.getVersion().compareTo(OFVersion.OF_12) < 0 ? pi.getInPort() : pi.getMatch().get(MatchField.IN_PORT)); Ethernet eth = IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD); EthType type = eth.getEtherType(); if(type.equals(EthType.ARP)) { ARP arp = (ARP) eth.getPayload(); short prtType = arp.getProtocolType(); /* * If it is not an IPv4 ARP packet then we ignore it. */ if (prtType != 0x0800) { log.info("Not an IPv4 ARP"); return Command.CONTINUE; } MacAddress srcMac = arp.getSenderHardwareAddress(); MacAddress destMac = arp.getTargetHardwareAddress(); IPv4Address srcIP = arp.getSenderProtocolAddress(); IPv4Address destIP = arp.getTargetProtocolAddress(); if(arp.getOpCode().equals(ArpOpcode.REQUEST)) { ArrayList<NumMacPair> nummac = deviceTable.get(srcIP); if(nummac==null) { nummac = new ArrayList<>(); nummac.add(new NumMacPair(srcMac,0)); deviceTable.put(srcIP, nummac); }else { if(search(nummac.iterator(),new NumMacPair(srcMac,0))==null) { nummac.add(new NumMacPair(srcMac,0)); } } HashMap<MacAddress,MacAddress> macPair = macTable.get(destIP); if(macPair==null||(!macPair.containsKey(srcMac))) { nummac = deviceTable.get(destIP); if(nummac!=null&&nummac.size()!=0) { NumMacPair pair = min(nummac.iterator()); pair.increment(); nummac.remove(pair); nummac.add(pair); MacAddress arpMac = pair.getMac(); Ethernet repEth = new Ethernet(); repEth.setDestinationMACAddress(srcMac); repEth.setEtherType(EthType.ARP); repEth.setSourceMACAddress(arpMac); repEth.setVlanID(eth.getVlanID()); ARP repArp = new ARP(); repArp.setHardwareType(arp.getHardwareType()); repArp.setProtocolType(arp.getProtocolType()); repArp.setHardwareAddressLength(arp.getHardwareAddressLength()); repArp.setProtocolAddressLength(arp.getProtocolAddressLength()); repArp.setOpCode(ArpOpcode.REPLY); repArp.setSenderHardwareAddress(arpMac); repArp.setSenderProtocolAddress(destIP); repArp.setTargetHardwareAddress(srcMac); repArp.setTargetProtocolAddress(srcIP); repEth.setPayload(repArp); byte[] data = repEth.serialize(); OFPacketOut po = sw.getOFFactory().buildPacketOut().setData(data) .setActions(Collections .singletonList((OFAction) sw.getOFFactory().actions().output(inPort, 0xffFFffFF))) .setInPort(OFPort.CONTROLLER).build(); sw.write(po); boolean nullBool = false; if(macPair==null) { macPair = new HashMap<>(); nullBool = true; } macPair.put(srcMac, arpMac); if(nullBool) macTable.put(destIP, macPair); return Command.STOP; } }else { MacAddress arpMac = macPair.get(srcMac); Ethernet repEth = new Ethernet(); repEth.setDestinationMACAddress(srcMac); repEth.setEtherType(EthType.ARP); repEth.setSourceMACAddress(arpMac); repEth.setVlanID(eth.getVlanID()); ARP repArp = new ARP(); repArp.setHardwareType(arp.getHardwareType()); repArp.setProtocolType(arp.getProtocolType()); repArp.setHardwareAddressLength(arp.getHardwareAddressLength()); repArp.setProtocolAddressLength(arp.getProtocolAddressLength()); repArp.setOpCode(ArpOpcode.REPLY); repArp.setSenderHardwareAddress(arpMac); repArp.setSenderProtocolAddress(destIP); repArp.setTargetHardwareAddress(srcMac); repArp.setTargetProtocolAddress(srcIP); repEth.setPayload(repArp); byte[] data = repEth.serialize(); OFPacketOut po = sw.getOFFactory().buildPacketOut().setData(data) .setActions(Collections .singletonList((OFAction) sw.getOFFactory().actions().output(inPort, 0xffFFffFF))) .setInPort(OFPort.CONTROLLER).build(); sw.write(po); return Command.STOP; } } else if(arp.getOpCode().equals(ArpOpcode.REPLY)) { ArrayList<NumMacPair> macPair = deviceTable.get(srcIP); if(macPair==null||(search(macPair.iterator(),new NumMacPair(srcMac,0))==null)) { boolean b = false; if(macPair == null) { macPair = new ArrayList<>(); b = true; } macPair.add(new NumMacPair(srcMac,0)); if(b) { deviceTable.put(srcIP,macPair); } } macPair = deviceTable.get(destIP); if(macPair==null||search(macPair.iterator(),new NumMacPair(srcMac,0))==null) { boolean b = false; if(macPair==null) { macPair = new ArrayList<>(); b = true; } macPair.add(new NumMacPair(destMac,1)); if(b) deviceTable.put(destIP,macPair); }else { Iterator<NumMacPair> itr = macPair.iterator(); NumMacPair pair = search(itr,new NumMacPair(destMac,0)); macPair.remove(pair); pair.increment(); macPair.add(pair); } HashMap<MacAddress,MacAddress> entryTable = macTable.get(destIP); if(entryTable==null||!entryTable.containsKey(srcMac)) { boolean b = false; if(entryTable==null) { entryTable = new HashMap<>(); b = true; } entryTable.put(srcMac, destMac); if(b) { macTable.put(destIP,entryTable); } } } } return Command.CONTINUE; } @Override public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { // TODO Auto-generated method stub switch (msg.getType()) { case PACKET_IN: return this.processPacketInMessage(sw, (OFPacketIn) msg, cntx); case FLOW_REMOVED: return this.processFlowRemovedMessage(sw, (OFFlowRemoved) msg); case ERROR: log.info("received an error {} from switch {}", msg, sw); return Command.CONTINUE; default: log.error("received an unexpected message {} from switch {}", msg, sw); return Command.CONTINUE; } } @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { // TODO Auto-generated method stub return null; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { // TODO Auto-generated method stub return null; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { // TODO Auto-generated method stub Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(IFloodlightProviderService.class); return l; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { // TODO Auto-generated method stub log.info("IPHandler Learning switch Starting...."); floodlightProviderService = context.getServiceImpl(IFloodlightProviderService.class); controllerDeviceTable = new ConcurrentHashMap<>(); controllerMacTable = new ConcurrentHashMap<>(); } @Override public void startUp(FloodlightModuleContext context) throws FloodlightModuleException { // TODO Auto-generated method stub floodlightProviderService.addOFMessageListener(OFType.PACKET_IN, this); floodlightProviderService.addOFMessageListener(OFType.FLOW_REMOVED, this); floodlightProviderService.addOFMessageListener(OFType.ERROR, this); ArrayList<NumMacPair> set = new ArrayList<>(); MacAddress mac1 = MacAddress.of("00:00:00:00:00:01"); set.add(new NumMacPair(mac1,1)); if(search(set.iterator(),new NumMacPair(mac1,0))!=null) log.info("Yes, I am doing right"); else log.info("No, I am doing wrong"); } }
35.642173
110
0.726336
d539036ceb6460363bb4e31f2fbcab446e4bd21c
759
package com.github.freeacs.web; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; public class SeleniumConfig { private WebDriver driver; public SeleniumConfig(long timeout) { FirefoxBinary firefoxBinary = new FirefoxBinary(); firefoxBinary.addCommandLineOptions("--headless"); FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.setBinary(firefoxBinary); driver = new FirefoxDriver(firefoxOptions); driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS); } public WebDriver getDriver() { return driver; } }
29.192308
73
0.778656
b89830ad62c0eb03d9bf3e0f27d9bc7f3ddc0c34
6,661
package gov.samhsa.ocp.ocpfis.service.mapping.dtotofhirmodel; import gov.samhsa.ocp.ocpfis.constants.CareTeamConstants; import gov.samhsa.ocp.ocpfis.domain.ParticipantTypeEnum; import gov.samhsa.ocp.ocpfis.service.dto.CareTeamDto; import gov.samhsa.ocp.ocpfis.service.dto.ParticipantDto; import gov.samhsa.ocp.ocpfis.util.DateUtil; import gov.samhsa.ocp.ocpfis.util.FhirResourceUtil; import org.hl7.fhir.dstu3.model.CareTeam; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; import org.hl7.fhir.dstu3.model.Period; import org.hl7.fhir.dstu3.model.Reference; import org.hl7.fhir.dstu3.model.ResourceType; import org.hl7.fhir.exceptions.FHIRException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CareTeamDtoToCareTeamConverter { public static CareTeam map(CareTeamDto careTeamDto) throws FHIRException, ParseException { CareTeam careTeam = new CareTeam(); //id careTeam.setId(careTeamDto.getId()); //name careTeam.setName(careTeamDto.getName()); //status if(careTeamDto.getStatusCode() != null && !careTeamDto.getStatusCode().trim().isEmpty()){ CareTeam.CareTeamStatus careTeamStatus = CareTeam.CareTeamStatus.fromCode(careTeamDto.getStatusCode()); careTeam.setStatus(careTeamStatus); } else{ CareTeam.CareTeamStatus careTeamStatus = CareTeam.CareTeamStatus.fromCode(CareTeamConstants.STATUS_ACTIVE); careTeam.setStatus(careTeamStatus); } //categories Coding coding = new Coding(); if (FhirResourceUtil.isStringNotNullAndNotEmpty(careTeamDto.getCategoryCode())) { coding.setCode(careTeamDto.getCategoryCode()); } if (FhirResourceUtil.isStringNotNullAndNotEmpty(careTeamDto.getCategoryDisplay())) { coding.setDisplay(careTeamDto.getCategoryDisplay()); } if (FhirResourceUtil.isStringNotNullAndNotEmpty(careTeamDto.getCategorySystem())) { coding.setSystem(careTeamDto.getCategorySystem()); } CodeableConcept codeableConcept = new CodeableConcept().addCoding(coding); careTeam.addCategory(codeableConcept); //subject careTeam.getSubject().setReference("Patient/" + careTeamDto.getSubjectId()); //start and end date Period period = new Period(); period.setStart(DateUtil.convertStringToDate(careTeamDto.getStartDate())); period.setEnd(DateUtil.convertStringToDate(careTeamDto.getEndDate())); careTeam.setPeriod(period); //ReasonCode Coding codingReasonCode = new Coding(); if (FhirResourceUtil.isStringNotNullAndNotEmpty(careTeamDto.getReasonCode())) { codingReasonCode.setCode(careTeamDto.getReasonCode()); } if (FhirResourceUtil.isStringNotNullAndNotEmpty(careTeamDto.getReasonDisplay())) { codingReasonCode.setDisplay(careTeamDto.getReasonDisplay()); } if (FhirResourceUtil.isStringNotNullAndNotEmpty(careTeamDto.getReasonSystem())) { codingReasonCode.setSystem(careTeamDto.getReasonSystem()); } CodeableConcept codeableConceptReasonCode = new CodeableConcept().addCoding(codingReasonCode); careTeam.setReasonCode(Collections.singletonList(codeableConceptReasonCode)); //participants List<ParticipantDto> participantDtoList = careTeamDto.getParticipants(); List<CareTeam.CareTeamParticipantComponent> participantsList = new ArrayList<>(); for (ParticipantDto participantDto : participantDtoList) { CareTeam.CareTeamParticipantComponent careTeamParticipant = new CareTeam.CareTeamParticipantComponent(); String memberType = participantDto.getMemberType(); if (memberType.equalsIgnoreCase(ParticipantTypeEnum.practitioner.getCode())) { careTeamParticipant.getMember().setReference(ParticipantTypeEnum.practitioner.getName() + "/" + participantDto.getMemberId()); } else if (memberType.equalsIgnoreCase(ParticipantTypeEnum.patient.getCode())) { careTeamParticipant.getMember().setReference(ParticipantTypeEnum.patient.getName() + "/" + participantDto.getMemberId()); } else if (memberType.equalsIgnoreCase(ParticipantTypeEnum.organization.getCode())) { careTeamParticipant.getMember().setReference(ParticipantTypeEnum.organization.getName() + "/" + participantDto.getMemberId()); } else if (memberType.equalsIgnoreCase(ParticipantTypeEnum.relatedPerson.getCode())) { careTeamParticipant.getMember().setReference(ParticipantTypeEnum.relatedPerson.getName() + "/" + participantDto.getMemberId()); } Coding codingRoleCode = new Coding(); if (FhirResourceUtil.isStringNotNullAndNotEmpty(participantDto.getRoleCode())) { codingRoleCode.setCode(participantDto.getRoleCode()); } if (FhirResourceUtil.isStringNotNullAndNotEmpty(participantDto.getRoleDisplay())) { codingRoleCode.setDisplay(participantDto.getRoleDisplay()); } if (FhirResourceUtil.isStringNotNullAndNotEmpty(participantDto.getRoleSystem())) { codingRoleCode.setSystem(participantDto.getRoleSystem()); } CodeableConcept codeableConceptRoleCode = new CodeableConcept().addCoding(codingRoleCode); careTeamParticipant.setRole(codeableConceptRoleCode); Period participantPeriod = new Period(); participantPeriod.setStart(DateUtil.convertStringToDate(participantDto.getStartDate())); participantPeriod.setEnd(DateUtil.convertStringToDate(participantDto.getEndDate())); careTeamParticipant.setPeriod(participantPeriod); participantsList.add(careTeamParticipant); } careTeam.setParticipant(participantsList); //managingOrganization Reference reference = new Reference(); reference.setReference(ResourceType.Organization + "/" + careTeamDto.getManagingOrganization()); careTeam.setManagingOrganization(Collections.singletonList(reference)); //episodeOfCare if (careTeamDto.getEpisodeOfCareCode() != null) { Reference eocReference = new Reference(); eocReference.setReference(careTeamDto.getEpisodeOfCareCode()); eocReference.setDisplay(careTeamDto.getEpisodeOfCareType()); careTeam.setContext(eocReference); } return careTeam; } }
47.920863
143
0.711455
8dd074ce97014674f6896ba1bc7e672e288525d0
1,013
package net.engining.profile.invoker.check; import net.engining.control.core.flow.FlowContext; import net.engining.control.core.invoker.AbstractSkippableInvoker; import net.engining.control.core.invoker.InvokerDefinition; import net.engining.pg.support.core.exception.ErrorCode; import net.engining.pg.support.core.exception.ErrorMessageException; import net.engining.profile.sdk.key.OperatorIdKey; import net.engining.profile.sdk.key.UserIdKey; /** * 不能对自己进行操作 * * @author zhaoyuanmin * @version 1.0.0 * @date 2020/12/11 16:40 * @since 1.0.0 */ @InvokerDefinition( requires = { UserIdKey.class, OperatorIdKey.class } ) public class CheckOperatorIsNotSelfInvoker extends AbstractSkippableInvoker { @Override public void invoke(FlowContext flowContext) { if (flowContext.get(UserIdKey.class).equals(flowContext.get(OperatorIdKey.class))) { throw new ErrorMessageException(ErrorCode.CheckError, "不能对自己进行该操作"); } } }
28.942857
92
0.731491
3522b2c6b0af58be3e3e26190269dfc4510daca2
1,845
package io.github.vampirestudios.obsidian.api.obsidian.enchantments; import io.github.vampirestudios.obsidian.api.obsidian.NameInformation; import net.minecraft.enchantment.EnchantmentTarget; import net.minecraft.entity.EquipmentSlot; import net.minecraft.util.Identifier; public class Enchantment { public NameInformation name; public String[] slots; public Identifier[] accepted_items; public Identifier[] accepted_enchantments; public String target; public String rarity; public int minimum_level = 1; public int maximum_level = 2; public int minimum_power; public int maximum_power; public ProtectionAmount[] protection_amounts; public AttackDamage[] attack_damages; public boolean treasure = false; public boolean cursed = false; public boolean available_for_enchanted_book_offer = true; public boolean available_for_random_selection = true; public net.minecraft.enchantment.Enchantment.Rarity getRarity() { return net.minecraft.enchantment.Enchantment.Rarity.valueOf(rarity); } public int getMinimumPower(int level) { if (minimum_power != 0) { return minimum_power; } else { return 1 + level * 10; } } public int getMaximumPower(int level) { if (maximum_power != 0) { return maximum_power; } else { return this.getMinimumPower(level) + 5; } } public EnchantmentTarget getEnchantmentTarget() { return EnchantmentTarget.valueOf(target); } public EquipmentSlot[] getEquipmentSlots() { EquipmentSlot[] equipmentSlots = new EquipmentSlot[10]; for (int i = 0; i < this.slots.length; i++) { equipmentSlots[i] = EquipmentSlot.byName(this.slots[i]); } return equipmentSlots; } }
30.75
76
0.685095
0c75c2f7e77101776e756253fe76db649bde06be
1,525
package ru.loolzaaa.sso.client.core.model; import com.fasterxml.jackson.databind.JsonNode; import java.util.List; import java.util.Objects; public class User { private Long id; private String login; private JsonNode config; private String name; private boolean enabled; private List<String> authorities; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public JsonNode getConfig() { return config; } public void setConfig(JsonNode config) { this.config = config; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public List<String> getAuthorities() { return authorities; } public void setAuthorities(List<String> authorities) { this.authorities = authorities; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return getLogin().equals(user.getLogin()); } @Override public int hashCode() { return Objects.hash(getLogin()); } }
19.805195
66
0.598033
fedee5baa567bfac548ed8ca9f68eba32debf7bb
2,975
package com.buuz135.industrial.block.resourceproduction; import com.buuz135.industrial.block.IndustrialBlock; import com.buuz135.industrial.block.resourceproduction.tile.LaserDrillTile; import com.buuz135.industrial.module.ModuleResourceProduction; import com.buuz135.industrial.utils.IndustrialTags; import com.hrznstudio.titanium.api.IFactory; import com.hrznstudio.titanium.recipe.generator.TitaniumShapedRecipeBuilder; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.data.IFinishedRecipe; import net.minecraft.item.Items; import net.minecraft.particles.ParticleTypes; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.math.vector.Vector3i; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import java.util.Random; import java.util.function.Consumer; public class LaserDrillBlock extends IndustrialBlock<LaserDrillTile> { public LaserDrillBlock() { super("laser_drill", Properties.from(Blocks.IRON_BLOCK), LaserDrillTile.class, ModuleResourceProduction.TAB_RESOURCE); } @Override public IFactory<LaserDrillTile> getTileEntityFactory() { return LaserDrillTile::new; } @Override public RotationType getRotationType() { return RotationType.SIX_WAY; } @OnlyIn(Dist.CLIENT) @Override public void animateTick(BlockState stateIn, World world, BlockPos pos, Random rand) { if (world.getTileEntity(pos) instanceof LaserDrillTile){ LaserDrillTile tile = (LaserDrillTile) world.getTileEntity(pos); if (!tile.getTarget().equals(BlockPos.ZERO)){ BlockPos target = tile.getTarget(); Vector3i vector = tile.getFacingDirection().getOpposite().getDirectionVec(); Vector3d vec = new Vector3d(pos.getX(), pos.getY(), pos.getZ()); vec = vec.add(0.5, 0.5, 0.5).add(vector.getX() /2D, vector.getY()/2D, vector.getZ() / 2D); Vector3d velocity = vec.subtractReverse(new Vector3d(target.getX(), target.getY(), target.getZ()).add(0.5, 0.5, 0.5)); double vel = 10; world.addParticle(ParticleTypes.END_ROD, vec.getX(), vec.getY(), vec.getZ(), velocity.x /vel ,velocity.y/vel,velocity.z /vel); } } } @Override public void registerRecipe(Consumer<IFinishedRecipe> consumer) { TitaniumShapedRecipeBuilder.shapedRecipe(this).patternLine("pfp").patternLine("bmb").patternLine("grg") .key('p', IndustrialTags.Items.PLASTIC) .key('f', IndustrialTags.Items.GEAR_DIAMOND) .key('b', Items.PISTON) .key('m', IndustrialTags.Items.MACHINE_FRAME_SIMPLE) .key('g', IndustrialTags.Items.GEAR_GOLD) .key('r', Items.REDSTONE) .build(consumer); } }
43.115942
142
0.696807
9af01107a6fda66d1a5fdeb1be81b78ae51bfaba
2,831
package com.vcom.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.Netty4ClientHttpRequestFactory; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.client.AsyncRestTemplate; import org.springframework.web.reactive.function.client.ExchangeFilterFunction; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import reactor.netty.http.client.HttpClient; import reactor.netty.resources.ConnectionProvider; import java.time.Duration; @Configuration public class WebClientConfig { private static final Logger log = LoggerFactory.getLogger(WebClientConfig.class); @Bean @LoadBalanced public WebClient.Builder loadBalancedWebClientBuilder() { ConnectionProvider provider = ConnectionProvider.builder("order") .maxConnections(100) .maxIdleTime(Duration.ofSeconds(30)) .maxLifeTime(Duration.ofSeconds(30)) .pendingAcquireTimeout(Duration.ofMillis(100)) .pendingAcquireMaxCount(50) .build(); HttpClient httpClient = HttpClient.create(provider) .doOnError((req, err) -> { log.error("err on request:{}", req.uri(), err); }, (res, err) -> { log.error("err on response:{}", res.uri(), err); }) .responseTimeout(Duration.ofSeconds(15)) // 超时 ; return WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient)); } @Bean public WebClient webClient(WebClient.Builder builder) { return builder .filter((clientRequest, next) -> { log.info("Request: {} {}", clientRequest.method(), clientRequest.url()); clientRequest.headers() .forEach((name, values) -> values.forEach(value -> log.info("Request: {}={}", name, value))); return next.exchange(clientRequest); }) .filter(ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { log.info("Response: {}", clientResponse.headers().asHttpHeaders().get("property-header")); return Mono.just(clientResponse); })) .build(); } @Bean @LoadBalanced public AsyncRestTemplate restTemplate() { Netty4ClientHttpRequestFactory factory = new Netty4ClientHttpRequestFactory(); return new AsyncRestTemplate(factory); } }
39.873239
121
0.650653
fc6357780f5945a056efc5dc8c50f33b4f7fcd86
8,286
/* * Copyright (c) 2016. Jan Wiemer */ package org.jacis.objectadapter.microstream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.jacis.container.JacisContainer; import org.jacis.container.JacisTransactionHandle; import org.jacis.plugin.JacisTransactionListener; import org.jacis.store.JacisStore; import org.jacis.store.TrackedViewRegistry; import org.jacis.testhelper.JacisTestHelper; import org.jacis.testhelper.TestObject; import org.jacis.testhelper.TrackedTestView; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JacisStoreWithMicrostreamCloningAndTrackedViewMultithreadedTest { static final Logger log = LoggerFactory.getLogger(JacisStoreWithMicrostreamCloningAndTrackedViewMultithreadedTest.class); protected JacisStore<String, TestObject> createTestStore(JacisTestHelper testHelper) { return testHelper.createTestStoreWithMicrostreamCloning(); } @Test() public void testMultiThreadedAccess() { JacisTestHelper testHelper = new JacisTestHelper(); AtomicReference<Throwable> exception = new AtomicReference<>(); final JacisStore<String, TestObject> store = createTestStore(testHelper); final JacisContainer container = store.getContainer(); final TestJacisTransactionListenerAdapter txListener = new TestJacisTransactionListenerAdapter(store); container.registerTransactionListener(txListener); store.getTrackedViewRegistry().registerTrackedView(new TrackedTestView()); int numberOfThreads = 10; int numberOfObjects = 50; Thread[] threads = new Thread[numberOfThreads]; long deadline = System.currentTimeMillis() + 5 * 1000; for (int i = 0; i < numberOfThreads; i++) { threads[i] = new Thread("TestThread" + i) { @Override public void run() { try { int iter = 0; while (System.currentTimeMillis() < deadline && exception.get() == null) { int currIter = ++iter; container.withLocalTxAndRetry(20, () -> { long objId = testHelper.getRandBetween(1, numberOfObjects); long inc = testHelper.getRandBetween(0, 10); String objName = "Obj" + objId; TestObject object = store.get(objName); String operation = object == null ? "(new)" : "(existing)"; if (object == null) { object = new TestObject(objName, 0); } long oldVal = object.getValue(); long totalInc; if (inc == 0) { log.debug("{} iter {} remove {} {} (oldVal: {}) --> {}", getName(), currIter, operation, object, oldVal, Thread.currentThread().getName()); store.remove(objName); totalInc = -object.getValue(); } else { log.debug("{} iter {} inc {} {} by {} from {} to {} --> {}", getName(), currIter, operation, object, inc, oldVal, oldVal + inc, Thread.currentThread().getName()); object.setValue(oldVal + (int) inc); store.update(objName, object); totalInc = (int) inc; } if (inc < 5) { TrackedViewRegistry<String, TestObject> tvr = store.getTrackedViewRegistry(); log.debug("... read current view values: count={}, sum={}", tvr.getView(TrackedTestView.class).getCount(), tvr.getView(TrackedTestView.class).getSum()); } String updateTxt = object.getName() + " form " + oldVal + " to " + (oldVal + inc); txListener.trackTx(totalInc, updateTxt); }); } } catch (Throwable t) { exception.set(t); log.error("Unexpected Exception {}", t, t); } finally { log.debug("terminate {}", Thread.currentThread().getName()); } } }; } for (int i = 0; i < numberOfThreads; i++) { threads[i].start(); } try { Thread.sleep(20); } catch (InterruptedException e) { log.info("sleep interrupted {}", e, e); } for (int i = 0; i < numberOfThreads; i++) { try { threads[i].join(); log.info("Thread finished: {}", threads[i].getName()); } catch (InterruptedException e) { log.info("join interrupted for thread {}: {}", threads[i].getName(), e); } } TrackedTestView view = store.getTrackedViewRegistry().getView(TrackedTestView.class); store.streamReadOnly().forEach(v -> log.info(" core value: {}", v)); log.info("coreCount=" + store.streamReadOnly().filter(v -> v != null).count()); log.info("viewCount=" + view.getCount()); long viewSum = view.getSum(); long storeSum = store.streamReadOnly().mapToLong(v -> v == null ? 0 : v.getValue()).sum(); long expectedSum = txListener.getSum(); log.info("expectedSum = {}", expectedSum); log.info("storeSum = {}", storeSum); log.info("viewSum = {}", viewSum); testHelper.sleep(1000); log.info("expectedSumAfterAWhile = {}", txListener.getSum()); assertEquals(expectedSum, viewSum); assertTrue("more than " + numberOfObjects + ": " + view.getCount() + "!", view.getCount() <= numberOfObjects); Throwable e = exception.get(); if (e != null) { throw new RuntimeException("Exception occured in one thread: " + e, e); } } public static class TestViewValue { private final int count; private final int sum; public TestViewValue(int count, int sum) { this.count = count; this.sum = sum; } public int getCount() { return count; } public int getSum() { return sum; } } public static class TestJacisTransactionListenerAdapter implements JacisTransactionListener { private final AtomicLong sum = new AtomicLong(0l); private JacisStore<String, TestObject> store; private ThreadLocal<Long> totalInc = new ThreadLocal<>(); private ThreadLocal<String> updateTxt = new ThreadLocal<>(); public TestJacisTransactionListenerAdapter(JacisStore<String, TestObject> store) { this.store = store; } public void trackTx(long totalInc, String updateTxt) { this.totalInc.set(totalInc); this.updateTxt.set(updateTxt); } public long getSum() { return sum.get(); } @Override public void afterCommit(JacisContainer container, JacisTransactionHandle tx) { Long ti = totalInc.get(); long newVal = sum.getAndAdd(ti); log.debug("...AFTER COMMIT: incremented object {} Thread: {}", updateTxt.get(), Thread.currentThread().getName()); log.debug("...AFTER COMMIT: incremented expected sum by {} -> new Value {} Thread: {}", ti, newVal + ti, Thread.currentThread().getName()); long viewSum = store.getTrackedViewRegistry().getView(TrackedTestView.class).getSum(); long expectedSum = sum.get(); if (viewSum != expectedSum) { log.warn("!!! View sum differs! View sum = " + viewSum + " expected = " + expectedSum + " Thread: " + Thread.currentThread().getName()); log.info("!!! count=" + store.getTrackedViewRegistry().getView(TrackedTestView.class).getCount()); long storeSum = store.streamReadOnly().mapToLong(v -> v == null ? null : v.getValue()).sum(); log.info("!!! storeSum = {}", storeSum); log.info("!!! viewSum = {}", viewSum); log.info("!!! expectedSum = {} (now: {})", expectedSum, sum.get()); store.streamReadOnly().forEach(v -> log.info(" core value: {}", v)); throw new IllegalStateException("View sum differs! View sum = " + viewSum + " expected = " + expectedSum); } this.totalInc.set(0l); this.updateTxt.set("-"); } @Override public void afterRollback(JacisContainer container, JacisTransactionHandle tx) { this.totalInc.set(0l); this.updateTxt.set("-"); } } }
41.848485
181
0.60922
2a8bf72fdd11df989c416b1a2928cb5b091a10e8
1,010
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: kythe/proto/common.proto package com.google.devtools.kythe.proto; public interface SymbolInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:kythe.proto.common.SymbolInfo) com.google.protobuf.MessageOrBuilder { /** * <pre> * The base un-qualified name for a node. * </pre> * * <code>string base_name = 1;</code> */ java.lang.String getBaseName(); /** * <pre> * The base un-qualified name for a node. * </pre> * * <code>string base_name = 1;</code> */ com.google.protobuf.ByteString getBaseNameBytes(); /** * <pre> * The fully qualified name for a node. * </pre> * * <code>string qualified_name = 2;</code> */ java.lang.String getQualifiedName(); /** * <pre> * The fully qualified name for a node. * </pre> * * <code>string qualified_name = 2;</code> */ com.google.protobuf.ByteString getQualifiedNameBytes(); }
21.956522
80
0.632673
d69b796b9f2259ef443d125d133ad115e5c1a96e
1,787
package com.huffingtonpost.chronos.agent; import com.huffingtonpost.chronos.model.JobDao; import com.huffingtonpost.chronos.model.JobSpec; import com.huffingtonpost.chronos.model.PlannedJob; import com.huffingtonpost.chronos.util.CronExpression; import org.apache.log4j.Logger; import org.joda.time.DateTime; import java.io.IOException; import java.util.List; public class AgentDriver extends Stoppable { public static Logger LOG = Logger.getLogger(AgentDriver.class); private final JobDao dao; private final Thread me; private final Reporting reporting; public AgentDriver(JobDao dao, Reporting reporting) { this.dao = dao; this.reporting = reporting; me = new Thread(this); } public void init(){ me.start(); } public static boolean shouldJobRun(JobSpec aJob, DateTime now) { if (aJob.getParent() != null || aJob.isEnabled() == false) { return false; } CronExpression ce = CronExpression.createWithoutSeconds(aJob.getCronString()); DateTime next = ce.nextTimeAfter(now.minusMinutes(1)); return next.equals(now); } public void doRun() { DateTime now = Utils.getCurrentTime(); List<JobSpec> jobs = dao.getJobs(); for (JobSpec aJob : jobs) { if (shouldJobRun(aJob, now)) { LOG.info("Adding job to queue:" + aJob); dao.addToQueue(new PlannedJob(aJob, now)); } } try { LOG.info(String.format("Sleeping for %d seconds...", (SLEEP_FOR / 1000))); Thread.sleep(SLEEP_FOR); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void run() { while (isAlive) { doRun(); } } @Override public void close() throws IOException { super.close(); if (dao != null) { dao.close(); } } }
24.148649
82
0.669838
a5b30c846118261e2a49d60392b201de1d2c98a8
6,993
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.crunch.kafka.offset.hdfs; import org.apache.crunch.kafka.offset.OffsetReader; import org.apache.crunch.kafka.offset.OffsetWriter; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.kafka.common.TopicPartition; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestName; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class HDFSOffsetReaderTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public TestName testName = new TestName(); private Path basePath; private FileSystem fileSystem; private OffsetWriter writer; private OffsetReader reader; @Before public void setup() throws IOException { Configuration config = new Configuration(); config.set(FileSystem.DEFAULT_FS, tempFolder.newFolder().getAbsolutePath()); fileSystem = FileSystem.newInstance(config); basePath = new Path(tempFolder.newFolder().toString(), testName.getMethodName()); writer = new HDFSOffsetWriter(config, basePath); reader = new HDFSOffsetReader(config, basePath); } @After public void cleanup() throws IOException { writer.close(); reader.close(); fileSystem.close(); } @Test(expected = IllegalArgumentException.class) public void constructNullConfig() { new HDFSOffsetReader(null, new Path("/")); } @Test(expected = IllegalArgumentException.class) public void constructNullPath() { new HDFSOffsetReader(new Configuration(), null); } @Test public void getStoredOffsetPersistenceTimesNoValues() throws IOException { List<Long> storedOffsetPersistenceTimes = reader.getStoredOffsetPersistenceTimes(); assertThat(storedOffsetPersistenceTimes, is(Collections.<Long>emptyList())); } @Test public void getStoredOffsetPersistenceTimesMultipleValues() throws IOException { long current = 1464992662000L; List<Long> persistedTimes = new LinkedList<>(); for (int i = 0; i < 10; i++) { persistedTimes.add(current + (i * 18000)); } for (Long t : persistedTimes) { try { writer.write(t, Collections.<TopicPartition, Long>emptyMap()); } catch (IOException e) { e.printStackTrace(); } } List<Long> storedTimes = reader.getStoredOffsetPersistenceTimes(); assertThat(storedTimes, is(persistedTimes)); } @Test public void readOffsetNoMatchForTime() throws IOException { Map<TopicPartition, Long> offsets = reader.readOffsets(12345L); assertThat(offsets, is(nullValue())); } @Test public void readOffsetLatestNone() throws IOException { assertThat(reader.readLatestOffsets(), is(Collections.<TopicPartition, Long>emptyMap())); } @Test public void readOffsetLatest() throws IOException { long current = 1464992662000L; List<Long> persistedTimes = new LinkedList<>(); for (int i = 0; i < 10; i++) { persistedTimes.add(current + (i * 18000)); } for (Long t : persistedTimes) { try { writer.write(t, Collections.<TopicPartition, Long>emptyMap()); } catch (IOException e) { e.printStackTrace(); } } long expectedTime = persistedTimes.get(persistedTimes.size() - 1); Map<TopicPartition, Long> offsets = new HashMap<>(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 5; j++) { offsets.put(new TopicPartition("topic" + i, j), (long) j); } } writer.write(expectedTime, offsets); Map<TopicPartition, Long> retrievedOffsets = reader.readLatestOffsets(); assertThat(retrievedOffsets, is(offsets)); } @Test public void readOffsetForTime() throws IOException { long current = 1464992662000L; List<Long> persistedTimes = new LinkedList<>(); for (int i = 0; i < 10; i++) { persistedTimes.add(current + (i * 18000)); } for (Long t : persistedTimes) { try { writer.write(t, Collections.<TopicPartition, Long>emptyMap()); } catch (IOException e) { e.printStackTrace(); } } long expectedTime = persistedTimes.get(2); Map<TopicPartition, Long> offsets = new HashMap<>(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 5; j++) { offsets.put(new TopicPartition("topic" + i, j), (long) j); } } writer.write(expectedTime, offsets); Map<TopicPartition, Long> retrievedOffsets = reader.readOffsets(expectedTime); assertThat(retrievedOffsets, is(offsets)); } @Test public void skipReadingDirectory() throws IOException { long current = 1464992662000L; List<Long> persistedTimes = new LinkedList<>(); for (int i = 0; i < 10; i++) { persistedTimes.add(current + (i * 18000)); } for (Long t : persistedTimes) { try { writer.write(t, Collections.<TopicPartition, Long>emptyMap()); } catch (IOException e) { e.printStackTrace(); } } fileSystem.mkdirs(new Path(basePath, "imadirectory")); List<Long> storedTimes = reader.getStoredOffsetPersistenceTimes(); assertThat(storedTimes, is(persistedTimes)); } @Test public void skipInvalidFile() throws IOException { long current = 1464992662000L; List<Long> persistedTimes = new LinkedList<>(); for (int i = 0; i < 10; i++) { persistedTimes.add(current + (i * 18000)); } for (Long t : persistedTimes) { try { writer.write(t, Collections.<TopicPartition, Long>emptyMap()); } catch (IOException e) { e.printStackTrace(); } } fileSystem.createNewFile(new Path(basePath, "imabadfile.json")); fileSystem.createNewFile(new Path(basePath, "imabadfile.txt")); List<Long> storedTimes = reader.getStoredOffsetPersistenceTimes(); assertThat(storedTimes, is(persistedTimes)); } }
29.631356
93
0.68683
93c1f0536c45e01da5ec9f794633ffeb73e01d1b
5,725
/* * 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.sysds.test.functions.lineage; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.sysds.hops.OptimizerUtils; import org.apache.sysds.hops.recompile.Recompiler; import org.apache.sysds.runtime.lineage.Lineage; import org.apache.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType; import org.apache.sysds.runtime.lineage.LineageCacheStatistics; import org.apache.sysds.runtime.matrix.data.MatrixValue; import org.apache.sysds.test.TestConfiguration; import org.apache.sysds.test.TestUtils; import org.apache.sysds.utils.Statistics; import org.junit.Assert; import org.junit.Test; @net.jcip.annotations.NotThreadSafe public class CacheEvictionTest extends LineageBase { protected static final String TEST_DIR = "functions/lineage/"; protected static final String TEST_NAME1 = "CacheEviction2"; protected String TEST_CLASS_DIR = TEST_DIR + CacheEvictionTest.class.getSimpleName() + "/"; private final static String TEST_CONF = "SystemDS-config-eviction.xml"; private final static File TEST_CONF_FILE = new File(SCRIPT_DIR + TEST_DIR, TEST_CONF); @Override public void setUp() { TestUtils.clearAssertionInformation(); addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1)); } @Test public void testEvictionOrder() { runTest(TEST_NAME1); } public void runTest(String testname) { boolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION; boolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES; try { LOG.debug("------------ BEGIN " + testname + "------------"); /* This test verifies the order of evicted items w.r.t. the specified * cache policies, using a mini-batch wise autoencoder inspired * test script. An epoch-wise reusable scale and shift is part of * every batch processing. LRU fails to reuse the scale calls as * it tends to evicts scale and shift intermediates due to higher * number of post scale intermediates, where cost & size successfully * reuses all the reusable operations. * * TODO: add DagHeight. All three policies perform as expected in my * laptop, but for some reasons, LRU performs better in github actions * - that leads to failed comparison between dagheight and LRU. */ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = false; OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = false; getAndLoadTestConfiguration(testname); fullDMLScriptName = getScript(); Lineage.resetInternalState(); // LRU based eviction List<String> proArgs = new ArrayList<>(); proArgs.add("-stats"); proArgs.add("-lineage"); proArgs.add(ReuseCacheType.REUSE_FULL.name().toLowerCase()); proArgs.add("policy_lru"); proArgs.add("-args"); proArgs.add(output("R")); programArgs = proArgs.toArray(new String[proArgs.size()]); runTest(true, EXCEPTION_NOT_EXPECTED, null, -1); HashMap<MatrixValue.CellIndex, Double> R_lru = readDMLMatrixFromOutputDir("R"); long hitCount_lru = LineageCacheStatistics.getInstHits(); long colmeanCount_lru = Statistics.getCPHeavyHitterCount("uacmean"); // costnsize scheme (computationTime/Size) proArgs.clear(); proArgs.add("-stats"); proArgs.add("-lineage"); proArgs.add(ReuseCacheType.REUSE_FULL.name().toLowerCase()); proArgs.add("policy_costnsize"); proArgs.add("-args"); proArgs.add(output("R")); programArgs = proArgs.toArray(new String[proArgs.size()]); Lineage.resetInternalState(); runTest(true, EXCEPTION_NOT_EXPECTED, null, -1); HashMap<MatrixValue.CellIndex, Double> R_costnsize= readDMLMatrixFromOutputDir("R"); long hitCount_cs = LineageCacheStatistics.getInstHits(); long colmeanCount_cs = Statistics.getCPHeavyHitterCount("uacmean"); // Compare results Lineage.setLinReuseNone(); TestUtils.compareMatrices(R_lru, R_costnsize, 1e-6, "LRU", "costnsize"); // Compare cache hits Assert.assertTrue("Violated cache hit count: "+hitCount_lru+" < "+hitCount_cs, hitCount_lru < hitCount_cs); // Compare reused instruction (uacmean) counts Assert.assertTrue("Violated uacmean count: "+colmeanCount_cs+" < "+colmeanCount_lru, colmeanCount_cs < colmeanCount_lru); } finally { OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = old_simplification; OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = old_sum_product; Recompiler.reinitRecompiler(); } } /** * Override default configuration with custom test configuration to ensure * scratch space and local temporary directory locations are also updated. */ @Override protected File getConfigTemplateFile() { // Instrumentation in this test's output log to show custom configuration file used for template. System.out.println("This test case overrides default configuration with " + TEST_CONF_FILE.getPath()); return TEST_CONF_FILE; } }
39.756944
104
0.752314
9ef208f8cb513ff8a4e9f78eb9d6e47603db137b
1,054
/* * Copyright (c) Alexander <gasfull98@gmail.com> Chapchuk * Project name: TradingPlatform * * Licensed under the MIT License. See LICENSE file in the project root for license information. */ package ru.zendal.config.bundle; import ru.zendal.config.bundle.builder.InventoryConfigBundleBuilder; import java.util.List; public class InventoryConfigBundle { private List<Double> betSpread; private boolean economyEnable = false; public InventoryConfigBundle(InventoryConfigBundleBuilder bundleBuilder) { this.prepareBuilder(bundleBuilder); } private void prepareBuilder(InventoryConfigBundleBuilder bundleBuilder) { if (bundleBuilder.hasBetSpread()) { betSpread = bundleBuilder.getBetSpread(); } if (bundleBuilder.hasFlagEconomyEnable()) { economyEnable = bundleBuilder.getFlagEconomyEnable(); } } public List<Double> getBetSpread() { return this.betSpread; } public boolean isEconomyEnable() { return economyEnable; } }
25.095238
96
0.705882
e06c7d9eaa2f1a5b401a3b2ce0b2c99e733c67bf
2,663
/** * Copyright 2021 SPeCS. * * 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. under the License. */ package org.specs.Arm.instruction; import java.util.Collections; import java.util.HashMap; import java.util.Map; import pt.up.fe.specs.binarytranslation.instruction.InstructionCondition; /* * Predicates for the execution of ARM instructions which contain a "cond" field */ public enum ArmInstructionCondition implements InstructionCondition { Equal("eq", 0b0000), NotEqual("ne", 0b0001), CarrySet("cs", 0b0010), CarryClear("cc", 0b0011), MinusNegative("mn", 0b0100), PlusPositiveZero("pl", 0b0101), Overflow("vs", 0b0110), NoOverflow("vc", 0b0111), UnsignedHigher("hi", 0b1000), UnsignedLowerSame("ls", 0b1001), SignedGreaterThanorEqual("ge", 0b1010), SignedLessThan("lt", 0b1011), SignedGreaterThan("gt", 0b1100), SignedLessThanorEqual("le", 0b1101), Always1("al", 0b1110), Always2("nvb", 0b1111), NONE("NONE", 0b0000); private String shorthandle; private int condCode; private ArmInstructionCondition(String shorthandle, int condCode) { this.shorthandle = shorthandle; this.condCode = condCode; } public Boolean isConditional() { return this.equals(ArmInstructionCondition.NONE); } public int getCondCode() { return condCode; } public String getShorthandle() { return shorthandle; } /* * maps the condition code to the enum (EXCEPT "NONE"!!!) */ private static final Map<Integer, ArmInstructionCondition> DecodeCond; static { Map<Integer, ArmInstructionCondition> aMap = new HashMap<Integer, ArmInstructionCondition>(); for (ArmInstructionCondition cond : ArmInstructionCondition.values()) if (cond != ArmInstructionCondition.NONE) aMap.put(cond.getCondCode(), cond); DecodeCond = Collections.unmodifiableMap(aMap); } public static ArmInstructionCondition decodeCondition(int condcode) { return DecodeCond.get(condcode); } }
30.609195
118
0.674427
4154754b292e0199a22fdd0415efee77eec825a1
1,246
package com.mtinge.yuugure.services.database.props; import com.mtinge.yuugure.data.postgres.ReportTargetType; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import java.sql.Timestamp; @AllArgsConstructor @NoArgsConstructor @Getter @Setter @Accessors(fluent = true) public class ReportProps { /** * Whether or not this report is active (open/closed). */ private Boolean active = null; /** * The reporter's account ID. */ private Integer account = null; /** * When this report was received. */ private Timestamp timestamp = null; /** * If this report has been claimed by a staff member. */ private Boolean claimed = null; /** * The staff member's ID that claimed this report. */ private Integer claimedBy = null; /** * The dynamic target type, e.g. "upload"|"user". */ private ReportTargetType targetType = null; /** * The dynamic target ID. If the targetType is a user, then this would correspond to the reported * user's ID. */ private Integer targetId = null; /** * The user's reason for reporting, e.g. "breaks rule #3" */ private String content = null; }
23.961538
99
0.695827
b79f06de8afa037b0dab4c281ceeee2fafe987cf
1,779
package eu.datex2.schema._2._2_0; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; /** * <p>Java class for OpenlrExtendedLinear complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="OpenlrExtendedLinear"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="openlrLineLocationReference" type="{http://datex2.eu/schema/2/2_0}OpenlrLineLocationReference"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "OpenlrExtendedLinear", propOrder = { "openlrLineLocationReference" }) public class OpenlrExtendedLinear { @XmlElement(required = true) protected OpenlrLineLocationReference openlrLineLocationReference; /** * Gets the value of the openlrLineLocationReference property. * * @return * possible object is * {@link OpenlrLineLocationReference } * */ public OpenlrLineLocationReference getOpenlrLineLocationReference() { return openlrLineLocationReference; } /** * Sets the value of the openlrLineLocationReference property. * * @param value * allowed object is * {@link OpenlrLineLocationReference } * */ public void setOpenlrLineLocationReference(OpenlrLineLocationReference value) { this.openlrLineLocationReference = value; } }
28.238095
128
0.690275
f3d8e0544e27775e72c4e59fdb1f2dac7a2b2898
1,394
/********************************************************************************** * * $Header: /opt/CVS/osp/src/portfolio/org/theospi/portfolio/list/intf/CustomLinkListGenerator.java,v 1.2 2005/08/30 21:27:09 jellis Exp $ * *********************************************************************************** * * Copyright (c) 2005, 2006, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.theospi.portfolio.list.intf; public interface CustomLinkListGenerator extends ListGenerator { /** * Create a custom link for enty if it needs * to customize, otherwise, null to use the usual entry * @param entry * @return link to use or null to use normal redirect link */ public String getCustomLink(Object entry); }
39.828571
138
0.598278
29ea7aa62e7f49d445f4028f2dfda917450df503
2,699
package com.badlogic.audio.samples.part4; import java.awt.Color; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import com.badlogic.audio.io.AudioDevice; import com.badlogic.audio.io.MP3Decoder; import com.badlogic.audio.visualization.Plot; /** * A simple example on how to do real-time plotting. First all samples * from an mp3 file are read in and plotted, 1024 samples per pixel. Next * we open a new MP3Decoder and an AudioDevice and play back the music. While * doing this we also set a marker in the plot that shows us the current position * of the music playback. The marker position is calculated in pixels by * measuring the elapsed time between the start of the playback and the * current time. The elapsed time is then multiplied by the frequency divided * by the sample window size (1024 samples in this case). This gives us the * x-coordinate of the marker in the plot. After writting a sample window * to the audio device and setting the marker we sleep for 20ms to give * the Swing GUI thread time to repaint the plot with the updated marker * position. * * @author mzechner * */ public class RealTimePlot { private static final int SAMPLE_WINDOW_SIZE = 1024; private static final String FILE = "samples/sample.mp3"; public static void main( String[] argv ) throws FileNotFoundException, Exception { float[] samples = readInAllSamples( FILE ); Plot plot = new Plot( "Wave Plot", 1024, 512 ); plot.plot( samples, SAMPLE_WINDOW_SIZE, Color.red ); MP3Decoder decoder = new MP3Decoder( new FileInputStream( FILE ) ); AudioDevice device = new AudioDevice( ); samples = new float[SAMPLE_WINDOW_SIZE]; long startTime = 0; while( decoder.readSamples( samples ) > 0 ) { device.writeSamples( samples ); if( startTime == 0 ) startTime = System.nanoTime(); float elapsedTime = (System.nanoTime()-startTime)/1000000000.0f; int position = (int)(elapsedTime * (44100/SAMPLE_WINDOW_SIZE)); plot.setMarker( position, Color.white ); Thread.sleep(15); // this is needed or else swing has no chance repainting the plot! } } public static float[] readInAllSamples( String file ) throws FileNotFoundException, Exception { MP3Decoder decoder = new MP3Decoder( new FileInputStream( file ) ); ArrayList<Float> allSamples = new ArrayList<Float>( ); float[] samples = new float[1024]; while( decoder.readSamples( samples ) > 0 ) { for( int i = 0; i < samples.length; i++ ) allSamples.add( samples[i] ); } samples = new float[allSamples.size()]; for( int i = 0; i < samples.length; i++ ) samples[i] = allSamples.get(i); return samples; } }
35.051948
94
0.72286
2573de8de7303451a66e287549c67b5188e361cf
1,963
package com.beanflame.ucemod.registry; import com.beanflame.ucemod.block.tile.TileEntityCoreBlock; import com.beanflame.ucemod.render.EntityRenderFactory; //import com.douyan.ucemod.render.entity.RenderBasicMiningShip; import com.beanflame.ucemod.render.tesr.TESRCoreBlock; import net.minecraft.client.renderer.entity.Render; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.swing.text.html.parser.Entity; /** * Creative by beanflame on 2020/1/25 * 豆焰 / 青蛙 */ @SideOnly(Side.CLIENT) @Mod.EventBusSubscriber public class UCERenderLoader { public UCERenderLoader(){ } @SubscribeEvent public void bindEntityRenderer(ModelRegistryEvent event) { registerTSERRenders(); registerEntityRenders(); } private void registerTSERRenders(){ //UCERegistry.regTileRender(TileEntityCoreBlock.class,new TESRCoreBlock()); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityCoreBlock.class,new TESRCoreBlock()); //ClientRegistry.bindTileEntitySpecialRenderer(TileEntityMiningMachine.class,new TESRMiningMachine()); //ClientRegistry.bindTileEntitySpecialRenderer(EntityEngineerWorktable.class,new TESREngineerWorktable()); } public void registerEntityRenders(){ // registerEntityRender(MachineExplorer.class, RenderBasicMiningShip.class); } private static <T extends Entity> void registerEntityRender(Class<? extends net.minecraft.entity.Entity> entityClass, Class<? extends Render> render) { RenderingRegistry.registerEntityRenderingHandler(entityClass, new EntityRenderFactory(render)); } }
36.351852
153
0.78757
3cfa9b972c7fa8a167581c70d1203bffaf010d87
5,718
/* * Copyright 2017 Exorath * * 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.exorath.plugin.game.cakewars.cake; import com.exorath.exoHUD.DisplayProperties; import com.exorath.exoHUD.locations.row.HologramLocation; import com.exorath.exoHUD.removers.NeverRemover; import com.exorath.exoHUD.texts.ChatColorText; import com.exorath.exoHUD.texts.PlainText; import com.exorath.exoteams.TeamAPI; import com.exorath.plugin.base.ExoBaseAPI; import com.exorath.plugin.basegame.BaseGameAPI; import com.exorath.plugin.base.manager.ListeningManager; import com.exorath.plugin.basegame.state.State; import com.exorath.plugin.basegame.state.StateChangeEvent; import com.exorath.plugin.basegame.team.TeamManager; import com.exorath.plugin.game.cakewars.Main; import com.exorath.plugin.game.cakewars.players.CWPlayer; import com.exorath.plugin.game.cakewars.players.PlayerManager; import com.exorath.plugin.game.cakewars.team.CWTeam; import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.metadata.FixedMetadataValue; import java.util.HashMap; import java.util.Map; /** * Created by toonsev on 6/2/2017. */ public class CakeManager implements ListeningManager { private TeamAPI teamAPI; private Map<Block, CWTeam> teamByCake = new HashMap<>(); private Map<CWTeam, HologramLocation> hologramsByTeam = new HashMap<>(); public CakeManager(TeamAPI teamAPI) { this.teamAPI = teamAPI; teamAPI.getTeams().stream().map(team -> (CWTeam) team).forEach(team -> { Location cakeLocation = team.getCakeLocation(); if (cakeLocation == null) Main.terminate("No cakeLocation set for a team"); teamByCake.put(cakeLocation.getBlock(), team); }); } @EventHandler public void onStateChange(StateChangeEvent event) { if (event.getNewState() == State.STARTED) { teamByCake.forEach((block, team) -> { block.setType(Material.CAKE_BLOCK, false); block.setMetadata("cake", new FixedMetadataValue(Main.getInstance(), true)); hologramsByTeam.put(team, new HologramLocation(block.getLocation().clone().add(0.5d, 1.5d, 0.5d))); hologramsByTeam.get(team).addText(new PlainText(team.getName() + "'s"), DisplayProperties.create(0, NeverRemover.never())); hologramsByTeam.get(team).addText(ChatColorText.markup(new PlainText("Cake")).color(ChatColor.GRAY), DisplayProperties.create(-1, NeverRemover.never())); }); } } @EventHandler public void onPhysicsEvent(BlockPhysicsEvent event) { if (teamByCake.containsKey(event.getBlock())) { event.setCancelled(true); } } @EventHandler public void onInteract(PlayerInteractEvent event) { if (event.getClickedBlock() != null && event.getAction() != Action.LEFT_CLICK_BLOCK && event.getClickedBlock().hasMetadata("cake")) event.setCancelled(true); } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockBreak(BlockBreakEvent event) { teamByCake.forEach((block, team) -> { if (block.getLocation().equals(event.getBlock().getLocation())) System.out.println("Cake matches location"); }); if (teamByCake.containsKey(event.getBlock())) { System.out.println("cake has metadata"); handleCakeBreak(event); return; } //TODO MOVE THIS } private void handleCakeBreak(BlockBreakEvent event) { CWPlayer cwPlayer = ExoBaseAPI.getInstance().getManager(PlayerManager.class).getPlayer(event.getPlayer()); if (cwPlayer == null || cwPlayer.getTeam() == null) { System.out.println("Breaker does not have a team"); event.setCancelled(true); return; } CWTeam blockTeam = teamByCake.get(event.getBlock()); if (blockTeam != null && !blockTeam.equals(cwPlayer.getTeam()) && blockTeam.isCakeAlive()) { blockTeam.setCakeAlive(false); Bukkit.getPluginManager().callEvent(new CakeBreakEvent(cwPlayer, cwPlayer.getTeam(), event.getBlock())); Bukkit.broadcastMessage(ChatColor.GREEN + "Team " + blockTeam.getName() + ChatColor.GREEN + " egg has been destroyed."); blockTeam.getPlayers().forEach(teamPlayer -> TeamManager.getPlayer(teamPlayer).sendMessage(ChatColor.RED + "Your egg has been destroyed, you will no longer respawn.")); event.setCancelled(false); hologramsByTeam.get(blockTeam).addText(ChatColorText.markup(PlainText.plain("Destroyed")).color(ChatColor.RED), DisplayProperties.create(-10, NeverRemover.never())); }else event.setCancelled(true); } }
43.648855
180
0.696572
4997d5fbf4e3f068a188a44df4a68cc773553e90
1,217
package com.tutorialspoint.collections; import java.util.TreeSet; public class TreeSetDemo { public static void main(String args[]) { // Create a tree set TreeSet<String> ts = new TreeSet<String>(); // Add elements to the tree set ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); System.out.println(ts); System.out.println("first: " + ts.first()); System.out.println("last: " + ts.last()); System.out.println("isEmpty: " + ts.isEmpty()); System.out.println("size: " + ts.size()); System.out.println("pollFirst: " + ts.pollFirst()); System.out.println(ts); System.out.println("pollLast: " + ts.pollLast()); System.out.println(ts); System.out.println("subSet(\"B\",\"D\"): " + ts.subSet("B", "D")); System.out.println("subSet(\"B\", false, \"D\", true): " + ts.subSet("B", false, "D", true)); System.out.println("tailSet(\"D\"): " + ts.tailSet("D")); System.out.println("tailSet(\"D\", false): " + ts.tailSet("D", false)); System.out.println("headSet(\"D\"): " + ts.headSet("D")); System.out.println("headSet(\"D\",true): " + ts.headSet("D", true)); } }
35.794118
98
0.565325
d7be0fc99bb6fc4dba1abbdf9289e4fee57ca5ae
3,568
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * 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 <https://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.util.collection; import com.google.common.collect.AbstractIterator; import com.sk89q.worldedit.math.BlockVector3; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntIterator; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.ints.IntListIterator; import java.util.Iterator; class VectorPositionList implements PositionList { private final IntList delegateX = new IntArrayList(); private final IntList delegateY = new IntArrayList(); private final IntList delegateZ = new IntArrayList(); @Override public BlockVector3 get(int index) { return BlockVector3.at( delegateX.getInt(index), delegateY.getInt(index), delegateZ.getInt(index) ); } @Override public void add(BlockVector3 vector) { delegateX.add(vector.getX()); delegateY.add(vector.getY()); delegateZ.add(vector.getZ()); } @Override public int size() { return delegateX.size(); } @Override public void clear() { delegateX.clear(); delegateY.clear(); delegateZ.clear(); } @Override public Iterator<BlockVector3> iterator() { return new AbstractIterator<BlockVector3>() { private final IntIterator iteratorX = delegateX.iterator(); private final IntIterator iteratorY = delegateY.iterator(); private final IntIterator iteratorZ = delegateZ.iterator(); @Override protected BlockVector3 computeNext() { if (!iteratorX.hasNext()) { return endOfData(); } return BlockVector3.at( iteratorX.nextInt(), iteratorY.nextInt(), iteratorZ.nextInt() ); } }; } @Override public Iterator<BlockVector3> reverseIterator() { return new AbstractIterator<BlockVector3>() { private final IntListIterator iteratorX = delegateX.listIterator(delegateX.size()); private final IntListIterator iteratorY = delegateY.listIterator(delegateY.size()); private final IntListIterator iteratorZ = delegateZ.listIterator(delegateZ.size()); @Override protected BlockVector3 computeNext() { if (!iteratorX.hasPrevious()) { return endOfData(); } return BlockVector3.at( iteratorX.previousInt(), iteratorY.previousInt(), iteratorZ.previousInt() ); } }; } }
32.436364
95
0.621917
ec1c03ccd8abdca6551f8c6f4ef3d55480cb7a85
1,569
/** * Copyright (c) 2018 Evolveum * * 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.evolveum.midpoint.test.asserter; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import com.evolveum.midpoint.prism.PrismValue; /** * @author semancik * */ public abstract class PrismValueAsserter<V extends PrismValue, RA> extends AbstractAsserter<RA> { private V prismValue; public PrismValueAsserter(V prismValue) { super(); this.prismValue = prismValue; } public PrismValueAsserter(V prismValue, String detail) { super(detail); this.prismValue = prismValue; } public PrismValueAsserter(V prismValue, RA returnAsserter, String detail) { super(returnAsserter, detail); this.prismValue = prismValue; } public V getPrismValue() { return prismValue; } // TODO protected String desc() { return getDetails(); } }
25.721311
97
0.751434
208bbaddf9f4bd8e3d918e193234b1c6bc76633f
5,694
/* * Copyright 2017 Huawque * * 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. * * https://github.com/javandoc/AndroidMp3Record_Lame * */ package com.mp3recorder.sample.media; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.os.Handler; import android.util.AttributeSet; import android.view.View; import com.mp3recorder.sample.R; import com.mp3recorder.sample.utils.Utils; import java.util.Random; public class WaveLine extends View { private final String TAG = WaveLine.this.getClass().getSimpleName(); private int lineWidth; private Random random; private Paint mPaint; private boolean startDraw; private int mRandomNumber = 1; private RectF rectLine; private final int lineNumber = 19; private boolean isDrawing; private Thread drawLineThread; private final float MAX_DBVALUE = 140;//默认DB最大值 private float mDecibelValue; private int reverseValue = 0; private int peakValue; private boolean defaultMode = true; private int mColor; private Handler mHandler = new Handler(); public WaveLine(Context context) { super(context); initView(); } public WaveLine(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.WaveLine); mColor = typedArray.getColor(R.styleable.WaveLine_line_color, -1); typedArray.recycle(); initView(); } public WaveLine(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs); initView(); } private void initView() { mPaint = new Paint(); mPaint.setDither(true); mPaint.setColor(mColor); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL_AND_STROKE); lineWidth = Utils.dip2px(getContext(), 0.7f); mPaint.setStrokeWidth(0.7f); random = new Random(); rectLine = new RectF(); } /** * @param decibelValue 0-100 */ public void updateDecibelValue(double decibelValue) { this.mDecibelValue = (float) decibelValue; } @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); float widthPerLine = getWidth() / lineNumber; float height = getHeight(); int round = Math.round(lineNumber / 2); double heightRatio = 0; for (int i = 0; i <= (lineNumber - 1); i++) { float randomValue = 0; heightRatio = getHeightRatio(round, i); if (defaultMode) { randomValue = mRandomNumber + peakValue; mDecibelValue = 1; } else { randomValue = random.nextInt(mRandomNumber <= 0 ? 1 : mRandomNumber) + mDecibelValue + peakValue; } int drawHeight = (int) ((randomValue / 100) * height); float startX = ((widthPerLine - lineWidth) / 2) + (widthPerLine * i); float startY = (float) (height - (drawHeight * heightRatio)) / 2; float stopX = ((widthPerLine + lineWidth) / 2) + (widthPerLine * i); float stopY = (float) (height + (drawHeight * heightRatio)) / 2; rectLine.setEmpty(); rectLine.set(startX, startY, stopX, stopY); canvas.drawRect(rectLine, mPaint); } } private double getHeightRatio(int round, int i) { double heightRatio; if (i < round) { mRandomNumber = 15;//动画幅度 heightRatio = (i % 2 == 0 ? 0.3 : 0.5);//绘制高度比 peakValue = i * 12;//峰值 } else if (i == round) { mRandomNumber = 27; peakValue = 45; heightRatio = 0.8; } else { mRandomNumber = 15; if (reverseValue == (lineNumber - 1)) {//反向 reverseValue = 0; } reverseValue += 2; heightRatio = ((i - reverseValue) % 2 == 0 ? 0.3 : 0.5); peakValue = (i - reverseValue) * 12; } return heightRatio; } public void stopDrawWave() { defaultMode = true; isDrawing = false; } public void drawWaveLine() { defaultMode = false; isDrawing = true; drawLineThread = new Thread(new Runnable() { @Override public void run() { while (isDrawing) { try { //根据DB值动态调整给制速度 int speedRatio = (int) (mDecibelValue / MAX_DBVALUE * 100); Thread.sleep(180 - (int) (1.5 * speedRatio)); } catch (InterruptedException e) { e.printStackTrace(); } postInvalidate(); } mRandomNumber = 1; postInvalidate(); } }); mHandler.postDelayed(new Runnable() { @Override public void run() { drawLineThread.start(); } }, 350); } }
31.285714
113
0.584299
a4c812f4f9a69a645579bd1b19ca80c577e94d7e
558
package tv.dyndns.kishibe.qmaclone.client.game.accuracyrate; import tv.dyndns.kishibe.qmaclone.client.packet.PacketProblemMinimum; public class AccuracyRateNormalizerMarubatsu implements AccuracyRateNormalizable { @Override public double normalize(PacketProblemMinimum problem) { int good = problem.good; int bad = problem.bad; if (good == 0 && bad == 0) { return -1; } double rate = good / (double) (good + bad); // 50% -> 0% rate -= 0.5; rate *= 2.0; rate = Math.max(0.0, rate); rate = Math.min(1.0, rate); return rate; } }
23.25
82
0.68638
b5ab5c1ab732e32acbdda7ee0059bd2a5d7d2905
4,473
package de.metas.ui.web.window.descriptor.factory; import de.metas.bpartner.BPartnerId; import de.metas.bpartner.quick_input.service.BPartnerQuickInputService; import de.metas.logging.LogManager; import de.metas.ui.web.window.datatypes.WindowId; import de.metas.ui.web.window.descriptor.DocumentEntityDescriptor; import de.metas.ui.web.window.descriptor.NewRecordDescriptor; import lombok.NonNull; import org.adempiere.ad.element.api.AdWindowId; import org.adempiere.exceptions.AdempiereException; import org.adempiere.model.InterfaceWrapperHelper; import org.compiere.model.I_C_BPartner; import org.compiere.model.I_C_BPartner_QuickInput; import org.slf4j.Logger; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import java.util.concurrent.ConcurrentHashMap; /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2017 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ /** * Provides {@link NewRecordDescriptor}s. * <p> * Task https://github.com/metasfresh/metasfresh/issues/1090 */ @Component public class NewRecordDescriptorsProvider { // services private static final Logger logger = LogManager.getLogger(NewRecordDescriptorsProvider.class); private final DocumentDescriptorFactory documentDescriptors; private final ConcurrentHashMap<String, NewRecordDescriptor> newRecordDescriptorsByTableName = new ConcurrentHashMap<>(); NewRecordDescriptorsProvider( @NonNull final DocumentDescriptorFactory documentDescriptors, @NonNull final BPartnerQuickInputService bpartnerQuickInputService) { this.documentDescriptors = documentDescriptors; final AdWindowId bpartnerQuickInputAdWindowId = bpartnerQuickInputService.getNewBPartnerWindowId().orElse(null); if (bpartnerQuickInputAdWindowId != null) { addNewRecordDescriptor(NewRecordDescriptor.of( I_C_BPartner.Table_Name, WindowId.of(bpartnerQuickInputAdWindowId), document -> { final I_C_BPartner_QuickInput template = InterfaceWrapperHelper.getPO(document); final BPartnerId bpartnerId = bpartnerQuickInputService.createBPartnerFromTemplate(template); return bpartnerId.getRepoId(); })); } else { logger.warn("No window found for " + I_C_BPartner_QuickInput.Table_Name); } } public void addNewRecordDescriptor(@NonNull final NewRecordDescriptor newRecordDescriptor) { newRecordDescriptorsByTableName.put(newRecordDescriptor.getTableName(), newRecordDescriptor); logger.info("Registered {}", newRecordDescriptor); } public NewRecordDescriptor getNewRecordDescriptorOrNull(@NonNull final String tableName) { return newRecordDescriptorsByTableName.get(tableName); } /** * @param entityDescriptor the entity descriptor of the quick input window (e.g. for BPartner that is C_BPartner_QuickInput) * @return new record descriptor */ public NewRecordDescriptor getNewRecordDescriptor(final DocumentEntityDescriptor entityDescriptor) { final WindowId newRecordWindowId = entityDescriptor.getWindowId(); return newRecordDescriptorsByTableName.values() .stream() .filter(descriptor -> WindowId.equals(newRecordWindowId, descriptor.getNewRecordWindowId())) .findFirst() .orElseThrow(() -> new AdempiereException("No new record quick input defined windowId=" + newRecordWindowId)); } @Nullable public DocumentEntityDescriptor getNewRecordEntityDescriptorIfAvailable(@NonNull final String tableName) { final NewRecordDescriptor newRecordDescriptor = getNewRecordDescriptorOrNull(tableName); if (newRecordDescriptor == null) { return null; } try { return documentDescriptors.getDocumentEntityDescriptor(newRecordDescriptor.getNewRecordWindowId()); } catch (final Exception ex) { logger.warn("Failed fetching document entity descriptor for {}. Ignored", newRecordDescriptor, ex); return null; } } }
35.220472
125
0.788509
c892e1dd6d4dfbe22383dd7012c3a23a0e80a516
1,250
package com.snapscreenapp.supervisor.impl; import com.snapscreenapp.supervisor.MonitoringService; import com.snapscreenapp.supervisor.PersistenceService; import com.snapscreenapp.supervisor.ViewerService; import com.snapscreenapp.supervisor.model.Account; import com.snapscreenapp.supervisor.model.DeviceConnection; import com.snapscreenapp.supervisor.model.User; import com.snapscreenapp.supervisor.model.ViewerConnection; // TODO: Spring REST Service? public class MonitoringServiceImpl implements MonitoringService { private PersistenceService persistenceService; private ViewerService viewerService; public MonitoringServiceImpl(PersistenceService persistenceService, ViewerService viewerService) { this.persistenceService = persistenceService; this.viewerService = viewerService; } @Override public void submit(DeviceConnection device, Activity activity) { User user = persistenceService.retrieveUserBy(device); if (user == null) return; Account account = user.getAccount(); ViewerConnection viewerConnection = user.getViewerConnection(); if (viewerConnection == null || account == null || !account.isCurrent()) return; viewerService.submit(viewerConnection, activity); } }
34.722222
100
0.7936
cf2476f9cb6d42039b5b3a751fffcc1a9188a8ff
2,104
/* * Copyright 2014 Semyon Proshev * * 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.tcity.android.ui.login; import com.tcity.android.background.runnable.chain.RunnableChain; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; class LoginChainListener implements RunnableChain.Listener { @Nullable private LoginActivity myActivity; @NotNull private LoginResult myLoginResult = LoginResult.PENDING; @Nullable private Exception myException; void onStarted() { myLoginResult = LoginResult.RUNNING; resetException(); if (myActivity != null) { myActivity.onRunningLogin(); } } @Override public void onFinished() { if (myLoginResult != LoginResult.FAILED) { myLoginResult = LoginResult.SUCCESS; if (myActivity != null) { myActivity.onSuccessfulLogin(); } } } @Override public void onException(@NotNull Exception e) { myLoginResult = LoginResult.FAILED; myException = e; if (myActivity != null) { myActivity.onFailedLogin(); } } @NotNull LoginResult getResult() { return myLoginResult; } @Nullable Exception getException() { return myException; } void resetException() { myException = null; } void setActivity(@Nullable LoginActivity activity) { myActivity = activity; } static enum LoginResult { PENDING, RUNNING, SUCCESS, FAILED } }
24.183908
75
0.654943
30076b746937865f35b1e05f30712169713438b1
657
package edu.ml.hw1.lei; public class Counter { private String name; private int count; private String code; public static Counter getMax(Counter a, Counter b) { return a.getCount() > b.getCount() ? a : b; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Counter(String name, int count, String code) { this.name = name; this.count = count; this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
15.642857
54
0.6621
3ceb18a6daf002d6f69b696363c731028d7929b2
4,264
/* Copyright 2012-2013 Eduworks Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.eduworks.gwt.client.net.packet; import java.util.Iterator; import java.util.Set; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONBoolean; import com.google.gwt.json.client.JSONException; import com.google.gwt.json.client.JSONNull; import com.google.gwt.json.client.JSONNumber; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.client.rpc.AsyncCallback; public abstract class AjaxPacket extends JSONObject { //Required protected constructor public AjaxPacket() { super(); }; public AjaxPacket(JavaScriptObject o) { super(o); }; public AjaxPacket(JSONObject o) { super(o.getJavaScriptObject()); }; public void put(String key, Object jsonValue) { if (jsonValue instanceof String) super.put(key, new JSONString((String)jsonValue)); else if (jsonValue instanceof Number) super.put(key, new JSONNumber(Double.parseDouble(String.valueOf(jsonValue)))); else if (jsonValue instanceof JSONArray) super.put(key, (JSONArray)jsonValue); else if (jsonValue instanceof JSONObject) super.put(key, (JSONObject)jsonValue); else if (jsonValue instanceof Boolean) super.put(key, JSONBoolean.getInstance((Boolean)jsonValue)); else if (jsonValue==null) super.put(key, (JSONNull)jsonValue); else throw new JSONException(); } public String getString(String key) { JSONValue jv; try { jv = super.get(key); } catch (NullPointerException e) { return null; } if (jv!=null&&jv.isString()!=null) return jv.isString().stringValue(); return null; } public Integer getInteger(String key) { JSONValue jv; try { jv = super.get(key); } catch (NullPointerException e) { return null; } if (jv!=null&&jv.isNumber()!=null) return Integer.parseInt(String.valueOf(jv.isNumber().doubleValue())); return null; } public Double getDouble(String key) { JSONValue jv; try { jv = super.get(key); } catch (NullPointerException e) { return null; } if (jv!=null&&jv.isNumber()!=null) return (Double)jv.isNumber().doubleValue(); return null; } public JSONArray getArray(String key) { JSONValue jv; try { jv = super.get(key); } catch (NullPointerException e) { return null; } if (jv!=null&&jv.isArray()!=null) return jv.isArray(); return null; } public JSONObject getObject(String key) { JSONValue jv; try { jv = super.get(key); } catch (NullPointerException e) { return null; } if (jv!=null&&jv.isObject()!=null) return jv.isObject(); return null; } public Boolean getBoolean(String key) { JSONValue jv; try { jv = super.get(key); } catch (NullPointerException e) { return null; } if (jv!=null&&jv.isBoolean()!=null) return (Boolean)jv.isBoolean().booleanValue(); return null; } public native void remove(String key) /*-{ if (this['jsObject']!=null) delete this['jsObject'][key]; else delete this[key]; }-*/; public final native static JavaScriptObject parseJSON(String x) /*-{ var e = (x!=null)? x.replace(/[\r\n\t]/g," "): "{}"; return eval('(' + ((e==""||e==null)? '{}' : e) + ')'); }-*/; public final AjaxPacket mergePackets(AjaxPacket ap) { Set<String> keys = ap.keySet(); for (Iterator<String> keyPointer=keys.iterator();keyPointer.hasNext();) { String key = keyPointer.next(); this.put(key, ap.get(key)); } return this; } }
27.509677
82
0.674953
6c9cc486063449c72bf416511b6eac49024e8e0b
1,400
// // ======================================================================== // Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.http2.frames; public abstract class Frame { public static final int HEADER_LENGTH = 9; public static final int DEFAULT_MAX_LENGTH = 0x40_00; public static final int MAX_MAX_LENGTH = 0xFF_FF_FF; public static final Frame[] EMPTY_ARRAY = new Frame[0]; private final FrameType type; protected Frame(FrameType type) { this.type = type; } public FrameType getType() { return type; } @Override public String toString() { return String.format("%s@%x", getClass().getSimpleName(), hashCode()); } }
30.434783
78
0.569286
8737fb83055cdedfbcb38d2a1e019824c647a9d9
1,449
package uk.ac.cam.cl.dtg.segue.dao.content; import ma.glasnost.orika.CustomConverter; import ma.glasnost.orika.MappingContext; import ma.glasnost.orika.metadata.Type; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * AudienceOrikaConverter A specialist converter class to work with the Orika automapper library. * * Responsible for converting the intended audience data structure from DO to DTO. * This converter will be adopted by Orika whenever it introspects a conversion between these specific types (not only * for the audience field). Its implementation is generic so that is fine. * It seems ORIKA is not good at converting between highly nested data structures. */ public class AudienceOrikaConverter extends CustomConverter<List<Map<String, List<String>>>, List<Map<String, List<String>>>> { @Override public List<Map<String, List<String>>> convert( List<Map<String, List<String>>> maps, Type<? extends List<Map<String, List<String>>>> type, MappingContext _context) { if (maps == null) {return null;} // This is horrible to read but it is a deep copy of the data structure - better safe than sorry. return maps.stream().map(m -> m.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().collect(Collectors.toList())))) .collect(Collectors.toList()); } }
42.617647
119
0.710835
a8005c0ac669b55568339d72efad2a31653dc387
2,592
package tetris.model; public class Game { private final Board board; private Piece nextPiece; private boolean playing = false; private boolean paused = false; private boolean dropping = false; private boolean gameOver = false; private int freeFallIterations; private int totalScore; public Game() { board = new Board(); } public BoardCell[][] getBoardCells() { return board.getBoardWithPiece(); } public Piece getNextPiece() { return nextPiece; } public long getIterationDelay() { return (long) (((11 - getLevel()) * 0.05) * 1000); } public int getScore() { return ((21 + (3 * getLevel())) - freeFallIterations); } public int getTotalScore() { return totalScore; } public int getLines() { return board.getFullLines(); } public int getLevel() { if ((board.getFullLines() >= 1) && (board.getFullLines() <= 90)) { return 1 + ((board.getFullLines() - 1) / 10); } else if (board.getFullLines() >= 91) { return 10; } else { return 1; } } public void startGame() { paused = false; dropping = false; nextPiece = Piece.getRandomPiece(); board.setCurrentPiece(Piece.getRandomPiece()); playing = true; } public boolean isPlaying() { return playing; } public boolean isPaused() { return paused; } public boolean isGameOver() { return gameOver; } public void pauseGame() { paused = !paused; } public void moveLeft() { board.moveLeft(); } public void moveRight() { board.moveRight(); } public void moveDown() { if (!board.canCurrentPieceMoveDown()) { if (freeFallIterations == 0) { playing = false; gameOver = true; } else { dropping = false; board.setCurrentPiece(nextPiece); nextPiece = Piece.getRandomPiece(); totalScore += getScore(); freeFallIterations = 0; } } else { board.moveDown(); freeFallIterations++; } } public void rotate() { board.rotate(); } public void drop() { dropping = true; } public boolean isDropping() { return dropping; } }
22.153846
75
0.504244
fb8c61994aa83413432d095f1575551656ea4d95
417
package com.truthbean.ffmpeg.constant; /** * @author truthbean */ public enum ImageStreamType { /** * yuv420p */ YUV(0), /** * rgba */ RGB(1), /** * jpeg */ JPEG(2); private int value; ImageStreamType(int value) { this.value = value; } /** * @return the value */ public int getValue() { return value; } }
11.914286
38
0.467626
8bcbc2e960a51b18e0dce011c25c097448274da8
8,025
package org.apereo.cas.web.flow.resolver.impl.mfa.adaptive; import lombok.extern.slf4j.Slf4j; import org.apereo.cas.CentralAuthenticationService; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.AuthenticationException; import org.apereo.cas.authentication.AuthenticationServiceSelectionPlan; import org.apereo.cas.authentication.AuthenticationSystemSupport; import org.apereo.cas.authentication.MultifactorAuthenticationUtils; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.configuration.model.core.authentication.TimeBasedAuthenticationProperties; import org.apereo.cas.services.MultifactorAuthenticationProvider; import org.apereo.cas.services.MultifactorAuthenticationProviderSelector; import org.apereo.cas.services.RegisteredService; import org.apereo.cas.services.ServicesManager; import org.apereo.cas.ticket.registry.TicketRegistrySupport; import org.apereo.cas.util.CollectionUtils; import org.apereo.cas.web.flow.authentication.BaseMultifactorAuthenticationProviderEventResolver; import org.apereo.cas.web.support.WebUtils; import org.apereo.inspektr.audit.annotation.Audit; import org.springframework.web.util.CookieGenerator; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.format.TextStyle; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * This is {@link TimedMultifactorAuthenticationPolicyEventResolver}. * * @author Misagh Moayyed * @since 5.2.0 */ @Slf4j public class TimedMultifactorAuthenticationPolicyEventResolver extends BaseMultifactorAuthenticationProviderEventResolver { private final List<TimeBasedAuthenticationProperties> timedMultifactor; public TimedMultifactorAuthenticationPolicyEventResolver(final AuthenticationSystemSupport authenticationSystemSupport, final CentralAuthenticationService centralAuthenticationService, final ServicesManager servicesManager, final TicketRegistrySupport ticketRegistrySupport, final CookieGenerator warnCookieGenerator, final AuthenticationServiceSelectionPlan authenticationSelectionStrategies, final MultifactorAuthenticationProviderSelector selector, final CasConfigurationProperties casProperties) { super(authenticationSystemSupport, centralAuthenticationService, servicesManager, ticketRegistrySupport, warnCookieGenerator, authenticationSelectionStrategies, selector); this.timedMultifactor = casProperties.getAuthn().getAdaptive().getRequireTimedMultifactor(); } @Override public Set<Event> resolveInternal(final RequestContext context) { final RegisteredService service = resolveRegisteredServiceInRequestContext(context); final Authentication authentication = WebUtils.getAuthentication(context); if (service == null || authentication == null) { LOGGER.debug("No service or authentication is available to determine event for principal"); return null; } if (timedMultifactor == null || timedMultifactor.isEmpty()) { LOGGER.debug("Adaptive authentication is not configured to require multifactor authentication by time"); return null; } final Map<String, MultifactorAuthenticationProvider> providerMap = MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext); if (providerMap == null || providerMap.isEmpty()) { LOGGER.error("No multifactor authentication providers are available in the application context"); throw new AuthenticationException(); } final Set<Event> providerFound = checkTimedMultifactorProvidersForRequest(context, service, authentication); if (providerFound != null && !providerFound.isEmpty()) { LOGGER.warn("Found multifactor authentication providers [{}] required for this authentication event", providerFound); return providerFound; } return null; } private Set<Event> checkTimedMultifactorProvidersForRequest(final RequestContext context, final RegisteredService service, final Authentication authentication) { final LocalDateTime now = LocalDateTime.now(); final DayOfWeek dow = DayOfWeek.from(now); final List<String> dayNamesForToday = Arrays.stream(TextStyle.values()) .map(style -> dow.getDisplayName(style, Locale.getDefault())) .collect(Collectors.toList()); final Map<String, MultifactorAuthenticationProvider> providerMap = MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext); final TimeBasedAuthenticationProperties timed = this.timedMultifactor.stream() .filter(t -> { boolean providerEvent = false; if (!t.getOnDays().isEmpty()) { providerEvent = t.getOnDays().stream().filter(dayNamesForToday::contains).findAny().isPresent(); } if (t.getOnOrAfterHour() >= 0) { providerEvent = now.getHour() >= t.getOnOrAfterHour(); } if (t.getOnOrBeforeHour() >= 0) { providerEvent = now.getHour() <= t.getOnOrBeforeHour(); } return providerEvent; }) .findFirst() .orElse(null); if (timed != null) { final Optional<MultifactorAuthenticationProvider> providerFound = resolveProvider(providerMap, timed.getProviderId()); if (!providerFound.isPresent()) { LOGGER.error("Adaptive authentication is configured to require [{}] for [{}], yet [{}] absent in the configuration.", timed.getProviderId(), service, timed.getProviderId()); throw new AuthenticationException(); } return buildEvent(context, service, authentication, providerFound.get()); } return null; } private Set<Event> buildEvent(final RequestContext context, final RegisteredService service, final Authentication authentication, final MultifactorAuthenticationProvider provider) { if (provider.isAvailable(service)) { LOGGER.debug("Attempting to build an event based on the authentication provider [{}] and service [{}]", provider, service.getName()); final Event event = validateEventIdForMatchingTransitionInContext(provider.getId(), context, buildEventAttributeMap(authentication.getPrincipal(), service, provider)); return CollectionUtils.wrapSet(event); } LOGGER.warn("Located multifactor provider [{}], yet the provider cannot be reached or verified", provider); return null; } @Audit(action = "AUTHENTICATION_EVENT", actionResolverName = "AUTHENTICATION_EVENT_ACTION_RESOLVER", resourceResolverName = "AUTHENTICATION_EVENT_RESOURCE_RESOLVER") @Override public Event resolveSingle(final RequestContext context) { return super.resolveSingle(context); } }
52.11039
136
0.672025