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
ff6a1ac9ccbff7b2cdaedf02af7fb828abb609ae
989
package com.example.android.miwok; public class Word { private String miwok; private String english; //Instead of storing image if we save image's resource id memory will be saved private int ImageResourceId; private int AudioResourceId; public Word(String english,String miwok,int imageResourceId,int audioResourceId){ this.miwok=miwok; this.english=english; this.AudioResourceId=audioResourceId; this.ImageResourceId=imageResourceId; } public Word(String english,String miwok,int audioResourceId){ this.miwok=miwok; this.english=english; this.AudioResourceId=audioResourceId; this.ImageResourceId=-1; } public String getDefaultTranslation(){ return english; } public String getMiwokTranslation(){ return miwok; } public int getImageResourceId() { return ImageResourceId; } public int getAudioResourceId(){ return AudioResourceId;} }
30.90625
85
0.69363
8600562a5e27292730ed528fb2f5cbb2328db525
1,058
package mvp.data.store; import android.content.Context; import java.io.File; /** * Created by ericYang on 2017/5/26. * Email:eric.yang@huanmedia.com * what? */ public class FilePathManager { //--------------------------------App缓存路径 public static File getImageCacheDir(Context context){ return StorageUtil.getIndividualCacheDirectory(context,"cacheImg"); } public static File getHttpCacheDir(Context context){ return StorageUtil.getIndividualCacheDirectory(context,"httpCache"); } public static File getCacheDir(Context context){ return StorageUtil.getIndividualCacheDirectory(context,"cache"); } public static File getApkDir(Context context){ return StorageUtil.getIndividualCacheDirectory(context,"apk"); } public static File getUpImage(Context context){ return StorageUtil.getIndividualCacheDirectory(context,"upImage"); } public static File getMaskDir(Context context) { return StorageUtil.getIndividualCacheDirectory(context,"mask",false); } }
30.228571
77
0.706994
559cc7a8a50f21bb5c2a0c01ca31934c6a8c7b13
504
package com.gempukku.libgdx.graph.ui.graph; import com.badlogic.gdx.scenes.scene2d.Event; import com.badlogic.gdx.utils.JsonValue; public class GetSerializedGraph extends Event { private String id; private JsonValue graph; public GetSerializedGraph(String id) { this.id = id; } public String getId() { return id; } public JsonValue getGraph() { return graph; } public void setGraph(JsonValue graph) { this.graph = graph; } }
18.666667
47
0.654762
57da0c3f507c28ab0f4c04c3e2ab849f4fef2dd8
3,601
package editorModule; import datatype.ComboItem; import main.App; import transferHandling.FileChooser; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; public class ConnectionNode { private JComboBox<ComboItem> comboBoxOutput; private JComboBox<ComboItem> comboBoxInput; private String[] comboBoxItems = {"ReVize Server", "Filesystem", "Copy & Paste"}; private JPanel parentPanel; private JButton transformationButton; private JLabel outputFormat; private JLabel inputFormat; private JLabel pathLabel; private String inputMode = ""; private String outputMode = ""; private File selectedTransformer; public ConnectionNode(Timeslot originTimeslot, Timeslot destinationTimeslot) { ComboItem comboItemReVize = new ComboItem("ReVize Server", "Value 1"); ComboItem comboItemFilesystem = new ComboItem("Filesystem", "Value 2"); comboBoxOutput.addItem(comboItemReVize); comboBoxInput.addItem(comboItemReVize); comboBoxOutput.addItem(comboItemFilesystem); comboBoxInput.addItem(comboItemFilesystem); comboBoxOutput.addActionListener (new ActionListener() { public void actionPerformed(ActionEvent e) { Object selectedItem = comboBoxOutput.getSelectedItem(); if (comboItemReVize.equals(selectedItem)) { outputMode = "revizeServer"; /*for (Source Source : originTimeslot.getElementList()) { Source.setDataExchangeChannel("revizeServer"); }*/ } else if (comboItemFilesystem.equals(selectedItem)) { outputMode = "fileSystem"; /*for (Source Source : originTimeslot.getElementList()) { Source.setDataExchangeChannel("fileSystem"); }*/ } } }); comboBoxInput.addActionListener (new ActionListener() { public void actionPerformed(ActionEvent e) { Object selectedItem = comboBoxOutput.getSelectedItem(); if (comboItemReVize.equals(selectedItem)) { inputMode = "revizeServer"; /*for (Source Source : originTimeslot.getElementList()) { Source.setDataExchangeChannel("revizeServer"); }*/ } else if (comboItemFilesystem.equals(selectedItem)) { inputMode = "fileSystem"; /*for (Source Source : originTimeslot.getElementList()) { Source.setDataExchangeChannel("fileSystem"); }*/ } } }); transformationButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Import Tool FileChooser fileChooser = new FileChooser(); File importFile = fileChooser.getFileFromChooser(); if(importFile != null) { selectedTransformer = importFile; } else { App.globalLogger.warning("File without Content"); } } }); } public JPanel getPanel() { return parentPanel; } }
34.625
85
0.557623
2963755be90a8a702d397b2bbc329a36ff7c0d52
521
package org.ovirt.engine.ui.common.widget; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.MenuItemSeparator; public class TitleMenuItemSeparator extends MenuItemSeparator { public TitleMenuItemSeparator(String title) { super(); DOM.setInnerHTML(getElement(), "<b>" + title + "</b>"); setStyleName("gwt-MenuItem"); } public TitleMenuItemSeparator(SafeHtml title) { this(title.asString()); } }
27.421053
63
0.704415
33996ea01e50d03ef85050f892ab84107bfe5fa8
321
package com.subrosagames.subrosa.domain.game; /** * Represents a game rule. */ public interface Rule { /** * Get rule type. * * @return rule type */ RuleType getRuleType(); /** * Get rule description. * * @return rule description */ String getDescription(); }
14.590909
45
0.560748
fbed45c121e7cc87d43d18a8a425f2e7d7080a50
318
package sample; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Label; public class Controller { @FXML private Label labelHello; @FXML public void handleButtonAction(Event e){ labelHello.setText("Bye JavaFX"); System.out.println("Button clicked"); } }
21.2
45
0.704403
2cb123c0d5a6adee97ce73a4a6b39d7979733a87
399
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int a,b; System.out.println("A sayısını giriniz: "); a = input.nextInt(); System.out.println("B sayısını giriniz: "); b = input.nextInt(); System.out.println("A ve B sayısının toplamı : " + (a+b)); } }
21
66
0.573935
41acd74ffa96d42a9eb96a3a9cc9ba79b4634ab4
4,311
package net.kenevans.polar.trainingsession; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Exercise { @SerializedName("startTime") @Expose private String startTime; @SerializedName("stopTime") @Expose private String stopTime; @SerializedName("timezoneOffset") @Expose private Integer timezoneOffset; @SerializedName("duration") @Expose private String duration; @SerializedName("distance") @Expose private Double distance; @SerializedName("sport") @Expose private String sport; @SerializedName("latitude") @Expose private Double latitude; @SerializedName("longitude") @Expose private Double longitude; @SerializedName("kiloCalories") @Expose private Integer kiloCalories; @SerializedName("heartRate") @Expose private HeartRate heartRate; @SerializedName("speed") @Expose private Speed speed; @SerializedName("zones") @Expose private Zones zones; @SerializedName("samples") @Expose private Samples samples; /** * No args constructor for use in serialization * */ public Exercise() { } /** * * @param startTime * @param distance * @param duration * @param speed * @param heartRate * @param kiloCalories * @param sport * @param longitude * @param timezoneOffset * @param latitude * @param zones * @param samples * @param stopTime */ public Exercise(String startTime, String stopTime, Integer timezoneOffset, String duration, Double distance, String sport, Double latitude, Double longitude, Integer kiloCalories, HeartRate heartRate, Speed speed, Zones zones, Samples samples) { super(); this.startTime = startTime; this.stopTime = stopTime; this.timezoneOffset = timezoneOffset; this.duration = duration; this.distance = distance; this.sport = sport; this.latitude = latitude; this.longitude = longitude; this.kiloCalories = kiloCalories; this.heartRate = heartRate; this.speed = speed; this.zones = zones; this.samples = samples; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getStopTime() { return stopTime; } public void setStopTime(String stopTime) { this.stopTime = stopTime; } public Integer getTimezoneOffset() { return timezoneOffset; } public void setTimezoneOffset(Integer timezoneOffset) { this.timezoneOffset = timezoneOffset; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public Double getDistance() { return distance; } public void setDistance(Double distance) { this.distance = distance; } public String getSport() { return sport; } public void setSport(String sport) { this.sport = sport; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Integer getKiloCalories() { return kiloCalories; } public void setKiloCalories(Integer kiloCalories) { this.kiloCalories = kiloCalories; } public HeartRate getHeartRate() { return heartRate; } public void setHeartRate(HeartRate heartRate) { this.heartRate = heartRate; } public Speed getSpeed() { return speed; } public void setSpeed(Speed speed) { this.speed = speed; } public Zones getZones() { return zones; } public void setZones(Zones zones) { this.zones = zones; } public Samples getSamples() { return samples; } public void setSamples(Samples samples) { this.samples = samples; } }
22.221649
249
0.627233
3d38937df0a2b0c9fa45258d29469b5627886c28
914
package org.narrative.common.util.video; import org.narrative.common.util.audio.AudioMetadata; /** * Date: 5/14/14 * Time: 11:06 AM * * @author brian */ public class AudioVideoMetadata { private String errorOutput; private AudioMetadata audioMetadata; private VideoMetadata videoMetadata; public AudioVideoMetadata() {} public String getErrorOutput() { return errorOutput; } public void setErrorOutput(String errorOutput) { this.errorOutput = errorOutput; } public AudioMetadata getAudioMetadata() { return audioMetadata; } public void setAudioMetadata(AudioMetadata audioMetadata) { this.audioMetadata = audioMetadata; } public VideoMetadata getVideoMetadata() { return videoMetadata; } public void setVideoMetadata(VideoMetadata videoMetadata) { this.videoMetadata = videoMetadata; } }
21.761905
63
0.694748
10d77961e60b3758c136b37f1cda0bc86052d328
10,908
/* * 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. * */ /** * Action class to route to appropriate URL for drilldown from INBOX */ package org.egov.egf.web.actions.payment; import com.exilant.eGov.src.transactions.VoucherTypeForULB; import com.opensymphony.xwork2.validator.annotations.Validations; 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.apache.struts2.interceptor.validation.SkipValidation; import org.egov.egf.web.actions.voucher.BaseVoucherAction; import org.egov.eis.service.EisCommonService; import org.egov.infra.admin.master.entity.AppConfig; import org.egov.infra.admin.master.service.AppConfigService; import org.egov.infra.admin.master.service.AppConfigValueService; import org.egov.infra.workflow.service.SimpleWorkflowService; import org.egov.model.advance.EgAdvanceRequisition; import org.egov.model.payment.Paymentheader; import org.egov.utils.FinancialConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; /** * @author mani */ @ParentPackage("egov") @Validations @Results({ @Result(name = "billpayment", type = "redirectAction", location = "payment-view", params = { "namespace", "/payment", "paymentid", "${paymentid}" }), @Result(name = "advancepayment", type = "redirectAction", location = "payment-advanceView", params = { "namespace", "/payment", "paymentid", "${paymentid}" }), @Result(name = "directbankpayment", type = "redirectAction", location = "directBankPayment-viewInboxItem", params = { "namespace", "/payment", "paymentid", "${paymentid}" }), @Result(name = "remitRecovery", type = "redirectAction", location = "remitRecovery-viewInboxItem", params = { "namespace", "/deduction", "paymentid", "${paymentid}" }), @Result(name = "contractoradvancepayment", type = "redirectAction", location = "advancePayment-viewInboxItem", params = { "namespace", "/payment", "paymentid", "${paymentid}" }) }) public class BasePaymentAction extends BaseVoucherAction { private static final long serialVersionUID = 8589393885303282831L; EisCommonService eisCommonService; private static Logger LOGGER = Logger.getLogger(BasePaymentAction.class); @Autowired @Qualifier("workflowService") private SimpleWorkflowService<Paymentheader> paymentHeaderWorkflowService; @Autowired private VoucherTypeForULB voucherTypeForULB; @Autowired AppConfigService appConfigService; public void setEisCommonService(final EisCommonService eisCommonService) { this.eisCommonService = eisCommonService; } public BasePaymentAction() { super(); } @Override public void prepare() { super.prepare(); bankBalanceValidation(); } protected String action = ""; protected String paymentid = ""; private final String BILLPAYMENT = "billpayment"; private final String DIRECTBANKPAYMENT = "directbankpayment"; private final String REMITTANCEPAYMENT = "remitRecovery"; public static final String ARF_TYPE = "Contractor"; private String bankBalanceCheck = ""; protected static final String ACTIONNAME = "actionname"; protected boolean canCheckBalance = false; public boolean isCanCheckBalance() { return canCheckBalance; } public void setCanCheckBalance(final boolean canCheckBalance) { this.canCheckBalance = canCheckBalance; } @Autowired protected AppConfigValueService appConfigValuesService; protected String showMode; @SkipValidation @Action(value = "/payment/basePayment-viewInboxItems") public String viewInboxItems() { if (LOGGER.isDebugEnabled()) LOGGER.debug("Starting viewInboxItems..... "); String result = null; final Paymentheader paymentheader = (Paymentheader) persistenceService.find("from Paymentheader where id=?", Long.valueOf(paymentid)); if (!validateOwner(paymentheader.getState())) return INVALIDPAGE; getSession().put("paymentid", paymentid); if (paymentheader.getVoucherheader().getName() .equalsIgnoreCase(FinancialConstants.PAYMENTVOUCHER_NAME_ADVANCE)) { final EgAdvanceRequisition arf = (EgAdvanceRequisition) persistenceService.find( "from EgAdvanceRequisition where arftype = ? and egAdvanceReqMises.voucherheader = ?", ARF_TYPE, paymentheader.getVoucherheader()); if (arf != null) result = "contractoradvancepayment"; else result = "advancepayment"; } else if (paymentheader.getVoucherheader().getName() .equalsIgnoreCase(FinancialConstants.PAYMENTVOUCHER_NAME_BILL) || FinancialConstants.PAYMENTVOUCHER_NAME_SALARY .equalsIgnoreCase(paymentheader.getVoucherheader().getName()) || FinancialConstants.PAYMENTVOUCHER_NAME_PENSION .equalsIgnoreCase(paymentheader.getVoucherheader().getName())) result = BILLPAYMENT; else if (paymentheader.getVoucherheader().getName() .equalsIgnoreCase(FinancialConstants.PAYMENTVOUCHER_NAME_DIRECTBANK)) result = DIRECTBANKPAYMENT; else if (paymentheader.getVoucherheader().getName() .equalsIgnoreCase(FinancialConstants.PAYMENTVOUCHER_NAME_REMITTANCE)) result = REMITTANCEPAYMENT; if (LOGGER.isDebugEnabled()) LOGGER.debug("Completed viewInboxItems..... "); return result; } // used only in create public boolean shouldshowVoucherNumber() { String vNumGenMode = "Manual"; vNumGenMode = voucherTypeForULB.readVoucherTypes(FinancialConstants.STANDARD_VOUCHER_TYPE_PAYMENT); if (!"Auto".equalsIgnoreCase(vNumGenMode)) { mandatoryFields.add("vouchernumber"); return true; } else return false; } /* * This api is to check bank balance and allow to create bill based on appconfig values like mandatory, warning, none. */ public void bankBalanceValidation() { final AppConfig appConfig = appConfigService.getAppConfigByModuleNameAndKeyName( FinancialConstants.MODULE_NAME_APPCONFIG, FinancialConstants.BALANCE_CHECK_CONTROL_TYPE); if (appConfig != null && !appConfig.getConfValues().isEmpty()) { final String appValue = appConfig.getConfValues().get(0).getValue(); if (FinancialConstants.MANDATORY.equalsIgnoreCase(appValue)) bankBalanceCheck = appValue.toLowerCase(); else if (FinancialConstants.WARNING.equalsIgnoreCase(appValue)) bankBalanceCheck = appValue.toLowerCase(); else if (NONE.equalsIgnoreCase(appValue)) bankBalanceCheck = appValue.toLowerCase(); } } public String getAction() { return action; } public void setAction(final String action) { this.action = action; } public String getPaymentid() { return paymentid; } public void setPaymentid(final String paymentid) { this.paymentid = paymentid; } public String getShowMode() { return showMode; } public void setShowMode(final String showMode) { this.showMode = showMode; } public String getFinConstExpendTypeContingency() { return FinancialConstants.STANDARD_EXPENDITURETYPE_CONTINGENT; } public String getFinConstExpendTypePension() { return FinancialConstants.STANDARD_EXPENDITURETYPE_PENSION; } public SimpleWorkflowService<Paymentheader> getPaymentHeaderWorkflowService() { return paymentHeaderWorkflowService; } public void setPaymentHeaderWorkflowService(final SimpleWorkflowService<Paymentheader> paymentHeaderWorkflowService) { this.paymentHeaderWorkflowService = paymentHeaderWorkflowService; } public String getBankBalanceCheck() { return bankBalanceCheck; } public void setBankBalanceCheck(final String bankBalanceCheck) { this.bankBalanceCheck = bankBalanceCheck; } }
42.776471
129
0.695545
854f7210b5db5ffe0dc73278bde1d79567532a94
574
package indi.ikun.spring.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * @Author caddyR * @Description 服务注册中心 @EnableEurekaServer//注册中心开启注解 * @Date 2019-03-06 11:40 * @Param * @return **/ @EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
22.076923
74
0.771777
9180a2122eaa59905ddc9817a776b2a7aa8b42e6
3,543
package eu.pixelstube.cloud.console; import eu.pixelstube.cloud.CloudLauncher; import eu.pixelstube.cloud.command.ICommandHandler; import eu.pixelstube.cloud.console.setup.SetupBuilder; import org.apache.commons.io.Charsets; import org.jline.reader.LineReader; import org.jline.reader.LineReaderBuilder; import org.jline.reader.UserInterruptException; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; import java.io.IOException; /** * This file was created by Max H. (Haizoooon) * Date: 15.05.2021 * Copyright© 2021 Max H. **/ public class ConsoleManager { private final LineReader lineReader; private Thread thread; private final ConsoleCompleter consoleCompleter; private final String prompt = Color.RESET.getColor() + Color.WHITE.getColor() + System.getProperty("user.name") + Color.RESET.getColor() + "@" + Color.CYAN.getColor() + "stubencloud-v1.0.0" + Color.RESET.getColor() + " $ "; public ConsoleManager() { consoleCompleter = new ConsoleCompleter(); lineReader = createLineReader(); startThread(); } private LineReader createLineReader(){ Terminal terminal = null; try { System.setProperty("org.jline.terminal.dumb", "true"); terminal = TerminalBuilder.builder().system(true).streams(System.in, System.out).encoding(Charsets.UTF_8).dumb(true).build(); } catch (IOException exception) { exception.printStackTrace(); } return LineReaderBuilder.builder() .completer(consoleCompleter) .terminal(terminal) .option(LineReader.Option.DISABLE_EVENT_EXPANSION, true) .option(LineReader.Option.AUTO_REMOVE_SLASH, false) .option(LineReader.Option.INSERT_TAB, false) .build(); } public void startThread(){ thread = new Thread(() -> { try { String line; while(!Thread.currentThread().isInterrupted()){ line = lineReader.readLine(prompt); handleInput(line); } }catch (UserInterruptException ignored){} }); thread.start(); } public void handleInput(String input){ if(SetupBuilder.getCurrentSetup() != null){ SetupBuilder.nextQuestion(SetupBuilder.getCurrentSetup().getCurrentInput().handle(input)); return; } if(input.isEmpty()){ return; } String[] args = input.split(" "); String command = args[0]; if(CloudLauncher.getInstance().getCommandManager().getCommandHandlerByName(command) == null){ CloudLauncher.getInstance().getCloudLogger().warning("The command could not be found! Please type 'help' for help."); return; } ICommandHandler commandHandler = CloudLauncher.getInstance().getCommandManager().getCommandHandlerByName(command); commandHandler.handle(CloudLauncher.getInstance().getConsoleSender(), args); } public void stopThread() { lineReader.getTerminal().reader().shutdown(); lineReader.getTerminal().pause(); thread.interrupt(); } public LineReader getLineReader() { return lineReader; } public ConsoleCompleter getConsoleCompleter() { return consoleCompleter; } public String getPrefix() { return prompt; } }
31.633929
137
0.627152
3e77b9c7018903e481afe2734ea3a8145192d436
1,538
package com.arm4j.weixin.request.qrcode; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.arm4j.core.DefaultEntityParam; import com.arm4j.core.DefaultURLParam; import com.arm4j.weixin.WeiXinCoreManagement; import com.arm4j.weixin.WeiXinToken; import com.arm4j.weixin.exception.WeiXinRequestException; import com.arm4j.weixin.request.qrcode.entity.QRCodeEntity; import com.arm4j.weixin.request.qrcode.response.QRCodeResponse; import org.apache.commons.lang3.StringUtils; @SuppressWarnings("unchecked") public class WeiXinQRCodeCreateRequest { public static QRCodeResponse request(String accessToken, QRCodeEntity entity) throws WeiXinRequestException { // 发送请求 String result = WeiXinCoreManagement.getInstance().get(WeiXinToken.QRCODE_CREATE) .createConn() .connect( new DefaultURLParam.Builder() .add("access_token", accessToken) .build(), new DefaultEntityParam(JSON.toJSONString(entity)) ).doPost(); // 处理返回结果 if (!StringUtils.isEmpty(result)) { JSONObject resultJSON = JSON.parseObject(result); if (resultJSON.containsKey("ticket")) { return JSON.parseObject(result, QRCodeResponse.class); } else { throw new WeiXinRequestException(result); } } throw new WeiXinRequestException("请求失败,原因[未知]"); } }
37.512195
113
0.656697
60c52571e7c9837c66400357666901b158b87f7a
1,576
package com.meo.stonymoon.enrichedday.ui.discovery.child; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.meo.stonymoon.enrichedday.R; public class TestFragment extends Fragment { private Button testButton; public TestFragment() { // Required empty public constructor } public static TestFragment newInstance(String param1, String param2) { TestFragment fragment = new TestFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_test, container, false); testButton = (Button) view.findViewById(R.id.test_button); testButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://bangumi.bilibili.com/anime/3461/play#85754")); startActivity(intent); } }); return view; } }
27.649123
96
0.663706
9228fa73205e38b98ff3ee9a7b6505574dfb47c4
263
package com.jadaptive.plugins.remote; import org.pf4j.PluginWrapper; import com.jadaptive.api.spring.AbstractSpringPlugin; public class RemoteUsersPlugin extends AbstractSpringPlugin { public RemoteUsersPlugin(PluginWrapper wrapper) { super(wrapper); } }
20.230769
61
0.81749
345af5f5523fedc28507881a06d5ed944a86f5a6
2,265
/** * The MIT License (MIT) * <p/> * Copyright (c) 2015 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.android.multievent; import android.telephony.PhoneStateListener; /** * @author Bertrand Martel */ public class PhoneListener extends PhoneStateListener { private MultiEvent manager = null; public PhoneListener(MultiEvent manager) { this.manager = manager; } public void onCallStateChanged(int state, String incomingNumber) { if (state == 1) { if (manager != null && manager.getPhoneCallListenerList() != null) { //Phone is rining for (int i = 0; i < manager.getPhoneCallListenerList().size(); i++) { manager.getPhoneCallListenerList().get(i).onIncomingCall(incomingNumber); } } } else if (state == 2) { if (manager != null && manager.getPhoneCallListenerList() != null) { //call has been taken for (int i = 0; i < manager.getPhoneCallListenerList().size(); i++) { manager.getPhoneCallListenerList().get(i).onOffHook(); } } } } }
39.051724
93
0.660486
2fdaceb9952de4741b6e1f004a2c4a5e14926703
936
package api.rest.privateapi.read.feeinfo; import api.rest.Json; import api.rest.privateapi.read.feeinfo.dto.FeeInfoDto; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import lombok.extern.log4j.Log4j2; @Log4j2 public class FeeInfo implements FeeInfoData { private final Json jsonSource; public FeeInfo() { this(new FeeInfoAsJson()); } public FeeInfo(Json jsonSource) { this.jsonSource = jsonSource; } @Override public FeeInfoDto data() throws Exception { try { return new Gson().fromJson( jsonSource.json(), new TypeToken<FeeInfoDto>() { }.getType() ); } catch (Exception e) { final String message = "Error retrieving data from Api - {}"; log.error(message, e.getMessage()); throw new Exception(message, e); } } }
25.297297
73
0.599359
d89384b4c67cac41b1921ae87f5e6bca7b11af7f
612
package net.sabamiso.android.androidnotificationtest; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.app.NotificationCompat; public class DummyActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dummy); Intent intent = new Intent(this, DummyService.class); startService(intent); } @Override protected void onResume() { super.onResume(); } }
25.5
61
0.73366
f86435a68bae3aa13c05f99c3803bd3d60229eb3
1,590
import java.util.Scanner; public class ClientView { private final Scanner input; public ClientView() { input = new Scanner(System.in); } public void printOpponentMoved(String loc) { System.out.println(String.format("Opponent moved to location %s", loc)); } public void printBeginGame() { System.out.println("You are beginning the game. Provide location [A-C][1-3] eg. A2"); } public void printGameBoard(String gameBoard) { StringBuffer sb = new StringBuffer().append(" 123").append('\n'); sb.append("A ").append(gameBoard.substring(0,3)).append('\n'); sb.append("B ").append(gameBoard.substring(4,7)).append('\n'); sb.append("C ").append(gameBoard.substring(8,11)).append('\n'); System.out.println(sb.toString()); } public String readLocation() { return input.next(); } public void printMoveNotAllowed() { System.out.println("Move not allowed. Try again..."); } public void printReceivedMessageError(Exception e) { System.out.println("Error during message receiving. Error: " + e.getMessage()); } public void printWin() { System.out.println("You win"); } public void printTie() { System.out.println("Game finished with tie"); } public void printDefeated() { System.out.println("You are defeated!"); } public void printEndGame() { System.out.println("You has been disconnected from server!"); } }
26.949153
94
0.59434
f94c5c022709890152690fb7581ffd2743ed95b6
5,689
/** * * Copyright (C) 2012-2013 DuyHai DOAN * * 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 info.archinnov.achilles.context; import static info.archinnov.achilles.entity.metadata.PropertyType.*; import static info.archinnov.achilles.type.ConsistencyLevel.*; import static org.fest.assertions.api.Assertions.*; import static org.mockito.Mockito.*; import info.archinnov.achilles.entity.metadata.EntityMeta; import info.archinnov.achilles.entity.metadata.PropertyMeta; import info.archinnov.achilles.entity.operations.CQLEntityProxifier; import info.archinnov.achilles.proxy.ReflectionInvoker; import info.archinnov.achilles.test.builders.PropertyMetaTestBuilder; import info.archinnov.achilles.test.mapping.entity.CompleteBean; import info.archinnov.achilles.type.OptionsBuilder; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.math.RandomUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.powermock.reflect.Whitebox; @RunWith(MockitoJUnitRunner.class) public class CQLPersistenceContextFactoryTest { private CQLPersistenceContextFactory pmf; @Mock private CQLDaoContext daoContext; @Mock private ConfigurationContext configContext; @Mock private CQLEntityProxifier proxifier; @Mock private ReflectionInvoker invoker; @Mock private CQLImmediateFlushContext flushContext; private Map<Class<?>, EntityMeta> entityMetaMap; private EntityMeta meta; private PropertyMeta idMeta; @Before public void setUp() throws Exception { meta = new EntityMeta(); idMeta = PropertyMetaTestBuilder.completeBean(Void.class, Long.class).field("id").type(ID).accessors() .invoker(invoker).build(); meta.setIdMeta(idMeta); meta.setEntityClass(CompleteBean.class); entityMetaMap = new HashMap<Class<?>, EntityMeta>(); entityMetaMap.put(CompleteBean.class, meta); pmf = new CQLPersistenceContextFactory(daoContext, configContext, entityMetaMap); Whitebox.setInternalState(pmf, ReflectionInvoker.class, invoker); } @Test public void should_create_new_context_for_entity_with_consistency_and_ttl() throws Exception { Long primaryKey = RandomUtils.nextLong(); CompleteBean entity = new CompleteBean(primaryKey); when((Class) proxifier.deriveBaseClass(entity)).thenReturn(CompleteBean.class); when(invoker.getPrimaryKey(entity, idMeta)).thenReturn(primaryKey); CQLPersistenceContext actual = pmf.newContext(entity, OptionsBuilder.withConsistency(EACH_QUORUM).withTtl(95)); assertThat(actual.getEntity()).isSameAs(entity); assertThat(actual.getPrimaryKey()).isSameAs(primaryKey); assertThat(actual.getPrimaryKey()).isSameAs(primaryKey); assertThat(actual.getEntityClass()).isSameAs((Class) CompleteBean.class); assertThat(actual.getEntityMeta()).isSameAs(meta); assertThat(actual.getIdMeta()).isSameAs(idMeta); assertThat(actual.getTtt().get()).isEqualTo(95); } @Test public void should_create_new_context_for_entity() throws Exception { Long primaryKey = RandomUtils.nextLong(); CompleteBean entity = new CompleteBean(primaryKey); when((Class) proxifier.deriveBaseClass(entity)).thenReturn(CompleteBean.class); when(invoker.getPrimaryKey(entity, idMeta)).thenReturn(primaryKey); CQLPersistenceContext actual = pmf.newContext(entity); assertThat(actual.getEntity()).isSameAs(entity); assertThat(actual.getPrimaryKey()).isSameAs(primaryKey); assertThat(actual.getEntityClass()).isSameAs((Class) CompleteBean.class); assertThat(actual.getEntityMeta()).isSameAs(meta); assertThat(actual.getIdMeta()).isSameAs(idMeta); assertThat(actual.getTtt()).isSameAs(CQLPersistenceContextFactory.NO_TTL); } @Test public void should_create_new_context_with_primary_key() throws Exception { Object primaryKey = RandomUtils.nextLong(); CQLPersistenceContext context = pmf.newContext(CompleteBean.class, primaryKey, OptionsBuilder.withConsistency(LOCAL_QUORUM).withTtl(98)); assertThat(context.getEntity()).isNull(); assertThat(context.getPrimaryKey()).isSameAs(primaryKey); assertThat(context.getEntityClass()).isSameAs((Class) CompleteBean.class); assertThat(context.getEntityMeta()).isSameAs(meta); assertThat(context.getIdMeta()).isSameAs(idMeta); assertThat(context.getTtt().get()).isEqualTo(98); } @Test public void should_create_new_context_for_slice_query() throws Exception { Long primaryKey = RandomUtils.nextLong(); List<Object> partitionComponents = Arrays.<Object> asList(primaryKey); when(invoker.instanciateEmbeddedIdWithPartitionComponents(idMeta, partitionComponents)).thenReturn(primaryKey); CQLPersistenceContext actual = pmf .newContextForSliceQuery(CompleteBean.class, partitionComponents, EACH_QUORUM); assertThat(actual.getEntity()).isNull(); assertThat(actual.getPrimaryKey()).isSameAs(primaryKey); assertThat(actual.getEntityClass()).isSameAs((Class) CompleteBean.class); assertThat(actual.getEntityMeta()).isSameAs(meta); assertThat(actual.getIdMeta()).isSameAs(idMeta); assertThat(actual.getTtt().isPresent()).isFalse(); } }
37.183007
113
0.792231
494715733e5ad476f90048d1a5d4fe6829d64e54
2,096
/* * Copyright (c) 2010-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.repo.api; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.exception.SchemaException; /** * Central point of dispatching notifications about changes to the system configuration object. * * @author mederly */ public interface SystemConfigurationChangeDispatcher { /** * Dispatches information on system configuration object change. * * Basically this directly pushes information to lower layers (prism, schema, repo, etc), and calls registered * listeners that originate in upper layers. * * @param ignoreVersion If false, the information is dispatched unconditionally. If true, we dispatch the notification only * if the system configuration version was really changed. This is to easily support sources that * "ping" sysconfig object in regular intervals, e.g. the cluster manager thread. * @param allowNotFound If true, we take non-existence of sysconfig object more easily. To be used e.g. on system init or * during tests execution. */ void dispatch(boolean ignoreVersion, boolean allowNotFound, OperationResult result) throws SchemaException; /** * Registers a listener that will be updated on system configuration object changes. */ void registerListener(SystemConfigurationChangeListener listener); /** * Unregisters a listener. */ void unregisterListener(SystemConfigurationChangeListener listener); }
38.814815
124
0.744752
df1e8e3f77a277a4f66a12c992650cd136ae9fe9
2,618
/** * Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2006-2016 * * 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.glite.security.voms.admin.view.actions.configuration; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Result; import org.glite.security.voms.admin.configuration.VOMSConfiguration; import org.glite.security.voms.admin.util.URLBuilder; import org.glite.security.voms.admin.view.actions.BaseAction; import com.opensymphony.xwork2.Preparable; @Result(name = BaseAction.SUCCESS, location = "configuration") public class ConfigurationAction extends BaseAction implements Preparable { /** * */ private static final long serialVersionUID = 1L; String vomsesConf; String mkGridmapConf; String contactString; String lsc; public void prepare() throws Exception { contactString = URLBuilder.baseVOMSURLFromConfiguration(); vomsesConf = VOMSConfiguration.instance().getVomsesConfigurationString(); HttpServletRequest request = ServletActionContext.getRequest(); // Build mkgridmap configuration mkGridmapConf = "group vomss://" + request.getServerName() + ":" + request.getServerPort() + "/voms/" + VOMSConfiguration.instance().getVOName() + " ." + VOMSConfiguration.instance().getVOName(); lsc = VOMSConfiguration.instance().getLSCConfiguration(); } public String getVomsesConf() { return vomsesConf; } public void setVomsesConf(String vomsesConf) { this.vomsesConf = vomsesConf; } public String getMkGridmapConf() { return mkGridmapConf; } public void setMkGridmapConf(String mkGridmapConf) { this.mkGridmapConf = mkGridmapConf; } public String getContactString() { return contactString; } public void setContactString(String contactString) { this.contactString = contactString; } public String getLSC() { return lsc; } public String getLsc() { return lsc; } public void setLsc(String lsc) { this.lsc = lsc; } }
24.240741
77
0.732238
ecbd6624832015a87a5222762b62ebd662411a60
621
package com.solverpeng.example; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; public interface GreetingService { String getGreetingMsg(); @Service @Profile("dev") class DevGreetingService implements GreetingService { @Override public String getGreetingMsg() { return "hi from dev"; } } @Service @Profile("prod") class ProductionGreetingService implements GreetingService { @Override public String getGreetingMsg() { return "hi from production"; } } }
21.413793
64
0.658615
98a2182eb1497e7e71af34f68070ed40eb6fccde
1,223
package com.inti.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; 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.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.inti.entities.User; import com.inti.services.interfaces.IUserService; @RestController @RequestMapping(value = "/") public class UserController { @Autowired IUserService userService ; @GetMapping(value="users") public List<User> findAll() { return userService.findAll(); } @GetMapping(value="user/{id}") public User findById(@PathVariable("id") Long idUser) { return userService.findById(idUser).orElse(null); } @PostMapping(value="user") public User save(@RequestBody User user) { return userService.save(user); } @DeleteMapping(value="user/{id}") public void delete(@PathVariable("id") long idUser) { userService.delete(idUser); } }
27.795455
62
0.785773
9e9d9c9199956ce002197f0cfa2f3bbaea6b8a06
3,504
/******************************************************************************* * Copyright (c) 2013 Humberto Fraga <xisberto@gmail.com>. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Humberto Fraga <xisberto@gmail.com> - initial API and implementation ******************************************************************************/ package net.xisberto.phonetodesktop; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.preference.PreferenceManager; public class Preferences { private static final String ACCOUNT_NAME = "accountName", LIST_ID = "listId", LAST_SENT_TEXT = "lastSentText"; private static String ONLY_LINKS, UNSHORTEN, GET_TITLES, SHOW_PREVIEW; private SharedPreferences prefs; private static Preferences sPreferences; public static Preferences getInstance(Context context) { if (sPreferences == null) { sPreferences = new Preferences(context); } return sPreferences; } private Preferences(Context context) { prefs = PreferenceManager.getDefaultSharedPreferences(context .getApplicationContext()); ONLY_LINKS = context.getString(R.string.pref_only_links); UNSHORTEN = context.getString(R.string.pref_unshorten); GET_TITLES = context.getString(R.string.pref_get_titles); SHOW_PREVIEW = context.getString(R.string.pref_show_preview); } public String loadAccountName() { return prefs.getString(ACCOUNT_NAME, null); } public String loadListId() { return prefs.getString(LIST_ID, null); } public String loadLastSentText() { return prefs.getString(LAST_SENT_TEXT, null); } public boolean loadOnlyLinks() { return prefs.getBoolean(ONLY_LINKS, false); } public boolean loadUnshorten() { return prefs.getBoolean(UNSHORTEN, false); } public boolean loadGetTitles() { return prefs.getBoolean(GET_TITLES, false); } public boolean loadShowPreview() { return prefs.getBoolean(SHOW_PREVIEW, true); } private void saveString(String key, String value) { SharedPreferences.Editor editor = prefs.edit(); editor.putString(key, value); apply(editor); } public void saveAccountName(String accountName) { saveString(ACCOUNT_NAME, accountName); } public void saveListId(String listId) { saveString(LIST_ID, listId); } public void saveLastSentText(String text) { saveString(LAST_SENT_TEXT, text); } private void saveBoolean(String key, boolean value) { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(key, value); apply(editor); } public void saveOnlyLinks(boolean value) { saveBoolean(ONLY_LINKS, value); } public void saveUnshorten(boolean value) { saveBoolean(UNSHORTEN, value); } public void saveGetTitles(boolean value) { saveBoolean(GET_TITLES, value); } public void saveShowPreview(boolean value) { saveBoolean(SHOW_PREVIEW, value); } public void removeListId() { SharedPreferences.Editor editor = prefs.edit(); editor.remove(LIST_ID); apply(editor); } @SuppressLint("NewApi") public void apply(Editor editor) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { editor.apply(); } else { editor.commit(); } } }
26.953846
80
0.712329
cfe2ba47be2884a78ae73c249c161ad96e5facd2
14,891
/** * Adopted from Joy Aether Ltd. * * Licensed under the agreement between Joy Aether Ltd. and IDT * Internation Ltd. (the "License"); * * 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.oregonscientific.meep.database; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingStrategy; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.internal.$Gson$Types; import com.google.gson.reflect.TypeToken; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; public final class ModelAttributes { private final Class<?> raw; private final FieldNamingStrategy fieldNamingPolicy; private Map<String, Field> columns; /** * Constructs a Model Attributes object from the {@code type} * @param type the model to pull attributes from */ public ModelAttributes(Class<?> type) { this(type, FieldNamingPolicy.IDENTITY); } /** * Constructs a Model Attributes object from the {@code type} with the * given {@code namingPolicy} * @param type the model to pull attributes from * @param namingPolicy the naming strategy to use for naming the Field(s) */ public ModelAttributes(Class<?> type, FieldNamingStrategy namingPolicy) { raw = type; fieldNamingPolicy = namingPolicy; columns = new HashMap<String, Field>(); if (!type.isInterface()) { Class<?> rawType = raw; TypeToken<?> typeToken = TypeToken.get(rawType); while (rawType != Object.class) { Field[] fields = rawType.getDeclaredFields(); for (Field field : fields) { if (isDatabaseField(field) || isForeignCollection(field)) { columns.put(getFieldSerializedName(field), field); } } typeToken = TypeToken.get($Gson$Types.resolve( typeToken.getType(), rawType, rawType.getGenericSuperclass())); rawType = typeToken.getRawType(); } } } /** * Returns the name of the database table the class Model represents * @return the name of the database table */ public String getTableName() { DatabaseTable table = raw == null ? null : raw.getAnnotation(DatabaseTable.class); return table == null ? raw.getSimpleName() : table.tableName(); } /** * Returns a Class object that identifies the declared type for the * field represented by this Field object. If it was a foreign field, the * declared type for the ID field associated with the foreign object is * returned * @param fieldName the name of the Field * @return a Class object identifying the declared type of the field * represented by this object */ public Class<?> getColumnType(String fieldName) { Field field = columns.get(fieldName); if (isForeignField(field)) { ModelAttributes attr = new ModelAttributes(field.getType()); return attr.getIdField() == null ? null : attr.getColumns().get(attr.getIdField()).getType(); } return field == null ? null : field.getType(); } /** * Returns the serialized name in the foreign collection that defines the relationship * between the type of the ModelAttribute and the objects on the foreign collection * * @param fieldName the serialzied name of the foreign collection * @return the column name that defines the relationship, null if the field specified * was not a foreign collection */ public String getForeignCollectionForeignName(String fieldName) { String result = null; String foreignFieldName = null; ModelAttributes attrs = Schema.getAttributes((Class<?>) getColumnGenericType(fieldName)); if (attrs == null || !isForeignCollection(fieldName)) { return result; } // Determines whether or not the a foreign collection field name is // specified in the annotation ForeignCollectionField fcField = columns.get(fieldName).getAnnotation(ForeignCollectionField.class); foreignFieldName = fcField == null ? null : fcField.foreignFieldName(); // Loop through the foreign collection object to find the field // that corresponds to the {@code} raw type of the model attributes for (String name : attrs.columns.keySet()) { Field field = attrs.columns.get(name); boolean isRequestedField = false; if (foreignFieldName == null || foreignFieldName.isEmpty()) { isRequestedField = field.getType().equals(raw); } else { isRequestedField = field.getName().equals(foreignFieldName); } // Found the foreign field if (isRequestedField) { result = name; break; } } return result; } /** * Returns a Type object that represents the declared type of the given column. * If the column was a foreign collection, the Type object returned reflects the * type of the containing element * * @param columnName the name of the database column * @return the type of the given column, null if the column was not found */ public Type getColumnGenericType(String columnName) { Field field = columns.get(columnName); if (isForeignCollection(field)) { Type genericFieldType = field.getGenericType(); if (genericFieldType instanceof ParameterizedType) { ParameterizedType foreignCollectionType = (ParameterizedType) genericFieldType; Type[] fieldArgTypes = foreignCollectionType.getActualTypeArguments(); return fieldArgTypes.length > 0 ? fieldArgTypes[0] : null; } } else { return field == null ? null : field.getGenericType(); } return null; } /** * Retrieves the database column name of the a given Field * @param fieldName the name of the Field * @return the database column name of a given Field */ public String getColumnName(String fieldName) { Field field = columns.get(fieldName); return field == null ? "" : getColumnName(field); } /** * Returns the {@link Field} with the given {@code fieldName} * * @param fieldName the name of the field * @return the {@link Field} with the given name */ public Field getField(String fieldName) { // Quick return if there is nothing to process if (fieldName == null) { return null; } Field result = columns.get(fieldName); if (result == null) { Collection<Field> fields = columns.values(); for (Field field : fields) { if (field.getName().equals(fieldName)) { result = field; break; } } } return result; } /** * Returns the name of the ID field of the data class * @return The name of the ID field, null if no ID field is found */ public String getIdField() { for (String fieldName : columns.keySet()) { if (isIdField(columns.get(fieldName))) { return fieldName; } } // Can be null if there was no ID field in a data class return null; } /** * Returns whether or not the ID field of the data class is generated * @return true if the ID column was auto generated, false otherwise */ public boolean isIdFieldGenerated() { String idFieldName = getIdField(); return idFieldName == null ? false : isGeneratedId(columns.get(idFieldName)); } /** * Returns the columns in a data model * @return a map of columns the data model represents. */ public Map<String, Field> getColumns() { return Collections.unmodifiableMap(columns); } /** * Determines whether or not a Field represents an ID column * @param columnName the column name of field being examined * @return true if the Field represents an ID column, false otherwise */ public boolean isIdColumn(String columnName) { return isIdField(columns.get(columnName)); } /** * Determines whether a given column represents a foreign field * @param columnName the column name of field being examined * @return true if the Field represents a foreign field, false otherwise */ public boolean isForeignField(String columnName) { return isForeignField(columns.get(columnName)); } /** * Determines whether or not a given column is a foreign collection * * @param columnName * the column name of field to determine whether it is a foreign * collection * @return true if the field is a foreign collection, false otherwise */ public boolean isForeignCollection(String columnName) { return isForeignCollection(columns.get(columnName)); } /** * Determines whether or not a given field's value should be encrypted * * @param columnName * the name of the database column * @return true if the field should be encrypted, false otherwise */ public boolean shouldEncryptColumn(String columnName) { return shouldEncryptField(columns.get(columnName)); } /** * Determines whether or not a given column is exposed for de/serialization * * @param columnName * the column name of field to determine whether it is expose * @return true if the field was exposed, false otherwise */ public boolean isColumnExposed(String columnName) { return isFieldExposed(columns.get(columnName)); } /** * Determines whether or not a given field is a password field * * @param columnName * the column name of field to determine whether it is a password * field * @return true if the field is a password field, false otherwise */ public boolean isPasswordColumn(String columnName) { return isPasswordField(columns.get(columnName)); } /** * Determines whether or not the given field should be omitted in equality comparison * * @param field the field to determine whether it should be omitted * @return true if the field should be omitted, false otherwise */ public boolean shouldFieldBeOmitted(Field f) { Omit omit = f == null ? null : f.getAnnotation(Omit.class); return omit == null ? false : omit.value(); } /** * Determines whether or not a given field is a password field * * @param f * the field to determine whether it is a password field * @return true if the field is a password field, false otherwise */ private boolean isPasswordField(Field f) { PasswordField pwdField = f == null ? null : f.getAnnotation(PasswordField.class); return pwdField != null; } /** * Determines whether or not a given field is exposed for de/serialization * * @param f * the field to determine whether it is expose * @return true if the field was exposed, false otherwise */ private boolean isFieldExposed(Field f) { Expose expose = f == null ? null : f.getAnnotation(Expose.class); return expose == null ? false : true; } /** * Determines whether a Field object is a foreign field * * @param f * the field being examined * @return true if the Field represents a foreign field, false otherwise */ private boolean isForeignField(Field f) { DatabaseField databaseField = f == null ? null : f.getAnnotation(DatabaseField.class); return databaseField == null ? false : databaseField.foreign(); } /** * Determines whether or not a given field is a foreign collection * * @param f * the field to determine whether it is a foreign collection * @return true if the field is a foreign collection, false otherwise */ private boolean isForeignCollection(Field f) { ForeignCollectionField foreignCollectionField = f == null ? null : f .getAnnotation(ForeignCollectionField.class); return foreignCollectionField != null; } /** * Determines whether or not a given field's value should be encrypted * * @param f * the field to determine whether its value should be encrypted * @return true if the field should be encrypted, false otherwise */ private boolean shouldEncryptField(Field f) { Encrypt encrypt = f == null ? null : f.getAnnotation(Encrypt.class); return encrypt != null; } /** * Determines whether or not a Field represents an ID column * * @param f * the field being examined * @return true if the Field represents an ID column, false otherwise */ private boolean isIdField(Field f) { DatabaseField databaseField = f == null ? null : f.getAnnotation(DatabaseField.class); return databaseField == null ? false : databaseField.id() || databaseField.generatedId() || (databaseField.generatedIdSequence() != null && !databaseField.generatedIdSequence().isEmpty()); } /** * Determines whether or not a Field represents an auto generated ID column * * @param f * the field being examined * @return true if the Field represents an auto generated ID column, false * otherwise */ private boolean isGeneratedId(Field f) { DatabaseField databaseField = f == null ? null : f.getAnnotation(DatabaseField.class); return databaseField == null ? false : databaseField.generatedId() || !databaseField.generatedIdSequence().isEmpty(); } /** * Determines whether or not a Field represents a column in the database * table * * @param f * the field being examined * @return true if the Field represents a database column, false otherwise */ private boolean isDatabaseField(Field f) { DatabaseField databaseField = f == null ? null : f.getAnnotation(DatabaseField.class); return databaseField != null; } /** * Retrieves the database column name of the a given Field * * @param f * the Field object * @return the database column name of a given Field */ private String getColumnName(Field f) { DatabaseField databaseField = f == null ? null : f.getAnnotation(DatabaseField.class); return databaseField == null ? f == null ? "" : f.getName() : databaseField.columnName(); } /** * Returns the name of the given column * * @param field * the field to return the name * @return the name of the field */ private String getFieldSerializedName(Field field) { return getFieldSerializedName(field, fieldNamingPolicy); } /** * Returns the serialized name of the column using the given naming policy * * @param f * the field to return the name * @param namingPolicy * the naming policy used to serialize name of the column * @return the name of the field */ private String getFieldSerializedName(Field f, FieldNamingStrategy namingPolicy) { SerializedName serializedName = f == null ? null : f.getAnnotation(SerializedName.class); return serializedName == null ? namingPolicy.translateName(f) : serializedName.value(); } }
32.655702
119
0.704318
640dffe118e5032c71c97d194031552dd99fa793
1,327
package com.gos.rebound_rumble.commands; import edu.wpi.first.wpilibj.Joystick; import com.gos.rebound_rumble.OI; import com.gos.rebound_rumble.subsystems.Shooter; public class Shoot extends CommandBase { private final Shooter m_shooter; private final OI m_oi; private final Joystick m_operatorJoystick; private final double m_speed; public Shoot(Shooter shooter, OI oi, double speed) { this.m_speed = speed; m_shooter = shooter; m_oi = oi; m_operatorJoystick = m_oi.getOperatorJoystick(); requires(m_shooter); } @Override protected void initialize() { m_shooter.initEncoder(); m_shooter.initPID(); } @Override protected void execute() { m_shooter.shoot(m_speed); if (Math.abs(m_operatorJoystick.getThrottle()) >= 0.3 || Math.abs(m_operatorJoystick.getTwist()) >= 0.3) { m_shooter.topRollersForward(); } } @Override protected boolean isFinished() { return false; } @Override protected void end() { if (!m_oi.areTopRollersOverriden()) { m_shooter.topRollersOff(); } m_shooter.disablePID(); m_shooter.stopEncoder(); } @Override protected void interrupted() { end(); } }
22.87931
64
0.62321
cd2c2822a7afb45025812144aa432cc5ccb83738
4,572
package com.company; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class DifficultyClassifier { private static int numberOfContainers; Map<String, Integer> cWords; public DifficultyClassifier(String dirPath) throws Exception { cWords = classifyWords(dirPath + "lib" + File.separator + "mostFreqWords.txt"); } /** * @param wordFile - file location of word list txt document with words in * difficulty order * @return - Map with each word mapped to a difficulty level from 1 to 10. * Scale is set exponentially (2x, 4x, 8x, 16x, 32x, etc.) */ private Map<String, Integer> classifyWords(String wordFile) throws Exception { return classifyWords(wordFile, 10); } /** * * @param wordFile - file location of word list txt document with words in * difficulty order * @param containers - number of containers to be created representing the number of difficulty levels * @return - Map with each word mapped to a difficulty container from a scale of 1 to the container * valued specified. Scale is set exponentially (2x, 4x, 8x, 16x, 32x, etc.) * @throws Exception - If container value passed is less than 2 */ private Map<String, Integer> classifyWords(String wordFile, int containers) throws Exception { if (containers < 3) { throw new Exception("Container Error: Number of containers must be at least 2."); } // Container constant set to container value. numberOfContainers = containers; // Subtract one from containers, largest container value reserved for words not in mostFreqWords.txt containers -= 1; Map<String, Integer> classifiedWords = new TreeMap<>(); int totalWords = totalNumberWords(wordFile); // Calculate splitter value based on number of containers double growth = 2; double splitter = 0; for(int i = 0; i < containers; i++){ splitter += growth; growth *= 2; } double varX = totalWords / splitter; // Calculating the number of words in each container level and storing in array File file = new File(wordFile); Scanner sc = new Scanner(file); Integer[] levelCount = new Integer[containers]; int wordCount = 0; for (int i = 0; i < containers; i++){ levelCount[i] = (int) (Math.pow(2.0, i + 1) * varX); wordCount += levelCount[i]; // If the total words are not split evenly, all extra words are placed into the // second to last container element in array if(i == containers-1){ levelCount[i] += (totalWords - wordCount); ; } } // Words are mapped to difficulty container based on array, levelCount, created above for(int i = 0; i < containers; i++){ for (int v = levelCount[i]; v > 0; v--){ String next = sc.nextLine(); classifiedWords.put(next, i + 1); } } sc.close(); return classifiedWords; } /** * @param wordFile - file location of word list txt document with words in difficulty order * @return - Integer representing the total number of words in wordFile * @throws IOException */ private int totalNumberWords(String wordFile) throws IOException { int wordCount = 0; File file = new File(wordFile); Scanner sc = new Scanner(file); while (sc.hasNextLine()) { wordCount++; sc.nextLine(); } sc.close(); return wordCount; } /** * @param word - String that needs to be found in wordList * @return - integer representing the difficult on a scale of 1 to 9. If word is not * found in wordList, difficulty level 10 is returned * @throws IOException */ public int wordClassification(String word) throws IOException { word = word.toLowerCase().replaceAll("\\s", ""); if(cWords.containsKey(word)){ return cWords.get(word); } else { // If the word is not found in Map, the word is defined to be in the highest difficulty container return numberOfContainers; } } public int getContainerCount(){ return numberOfContainers; } }
36.870968
110
0.601925
751c27deaa6d44f1c95d27e00f331b031a0429b7
1,592
package com.jun.mqttx.service.impl; import com.alibaba.fastjson.JSON; import com.jun.mqttx.config.MqttxConfig; import com.jun.mqttx.entity.PubMsg; import com.jun.mqttx.service.IRetainMessageService; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.util.Assert; /** * 存储通过 redis 实现 * * @author Jun * @since 1.0.4 */ @Service public class RetainMessageServiceImpl implements IRetainMessageService { /** * redis retain message prefix */ private final String retainMessageHashKey; private StringRedisTemplate stringRedisTemplate; public RetainMessageServiceImpl(StringRedisTemplate stringRedisTemplate, MqttxConfig mqttxConfig) { Assert.notNull(stringRedisTemplate, "stringRedisTemplate can't be null"); this.stringRedisTemplate = stringRedisTemplate; this.retainMessageHashKey = mqttxConfig.getRedis().getRetainMessagePrefix(); Assert.hasText(retainMessageHashKey, "retainMessagePrefix can't be null"); } @Override public void save(String topic, PubMsg pubMsg) { stringRedisTemplate.opsForHash().put(retainMessageHashKey, topic, JSON.toJSONString(pubMsg)); } @Override public void remove(String topic) { stringRedisTemplate.opsForHash().delete(retainMessageHashKey, topic); } @Override public PubMsg get(String topic) { String pubMsg = (String) stringRedisTemplate.opsForHash().get(retainMessageHashKey, topic); return JSON.parseObject(pubMsg, PubMsg.class); } }
31.84
103
0.747487
72b5ce5e2fd409de2bf7e725a731ae9d84834c18
3,031
package com.javamaster.b2c.cloud.test.security.repository; import java.util.ArrayList; import java.util.List; import javax.annotation.security.RolesAllowed; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreFilter; import org.springframework.stereotype.Repository; import com.javamaster.b2c.cloud.test.security.entity.Authority; import com.javamaster.b2c.cloud.test.security.entity.User; @Repository public class UserRepository { @Autowired private JdbcTemplate jdbcTemplate; public User findUserByUserId(String userId) { String s = "select * from users where userid=?"; User user = jdbcTemplate.queryForObject(s, (var1, var2) -> { User user1 = new User(); user1.setUserId(var1.getString("userid")); user1.setUsername(var1.getString("username")); user1.setPassword(var1.getString("password")); int enabled = var1.getInt("enabled"); if (enabled == 1) { user1.setEnabled(true); } else if (enabled == 0) { user1.setEnabled(false); } return user1; }, new Object[]{userId}); user.setAuthorities(findAuthoritisByUserId(userId)); return user; } public List<Authority> findAuthoritisByUserId(String userId) { String s = "select * from authorities where userid=?"; List<Authority> authoritys = jdbcTemplate.query(s, (var1, var2) -> { Authority authority1 = new Authority(); String authorityname = var1.getString("authorityname"); authority1.setAuthority(authorityname); return authority1; }, new Object[]{userId}); return authoritys; } // @PreAuthorize("hasRole('ROLE_ROOT')") @Secured("ROLE_ROOT") public void secured(User user) { System.out.println("secured start"); } // @PreAuthorize("hasRole('ROLE_ROOT')") @RolesAllowed("ROLE_ROOT") public void rolesAllowed(User user) { System.out.println("rolesAllowed start"); } @PreAuthorize("hasRole('ROLE_ROOT') and #user.userId=='218826483963'") @PostFilter("filterObject.userId=='218826483963'") public List<User> preAuthorize(User user) { System.out.println("preAuthorize start"); List<User> users = new ArrayList<>(); return users; } @PreFilter("targetObject.userId=='218826483963'") @PostAuthorize("returnObject.userId=='218826483963'") public User postAuthorize(List<User> users) { users.get(0).setUserId("218826483963"); System.out.println("postAuthorize start"); return users.get(0); } }
36.083333
76
0.673705
486c9588fd997b299252e18c4e26f266fb650629
18,446
package org.jp.illg.dstar.reflector.protocol.dplus.model; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.UUID; import org.jp.illg.dstar.DSTARDefines; import org.jp.illg.dstar.model.BackBoneHeader; import org.jp.illg.dstar.model.BackBoneHeaderFrameType; import org.jp.illg.dstar.model.BackBoneHeaderType; import org.jp.illg.dstar.model.DVPacket; import org.jp.illg.dstar.model.Header; import org.jp.illg.dstar.model.VoiceAMBE; import org.jp.illg.dstar.model.VoiceData; import org.jp.illg.dstar.model.defines.ConnectionDirectionType; import org.jp.illg.dstar.model.defines.DSTARProtocol; import org.jp.illg.dstar.reflector.model.ReflectorPacket; import org.jp.illg.dstar.reflector.protocol.model.ReflectorConnectTypes; import org.jp.illg.dstar.util.DSTARCRCCalculator; import org.jp.illg.util.ArrayUtil; import org.jp.illg.util.FormatUtil; import com.annimon.stream.Optional; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; public class DPlusPacketImpl extends ReflectorPacket implements DPlusPacket{ @Getter @Setter(AccessLevel.PRIVATE) private DPlusPacketType dPlusPacketType; @Getter @Setter(AccessLevel.PRIVATE) private DPlusPoll poll; @Getter @Setter(AccessLevel.PRIVATE) private DPlusConnect connect; public DPlusPacketImpl( final DPlusPacketType dplusPacketType, final UUID loopBlockID, final ConnectionDirectionType connectionDirection, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final DVPacket packet ) { super(DSTARProtocol.DCS, loopBlockID, connectionDirection, remoteAddress, localAddress, packet); setDPlusPacketType(dplusPacketType); } public DPlusPacketImpl(final DPlusPoll poll) { this( DPlusPacketType.POLL, null, ConnectionDirectionType.Unknown, (InetSocketAddress)null, (InetSocketAddress)null, null ); setPoll(poll); } public DPlusPacketImpl(final DPlusConnect connect) { this( DPlusPacketType.CONNECT, null, ConnectionDirectionType.Unknown, (InetSocketAddress)null, (InetSocketAddress)null, null ); setConnect(connect); } /* * ------------------------------------------------------ */ public DPlusPacketImpl( final DPlusPacketType dplusPacketType, final UUID loopBlockID, final ConnectionDirectionType connectionDirection, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final Header header, final VoiceData voice, final BackBoneHeader backbone ) { this( dplusPacketType, loopBlockID, connectionDirection, remoteAddress, localAddress, new DVPacket(backbone, header, voice) ); } public DPlusPacketImpl( final UUID loopBlockID, final ConnectionDirectionType connectionDirection, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final Header header, final BackBoneHeader backbone ) { this( DPlusPacketType.HEADER, loopBlockID, connectionDirection, remoteAddress, localAddress, new DVPacket(backbone, header) ); } public DPlusPacketImpl( final UUID loopBlockID, final ConnectionDirectionType connectionDirection, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final VoiceData voice, final BackBoneHeader backbone ) { this( DPlusPacketType.VOICE, loopBlockID, connectionDirection, remoteAddress, localAddress, new DVPacket(backbone, voice) ); } /* * ------------------------------------------------------ */ public DPlusPacketImpl( final DPlusPacketType dplusPacketType, final UUID loopBlockID, final ConnectionDirectionType connectionDirection, final Header header, final VoiceData voice, final BackBoneHeader backbone ) { this( dplusPacketType, loopBlockID, connectionDirection, null, null, header, voice, backbone ); } public DPlusPacketImpl( final UUID loopBlockID, final ConnectionDirectionType connectionDirection, final Header header, final BackBoneHeader backbone ) { this( loopBlockID, connectionDirection, null, null, header, backbone ); } public DPlusPacketImpl( final UUID loopBlockID, final ConnectionDirectionType connectionDirection, final VoiceData voice, final BackBoneHeader backbone ) { this( loopBlockID, connectionDirection, null, null, voice, backbone ); } /* * ------------------------------------------------------ */ public DPlusPacketImpl( final DPlusPacketType dplusPacketType, final Header header, final VoiceData voice, final BackBoneHeader backbone ) { this( dplusPacketType, null, ConnectionDirectionType.Unknown, null, null, header, voice, backbone ); } public DPlusPacketImpl( final Header header, final BackBoneHeader backbone ) { this( null, ConnectionDirectionType.Unknown, null, null, header, backbone ); } public DPlusPacketImpl( final VoiceData voice, final BackBoneHeader backbone ) { this( null, ConnectionDirectionType.Unknown, null, null, voice, backbone ); } @Override public DVPacket getDvPacket() { return this.getDVPacket(); } @Override public BackBoneHeader getBackBone() { return super.getBackBone(); } @Override public Header getRfHeader() { return super.getRfHeader(); } @Override public VoiceData getVoiceData() { return super.getVoiceData(); } @Override public char[] getRepeater2Callsign() { return super.getRfHeader().getRepeater2Callsign(); } @Override public char[] getRepeater1Callsign() { return super.getRfHeader().getRepeater1Callsign(); } @Override public char[] getYourCallsign() { return super.getRfHeader().getYourCallsign(); } @Override public char[] getMyCallsign() { return super.getRfHeader().getMyCallsign(); } @Override public char[] getMyCallsignAdd() { return super.getRfHeader().getMyCallsignAdd(); } @Override public DPlusPacketImpl clone() { DPlusPacketImpl copy = null; copy = (DPlusPacketImpl)super.clone(); copy.dPlusPacketType = this.dPlusPacketType; if(this.poll != null) {copy.poll = this.poll.clone();} if(this.connect != null) {copy.connect = this.connect.clone();} return copy; } @Override public String toString() { return toString(0); } public String toString(int indentLevel) { if(indentLevel < 0) {indentLevel = 0;} final StringBuilder sb = new StringBuilder(); FormatUtil.addIndent(sb, indentLevel); sb.append("[PacketType]:"); sb.append(getDPlusPacketType()); sb.append("\n"); switch(getDPlusPacketType()) { case CONNECT: sb.append(getConnect().toString(indentLevel + 4)); break; case POLL: sb.append(getPoll().toString(indentLevel + 4)); break; case HEADER: sb.append(getRfHeader().toString(indentLevel + 4)); sb.append("\n"); sb.append(getBackBone().toString(indentLevel + 4)); break; case VOICE: sb.append(getVoiceData().toString(indentLevel + 4)); sb.append("\n"); sb.append(getBackBone().toString(indentLevel + 4)); break; default: break; } return sb.toString(); } public static Optional<DPlusPacket> isValidConnectPacket(ByteBuffer buffer){ if(buffer == null) {return Optional.empty();} if(buffer.remaining() != 5 && buffer.remaining() != 8 && buffer.remaining() != 28) return Optional.empty(); final int bufferLength = buffer.remaining(); byte[] buf = null; int bufferOffset = 0; if(buffer.hasArray()) { buf = buffer.array(); bufferOffset = buffer.arrayOffset(); buffer.position(buffer.position() + bufferLength); }else { buf = new byte[bufferLength]; buffer.get(buf); } buffer.compact(); buffer.limit(buffer.position()); buffer.rewind(); ReflectorConnectTypes type = null; String repeaterCallsign = DSTARDefines.EmptyLongCallsign; boolean readonly = false; switch(bufferLength) { case 5: if(buf[bufferOffset + 4] == (byte)0x01) type = ReflectorConnectTypes.LINK; else if(buf[bufferOffset + 4] == (byte)0x00) type = ReflectorConnectTypes.UNLINK; else return Optional.empty(); break; case 8: final byte[] reply = Arrays.copyOfRange(buf, bufferOffset + 4, bufferOffset + 8); if(Arrays.equals(reply, "OKRW".getBytes())) type = ReflectorConnectTypes.ACK; else if(Arrays.equals(reply, "OKRO".getBytes())) { type = ReflectorConnectTypes.ACK; readonly = true; } else type = ReflectorConnectTypes.NAK; break; case 28: final StringBuffer sb = new StringBuffer(); for(int i = 4; i < 28; i++) { if(buf[bufferOffset + i] == 0x0) {break;} sb.append((char)buf[bufferOffset + i]); } repeaterCallsign = sb.toString(); type = ReflectorConnectTypes.LINK2; break; default: return Optional.empty(); } final DPlusConnect connect = new DPlusConnect(type); connect.setCallsign(repeaterCallsign); connect.setReadonly(readonly); return Optional.of((DPlusPacket)new DPlusPacketImpl(connect)); } public static Optional<byte[]> assembleConenctPacket(DPlusPacket packet) { if(packet == null || packet.getDPlusPacketType() != DPlusPacketType.CONNECT) return Optional.empty(); final DPlusConnect connect = packet.getConnect(); ReflectorConnectTypes type = connect.getType(); int bufLength = 0; byte[] buf = null; switch(type) { case LINK: bufLength = 5; buf = new byte[bufLength]; buf[0] = (byte) 0x05; buf[1] = (byte) 0x00; buf[2] = (byte) 0x18; buf[3] = (byte) 0x00; buf[4] = (byte) 0x01; break; case LINK2: bufLength = 28; buf = new byte[bufLength]; buf[0] = (byte) 0x1C; buf[1] = (byte) 0xC0; buf[2] = (byte) 0x04; buf[3] = (byte) 0x00; for(int i = 4; i < 20; i++) {buf[i] = 0x00;} String callsign = connect.getCallsign(); if(callsign != null) callsign = callsign.trim(); else callsign = DSTARDefines.EmptyLongCallsign; for (int i = 0; i < callsign.length(); i++) buf[i + 4] = (byte) callsign.charAt(i); buf[20] = 'D'; buf[21] = 'V'; buf[22] = '0'; buf[23] = '1'; buf[24] = '9'; buf[25] = '9'; buf[26] = '9'; buf[27] = '9'; break; case UNLINK: bufLength = 5; buf = new byte[bufLength]; buf[0] = (byte) 0x05; buf[1] = (byte) 0x00; buf[2] = (byte) 0x18; buf[3] = (byte) 0x00; buf[4] = (byte) 0x00; break; case ACK: bufLength = 8; buf = new byte[bufLength]; buf[0] = (byte) 0x08; buf[1] = (byte) 0xC0; buf[2] = (byte) 0x04; buf[3] = (byte) 0x00; buf[4] = 'O'; buf[5] = 'K'; buf[6] = 'R'; buf[7] = 'W'; break; case NAK: bufLength = 8; buf = new byte[bufLength]; buf[0] = (byte) 0x08; buf[1] = (byte) 0xC0; buf[2] = (byte) 0x04; buf[3] = (byte) 0x00; buf[4] = 'B'; buf[5] = 'U'; buf[6] = 'S'; buf[7] = 'Y'; break; default: return Optional.empty(); } return Optional.of(buf); } public static Optional<DPlusPacket> isValidPollPacket(ByteBuffer buffer){ if(buffer == null || buffer.remaining() <= 0) {return Optional.empty();} if(buffer.remaining() != 3) {return Optional.empty();} final int bufferLength = buffer.remaining(); byte[] buf = null; if(buffer.hasArray()) { buf = buffer.array(); buffer.position(buffer.position() + bufferLength); }else { buf = new byte[bufferLength]; buffer.get(buf); } buffer.compact(); buffer.limit(buffer.position()); buffer.rewind(); final DPlusPoll poll = new DPlusPoll(); return Optional.of((DPlusPacket)new DPlusPacketImpl(poll)); } public static Optional<byte[]> assemblePollPacket(DPlusPacket packet) { if(packet == null || packet.getDPlusPacketType() != DPlusPacketType.POLL) return Optional.empty(); final byte[] buf = new byte[3]; buf[0] = 0x03; buf[1] = 0x60; buf[2] = 0x00; return Optional.of(buf); } public static Optional<DPlusPacket> isValidHeaderPacket(ByteBuffer buffer){ if(buffer == null || buffer.remaining() <= 0) {return Optional.empty();} final int packetSize = buffer.remaining(); if(packetSize < 58) {return Optional.empty();} final byte[] head = new byte[2]; head[0] = buffer.get(); head[1] = buffer.get(); buffer.rewind(); if(head[0] != (byte)0x3A || head[1] != (byte)0x80) return Optional.empty(); byte[] buf = null; int bufferOffset = 0; if(buffer.hasArray()) { buf = buffer.array(); bufferOffset = buffer.arrayOffset(); buffer.position(buffer.position() + packetSize); }else { buf = new byte[packetSize]; buffer.get(buf); } buffer.compact(); buffer.limit(buffer.position()); buffer.rewind(); final BackBoneHeader bb = new BackBoneHeader(BackBoneHeaderType.DV, BackBoneHeaderFrameType.VoiceDataHeader); bb.setDestinationRepeaterID(buf[bufferOffset + 11]); bb.setSendRepeaterID(buf[bufferOffset + 12]); bb.setSendTerminalID(buf[bufferOffset + 13]); bb.getFrameID()[0] = buf[bufferOffset + 15]; bb.getFrameID()[1] = buf[bufferOffset + 14]; final Header header = new Header(); header.getFlags()[0] = buf[bufferOffset + 17]; header.getFlags()[1] = buf[bufferOffset + 18]; header.getFlags()[2] = buf[bufferOffset + 19]; ArrayUtil.copyOfRange( header.getRepeater2Callsign(), buf, bufferOffset + 20, bufferOffset + 20 + DSTARDefines.CallsignFullLength ); ArrayUtil.copyOfRange( header.getRepeater1Callsign(), buf, bufferOffset + 28, bufferOffset + 28 + DSTARDefines.CallsignFullLength ); ArrayUtil.copyOfRange( header.getYourCallsign(), buf, bufferOffset + 36, bufferOffset + 36 + DSTARDefines.CallsignFullLength ); ArrayUtil.copyOfRange( header.getMyCallsign(), buf, bufferOffset + 44, bufferOffset + 44 + DSTARDefines.CallsignFullLength ); ArrayUtil.copyOfRange( header.getMyCallsignAdd(), buf, bufferOffset + 52, bufferOffset + 52 + DSTARDefines.CallsignShortLength ); header.saveRepeaterCallsign(); final DPlusPacket packet = new DPlusPacketImpl(header, bb); return Optional.of(packet); } public static Optional<byte[]> assembleHeaderPacket(DPlusPacket packet) { if(packet == null || packet.getDPlusPacketType() != DPlusPacketType.HEADER) return Optional.empty(); final byte[] buf = new byte[58]; Arrays.fill(buf, (byte)0x00); buf[0] = (byte) 0x3A; buf[1] = (byte) 0x80; buf[2] = 'D'; buf[3] = 'S'; buf[4] = 'V'; buf[5] = 'T'; buf[6] = (byte) 0x10; buf[7] = (byte) 0x00; buf[8] = (byte) 0x00; buf[9] = (byte) 0x00; buf[10] = (byte) 0x20; buf[11] = packet.getBackBone().getDestinationRepeaterID(); buf[12] = packet.getBackBone().getSendRepeaterID(); buf[13] = packet.getBackBone().getSendTerminalID(); buf[14] = packet.getBackBone().getFrameID()[0]; buf[15] = packet.getBackBone().getFrameID()[1]; buf[16] = (byte) 0x80; buf[17] = (byte) 0x00; buf[18] = (byte) 0x00; buf[19] = (byte) 0x00; ArrayUtil.copyOfRange(buf, 20, packet.getRfHeader().getRepeater2Callsign()); ArrayUtil.copyOfRange(buf, 28, packet.getRfHeader().getRepeater1Callsign()); ArrayUtil.copyOfRange(buf, 36, packet.getRfHeader().getYourCallsign()); ArrayUtil.copyOfRange(buf, 44, packet.getRfHeader().getMyCallsign()); ArrayUtil.copyOfRange(buf, 52, packet.getRfHeader().getMyCallsignAdd()); int crc = DSTARCRCCalculator.calcCRCRange(buf, 17, 55); buf[56] = (byte)(crc & 0xff); buf[57] = (byte)((crc >> 8) & 0xff); return Optional.of(buf); } public static Optional<DPlusPacket> isValidVoicePacket(ByteBuffer buffer){ if(buffer == null || buffer.remaining() <= 0) {return Optional.empty();} final int packetSize = buffer.remaining(); if(packetSize < 29) {return Optional.empty();} final int[] head = new int[2]; head[0] = (int)(buffer.get() & 0xFF); head[1] = (int)(buffer.get() & 0xFF); buffer.rewind(); if((head[0] != 0x1D && head[0] != 0x20) || head[1] != 0x80) return Optional.empty(); byte[] buf = null; int bufferOffset = 0; if(buffer.hasArray()) { buf = buffer.array(); bufferOffset = buffer.arrayOffset(); buffer.position(buffer.position() + packetSize); }else { buf = new byte[packetSize]; buffer.get(buf); } buffer.compact(); buffer.limit(buffer.position()); buffer.rewind(); final BackBoneHeader bb = new BackBoneHeader( BackBoneHeaderType.DV, BackBoneHeaderFrameType.VoiceData ); bb.setDestinationRepeaterID(buf[bufferOffset + 11]); bb.setSendRepeaterID(buf[bufferOffset + 12]); bb.setSendTerminalID(buf[bufferOffset + 13]); bb.getFrameID()[0] = buf[bufferOffset + 15]; bb.getFrameID()[1] = buf[bufferOffset + 14]; bb.setManagementInformation(buf[bufferOffset + 16]); final VoiceData voice = new VoiceAMBE(); ArrayUtil.copyOfRange( voice.getVoiceSegment(), buf, bufferOffset + 17, bufferOffset + 17 + DSTARDefines.VoiceSegmentLength ); ArrayUtil.copyOfRange( voice.getDataSegment(), buf, bufferOffset + 26, bufferOffset + 26 + DSTARDefines.DataSegmentLength ); final DPlusPacket packet = new DPlusPacketImpl(voice, bb); return Optional.of(packet); } public static Optional<byte[]> assembleVoicePacket(DPlusPacket packet) { if(packet == null || packet.getDPlusPacketType() != DPlusPacketType.VOICE) return Optional.empty(); final boolean isLastFrame = packet.getDvPacket().isEndVoicePacket(); final byte[] buf = new byte[isLastFrame ? 32 : 29]; Arrays.fill(buf, (byte)0x00); if(isLastFrame) { buf[0] = (byte) 0x20; buf[1] = (byte) 0x80; } else { buf[0] = (byte) 0x1D; buf[1] = (byte) 0x80; } buf[2] = 'D'; buf[3] = 'S'; buf[4] = 'V'; buf[5] = 'T'; buf[6] = (byte) 0x20; buf[7] = (byte) 0x00; buf[8] = (byte) 0x00; buf[9] = (byte) 0x00; buf[10] = (byte) 0x20; buf[11] = packet.getBackBone().getDestinationRepeaterID(); buf[12] = packet.getBackBone().getSendRepeaterID(); buf[13] = packet.getBackBone().getSendTerminalID(); buf[14] = packet.getBackBone().getFrameID()[0]; buf[15] = packet.getBackBone().getFrameID()[1]; buf[16] = packet.getBackBone().getSequenceNumber(); if(isLastFrame) { ArrayUtil.copyOfRange(buf, 17, DSTARDefines.VoiceSegmentLastBytesICOM); ArrayUtil.copyOfRange(buf, 26, DSTARDefines.LastPatternBytesICOM); } else { ArrayUtil.copyOfRange(buf, 17, packet.getVoiceData().getVoiceSegment()); ArrayUtil.copyOfRange(buf, 26, packet.getVoiceData().getDataSegment()); } return Optional.of(buf); } }
23.740026
103
0.679334
f6f267430d7a2054f0ec66eb95d4cf184c942ec7
1,162
package com.bookstore.service; import com.bookstore.entity.Author; import com.bookstore.repository.AuthorRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service public class InsertFirstAuthorService { private final AuthorRepository authorRepository; private final InsertSecondAuthorService insertSecondAuthorService; public InsertFirstAuthorService(AuthorRepository authorRepository, InsertSecondAuthorService insertSecondAuthorService) { this.authorRepository = authorRepository; this.insertSecondAuthorService = insertSecondAuthorService; } @Transactional(propagation = Propagation.REQUIRED) public void insertFirstAuthor() { Author author = new Author(); author.setName("Joana Nimar"); authorRepository.saveAndFlush(author); // I even flush the insert! try { insertSecondAuthorService.insertSecondAuthor(); } catch (RuntimeException e) { System.err.println("Exception: " + e); } } }
32.277778
74
0.745267
2b443d0506cfffc7bc1595ce2c4432dfa8b5bd7e
2,641
/* * 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.glaf.core.util; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class HttpQueryUtils { protected final static Log logger = LogFactory.getLog(HttpQueryUtils.class); protected static Boolean getBooleanValue(HttpServletRequest request, String name) { String value = request.getParameter(name); if (request.getAttribute(name) != null) { value = (String) request.getAttribute(name); } if (StringUtils.equalsIgnoreCase(value, "true")) { return true; } return false; } protected static Object getObjectValue(HttpServletRequest request, String name) { Object value = getParameter(request, name); if (request.getAttribute(name) != null) { value = request.getAttribute(name); } return value; } public static String getParameter(HttpServletRequest request, String name) { String value = request.getParameter(name); if (StringUtils.isEmpty(value)) { String[] values = request.getParameterValues(name); if (values != null && values.length > 0) { StringBuilder buff = new StringBuilder(1000); for (int i = 0; i < values.length; i++) { if (i < values.length - 1) { if (StringUtils.isNotEmpty(values[i])) { buff.append(values[i]).append(','); } } else { if (StringUtils.isNotEmpty(values[i])) { buff.append(values[i]); } } } if (StringUtils.isNotEmpty(buff.toString())) { value = buff.toString(); } } } return value; } protected static String getStringValue(HttpServletRequest request, String name) { String value = getParameter(request, name); if (request.getAttribute(name) != null) { value = (String) request.getAttribute(name); } return value; } }
32.207317
84
0.710716
8071a71aeb4b4eca4ee7955cc17350cec182e76b
2,292
package org.synyx.urlaubsverwaltung.dev; import org.junit.Assert; import org.junit.Test; import org.synyx.urlaubsverwaltung.core.person.Role; /** * Unit test for {@link TestUser}. * * @author Aljona Murygina - murygina@synyx.de */ public class TestUserTest { @Test public void ensureReturnsCorrectRolesForTestUser() { Role[] roles = TestUser.USER.getRoles(); Assert.assertNotNull("Should not be null", roles); Assert.assertEquals("Wrong number of roles", 1, roles.length); Assert.assertEquals("Wrong role", Role.USER, roles[0]); } @Test public void ensureReturnsCorrectRolesForTestDepartmentHead() { Role[] roles = TestUser.DEPARTMENT_HEAD.getRoles(); Assert.assertNotNull("Should not be null", roles); Assert.assertEquals("Wrong number of roles", 2, roles.length); Assert.assertEquals("Wrong role", Role.USER, roles[0]); Assert.assertEquals("Wrong role", Role.DEPARTMENT_HEAD, roles[1]); } @Test public void ensureReturnsCorrectRolesForTestDepartmentHeadSecondStageAuthority() { Role[] roles = TestUser.SECOND_STAGE_AUTHORITY.getRoles(); Assert.assertNotNull("Should not be null", roles); Assert.assertEquals("Wrong number of roles", 2, roles.length); Assert.assertEquals("Wrong role", Role.USER, roles[0]); Assert.assertEquals("Wrong role", Role.SECOND_STAGE_AUTHORITY, roles[1]); } @Test public void ensureReturnsCorrectRolesForTestBoss() { Role[] roles = TestUser.BOSS.getRoles(); Assert.assertNotNull("Should not be null", roles); Assert.assertEquals("Wrong number of roles", 2, roles.length); Assert.assertEquals("Wrong role", Role.USER, roles[0]); Assert.assertEquals("Wrong role", Role.BOSS, roles[1]); } @Test public void ensureReturnsCorrectRolesForTestOffice() { Role[] roles = TestUser.OFFICE.getRoles(); Assert.assertNotNull("Should not be null", roles); Assert.assertEquals("Wrong number of roles", 3, roles.length); Assert.assertEquals("Wrong role", Role.USER, roles[0]); Assert.assertEquals("Wrong role", Role.BOSS, roles[1]); Assert.assertEquals("Wrong role", Role.OFFICE, roles[2]); } }
30.972973
86
0.673211
ac1b6b0ed2b9aef205258f2bf00b37feda1ab038
15,191
package zj.base.dao; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.transform.Transformers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import zj.base.common.Pager; import zj.base.common.QueryCondition; import zj.base.common.SystemContext; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.math.BigInteger; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; /** * @author lzj 2014/08/19 */ @SuppressWarnings("unchecked") @Repository("baseDao") public class BaseDao<T, ID extends Serializable> implements IBaseDao<T, ID> { /** * Dao只做关于数据库的处理 */ @Autowired private SessionFactory sessionFactory; /** * 创建一个Class的对象来获取泛型的class */ private Class<?> clz; public Class<?> getClz() { if (clz == null) { // 获取泛型的Class对象 clz = ((Class<?>) (((ParameterizedType) (this.getClass().getGenericSuperclass())) .getActualTypeArguments()[0])); } return clz; } protected Session getSession() { return sessionFactory.getCurrentSession(); } @Override public void flush() { getSession().flush(); } @Override public void clear() { getSession().clear(); } @Override public Long getTotalCount() { StringBuilder sb = new StringBuilder(); sb.append("select count(*) from ").append(getClz().getName()); return (Long) queryObject(sb); } @Override public T save(T t) { getSession().save(t); return t; } @Override public void update(T t) { getSession().update(t); } @Override public void delete(ID id) { getSession().delete(this.load(id)); } @Override public void delete(T entity) { getSession().delete(entity); } @Override public int delete(ID[] ids) { StringBuilder sb = new StringBuilder(); sb.append("delete ").append(getClz().getName()).append(" o where o.id in ?1"); return updateByHql(sb, ids); } @Override public T load(ID id) { return (T) getSession().load(getClz(), id); } @Override public List<T> load(ID[] ids) { StringBuilder sb = new StringBuilder(); sb.append("from ").append(getClz().getName()).append("o where o.id in :ids"); return getSession().createQuery(sb.toString()).setParameter("ids", ids).list(); } @Override public T get(ID id) { return (T) getSession().get(getClz(), id); } @Override public T loadByParam(String propertyName, Object value) { StringBuilder sb = new StringBuilder(); sb.append("from ").append(getClz().getName()).append("o where o.").append(propertyName).append("= ?1"); return (T) queryObject(sb, value); } @Override public List<T> listByParam(String propertyName, Object value) { StringBuilder sb = new StringBuilder(); sb.append("from ").append(getClz().getName()).append("o where o.").append(propertyName).append("= ?1 order by createDate"); return list(sb, value); } @Override public List<T> listAll() { StringBuilder sb = new StringBuilder(); sb.append("from ").append(getClz().getName()); return list(sb); } @Override public Pager<T> findAll() { StringBuilder sb = new StringBuilder(); sb.append("from ").append(getClz().getName()); return find(sb); } // *******************list列表对象不分页 +别名和查询参数的查询 开始******** // 初始化排序 private StringBuilder initSort(StringBuilder hql) { String order = SystemContext.getOrder(); String sort = SystemContext.getSort(); if (sort != null && !sort.isEmpty()) { hql.append(" order by ").append(sort); if (!"desc".equals(order)) hql.append(" asc"); else hql.append(" desc"); } return hql; } /** * 多条件不分页查询 */ @Override public List<T> listByConditions(List<QueryCondition> conditions) { StringBuilder hql = new StringBuilder(); hql.append("from ").append(getClz().getName()).append(" o where"); for (QueryCondition con : conditions) { hql.append(" o.").append(con.getKey()).append(con.getOperator()).append(":").append(con.getKey()).append(" ").append(con.getLogicOperator()); } hql = initSort(hql); Query query = getSession().createQuery(hql.toString()); setConditionParameter(query, conditions); return query.setCacheable(true).list(); } @Override public Pager<T> findByConditions(List<QueryCondition> conditions) { StringBuilder hql = new StringBuilder(); hql.append("from ").append(getClz().getName()).append(" o where 1=1 and"); for (QueryCondition con : conditions) { hql.append(" o.").append(con.getKey()).append(" ").append(con.getOperator()).append(":").append(con.getKey()).append(" ").append(con.getLogicOperator()); } hql = initSort(hql); String cq = getCountHql(hql, true); Query cquery = getSession().createQuery(cq); Query query = getSession().createQuery(hql.toString()); // 设置别名参数 setConditionParameter(query, conditions); setConditionParameter(cquery, conditions); // 设置分页量化数据 Pager<T> pages = new Pager<>(); setPagers(query, pages); List<T> datas = query.setCacheable(true).list(); pages.setRows(datas); long total = (Long) cquery.uniqueResult(); pages.setTotal(total); return pages; } // 设置有多条件查询的值 private void setConditionParameter(Query query, List<QueryCondition> conditions) { for (QueryCondition con : conditions) { query.setParameter(con.getKey(), con.getValue()); } } // 设置有别名的查询参数和多条件查询 用(:xxx) @SuppressWarnings("rawtypes") private void setAliasParameter(Query query, Map<String, Object> collection) { if (collection != null) { Set<String> keys = collection.keySet(); for (String key : keys) { Object val = collection.get(key); if (val instanceof Collection) { // 查询条件是列表 query.setParameterList(key, (Collection) val); } else { query.setParameter(key, val); } } } } // 设置查询用(?)参数 private void setParameter(Query query, Object[] args) { if (args != null && args.length > 0) { StringBuilder sb; for (int i = 0; i < args.length; i++) { sb = new StringBuilder(); if (i == 0) { query.setParameter(sb.append(i + 1).toString(), args[i]); } else { query.setParameter(sb.append(i).toString(), args[i]); } } } } public List<T> list(StringBuilder hql, Object[] args) { return this.list(hql, args, null); } public List<T> list(StringBuilder hql, Object arg) { return this.list(hql, new Object[]{arg}); } public List<T> list(StringBuilder hql) { return this.list(hql, null); } public List<T> list(StringBuilder hql, Object[] args, Map<String, Object> alias) { hql = initSort(hql); Query query = getSession().createQuery(hql.toString()); setAliasParameter(query, alias); setParameter(query, args); return query.setCacheable(true).list(); } public List<T> listByAlias(StringBuilder hql, Map<String, Object> alias) { return this.list(hql, null, alias); } // *******************list列表对象不分页 +别名和查询参数的查询 结束******** // *****************************分页查询开始****************** // 设置分页对象,初始化pageSize为10 @SuppressWarnings("rawtypes") private void setPagers(Query query, Pager pages) { Integer pageSize = SystemContext.getPageSize(); Integer pageOffset = SystemContext.getPageOffset(); if (pageOffset == null || pageOffset < 0) pageOffset = 0; if (pageSize == null || pageSize < 0) pageSize = 10; pages.setOffset(pageOffset); pages.setSize(pageSize); query.setFirstResult(pageOffset).setMaxResults(pageSize); } // 使用Count()函数的查询 private String getCountHql(StringBuilder hql, boolean isHql) { // 截取从from字符开始到最后的子串 String e = hql.substring(hql.indexOf("from")); String c = "select count(*) " + e; // 不要fetch if (isHql) c = c.replace("fetch", ""); return c; } public Pager<T> find(StringBuilder hql, Object[] args) { return this.find(hql, args, null); } public Pager<T> find(StringBuilder hql, Object arg) { return this.find(hql, new Object[]{arg}); } public Pager<T> find(StringBuilder hql) { return this.find(hql, null); } public Pager<T> find(StringBuilder hql, Object[] args, Map<String, Object> alias) { hql = initSort(hql); String cq = getCountHql(hql, true); Query cquery = getSession().createQuery(cq); Query query = getSession().createQuery(hql.toString()); // 设置别名参数 setAliasParameter(query, alias); setAliasParameter(cquery, alias); // 设置参数 setParameter(query, args); setParameter(cquery, args); // 设置分页量化数据 Pager<T> pages = new Pager<>(); setPagers(query, pages); List<T> datas = query.setCacheable(true).list(); pages.setRows(datas); long total = (Long) cquery.uniqueResult(); pages.setTotal(total); return pages; } public Pager<T> findByAlias(StringBuilder hql, Map<String, Object> alias) { return this.find(hql, null, alias); } // *****************************分页查询完毕****************** // ******************查询单个对象开始*************************** public Object queryObject(StringBuilder hql, Object[] args, Map<String, Object> alias) { Query query = getSession().createQuery(hql.toString()); setAliasParameter(query, alias); setParameter(query, args); return query.uniqueResult(); } public Object queryObjectByAlias(StringBuilder hql, Map<String, Object> alias) { return this.queryObject(hql, null, alias); } public Object queryObject(StringBuilder hql, Object[] args) { return this.queryObject(hql, args, null); } public Object queryObject(StringBuilder hql, Object arg) { return this.queryObject(hql, new Object[]{arg}); } public Object queryObject(StringBuilder hql) { return this.queryObject(hql, null); } // ******************查询单个对象完毕*************************** // *********************更新对象开始******************* public int updateByHql(StringBuilder hql, Object[] args) { Query query = getSession().createQuery(hql.toString()); setParameter(query, args); return query.executeUpdate(); } public int updateByHql(StringBuilder hql, Object arg) { return this.updateByHql(hql, new Object[]{arg}); } public int updateByHql(StringBuilder hql) { return this.updateByHql(hql, null); } // *********************更新对象完毕******************* // ******************原生sql开始******************** public <N> List<N> listBySql(StringBuilder sql, Object[] args, Class<?> clz, boolean hasEntity) { return this.listBySql(sql, args, null, clz, hasEntity); } public <N> List<N> listBySql(StringBuilder sql, Object arg, Class<?> clz, boolean hasEntity) { return this.listBySql(sql, new Object[]{arg}, clz, hasEntity); } public <N> List<N> listBySql(StringBuilder sql, Class<?> clz, boolean hasEntity) { return this.listBySql(sql, null, clz, hasEntity); } public <N> List<N> listBySql(StringBuilder sql, Object[] args, Map<String, Object> alias, Class<?> clz, boolean hasEntity) { sql = initSort(sql); SQLQuery sq = getSession().createSQLQuery(sql.toString()); setAliasParameter(sq, alias); setParameter(sq, args); if (hasEntity) { sq.addEntity(clz); } else sq.setResultTransformer(Transformers.aliasToBean(clz)); return sq.list(); } public <N> List<N> listByAliasSql(StringBuilder sql, Map<String, Object> alias, Class<?> clz, boolean hasEntity) { return this.listBySql(sql, null, alias, clz, hasEntity); } // ************************不分页原生sql结束********************** // **************分页原生sql开始 ********************** public <N> Pager<N> findBySql(StringBuilder sql, Object[] args, Class<?> clz, boolean hasEntity) { return this.findBySql(sql, args, null, clz, hasEntity); } public <N> Pager<N> findBySql(StringBuilder sql, Object arg, Class<?> clz, boolean hasEntity) { return this.findBySql(sql, new Object[]{arg}, clz, hasEntity); } public <N> Pager<N> findBySql(StringBuilder sql, Class<?> clz, boolean hasEntity) { return this.findBySql(sql, null, clz, hasEntity); } public <N> Pager<N> findBySql(StringBuilder sql, Object[] args, Map<String, Object> alias, Class<?> clz, boolean hasEntity) { sql = initSort(sql); String cq = getCountHql(sql, false); SQLQuery sq = getSession().createSQLQuery(sql.toString()); SQLQuery cquery = getSession().createSQLQuery(cq); setAliasParameter(sq, alias); setAliasParameter(cquery, alias); setParameter(sq, args); setParameter(cquery, args); Pager<N> pages = new Pager<>(); setPagers(sq, pages); if (hasEntity) { sq.addEntity(clz); } else { sq.setResultTransformer(Transformers.aliasToBean(clz)); } List<N> datas = sq.list(); pages.setRows(datas); long total = ((BigInteger) cquery.uniqueResult()).longValue(); pages.setTotal(total); return pages; } public <N> Pager<N> findByAliasSql(StringBuilder sql, Map<String, Object> alias, Class<?> clz, boolean hasEntity) { return this.findBySql(sql, null, alias, clz, hasEntity); } @Override public boolean isExist(String propertyName, Object value) { T object = get(propertyName, value); return (object != null); } @Override public T get(String propertyName, Object value) { String hql = "from " + getClz().getName() + " as model where model." + propertyName + " = ?"; return (T) getSession().createQuery(hql).setParameter(0, value).uniqueResult(); } // **************分页原生sql结束 ************************* }
32.880952
165
0.576855
78c9c289a712d05532c9cb8583f86ca280f1eb84
3,916
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; 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. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ package org.apache.ignite.internal; import java.util.Collections; import java.util.HashMap; import java.util.IllegalFormatException; import java.util.Map; /** * Set of classes represented as prefix tree. * {@code *} symbol is allowed and indicates that all packages and classes are included. */ public class ClassSet { /** Corresponds to {@code *} symbol. */ private static final Map<String, Node> ALL = Collections.emptyMap(); /** Root. */ private Node root = new Node(); /** * Adds class name to the set. * * @param clsName Class name. */ public void add(String clsName) { String[] tokens = clsName.split("\\."); Node cur = root; for (int i = 0; i < tokens.length; i++) { if (cur.children == ALL) return; if (tokens[i].equals("*")) { if (i != tokens.length - 1) throw new IllegalArgumentException("Incorrect class name format."); cur.children = ALL; return; } if (cur.children == null) cur.children = new HashMap<>(); Node n = cur.children.get(tokens[i]); if (n == null) { n = new Node(); cur.children.put(tokens[i], n); } cur = n; } } /** * @param clsName Class name. */ public boolean contains(String clsName) { String[] tokens = clsName.split("\\."); Node cur = root; for (int i = 0; i < tokens.length; i++) { if (cur.children == ALL) return true; if (cur.children == null) return false; Node n = cur.children.get(tokens[i]); if (n == null) return false; if (i == tokens.length - 1) return true; cur = n; } return false; } /** */ private static class Node { /** Children. */ private Map<String, Node> children; } }
31.079365
101
0.613126
607e7862670f4b2f31d79b77788e8cc1a7f6ab5e
204
package calisthenics.wrapprimitives; /** * Created by thaodang on 19/8/15. */ public class Spear implements Weapon { @Override public void use() { System.out.print("Throwing"); } }
17
38
0.647059
222cba4fcab1045a9ae7a5f1bc7d4c8a9ef32f09
2,147
package com.gentics.madl.type; import static com.gentics.mesh.madl.type.VertexTypeDefinition.vertexType; import java.util.stream.Stream; import com.gentics.mesh.madl.frame.VertexFrame; import com.gentics.mesh.madl.type.ElementTypeDefinition; import com.gentics.mesh.madl.type.impl.EdgeTypeDefinitionImpl.EdgeTypeDefinitionBuilder; import com.gentics.mesh.madl.type.impl.VertexTypeDefinitionImpl.VertexTypeDefinitionBuilder; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; public interface TypeHandler { default void createType(VertexTypeDefinitionBuilder builder) { createType(builder.build()); } default void createType(EdgeTypeDefinitionBuilder builder) { createType(builder.build()); } void createType(ElementTypeDefinition def); /** * Create a new vertex type for the given vertex class type. * * @param clazzOfVertex * @param superClazzOfVertex * Super vertex type. If null "V" will be used. */ default void createVertexType(Class<?> clazz, Class<?> superClazz) { createType(vertexType(clazz, superClazz)); } /** * Change the element type. * * @param vertex * @param newType * @param tx * @return */ Vertex changeType(Vertex vertex, String newType, Graph tx); /** * Create a new vertex type. * * @param clazzOfVertex * @param superClazzOfVertex * Super vertex type. If null "V" will be used. */ void addVertexType(String clazzOfVertex, String superClazzOfVertex); /** * Remove the vertex type with the given name. * * @param string */ @Deprecated void removeVertexType(String typeName); /** * Remove the edge type with the given name. * * @param typeName */ @Deprecated void removeEdgeType(String typeName); /** * Update the vertex type for the given element using the class type. * * @param element * @param classOfVertex */ void setVertexType(Element element, Class<?> classOfVertex); <T extends VertexFrame> long count(Class<? extends T> persistanceClass); <T extends VertexFrame> Stream<T> findAll(Class<? extends T> classOfT); }
24.965116
92
0.730787
ced49e2fa4b5702a52f1b00b2de4f2ef9fbbeda5
24,430
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.locator; import com.google.common.base.Predicates; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import org.apache.cassandra.dht.Murmur3Partitioner; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.locator.ReplicaCollection.Builder.Conflict; import org.apache.cassandra.utils.FBUtilities; import org.junit.Assert; import org.junit.Test; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.AbstractMap; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import static com.google.common.collect.Iterables.*; import static com.google.common.collect.Iterables.filter; import static org.apache.cassandra.locator.Replica.fullReplica; import static org.apache.cassandra.locator.Replica.transientReplica; public class ReplicaCollectionTest { static final InetAddressAndPort EP1, EP2, EP3, EP4, EP5, BROADCAST_EP, NULL_EP; static final Range<Token> R1, R2, R3, R4, R5, BROADCAST_RANGE, NULL_RANGE; static final List<InetAddressAndPort> ALL_EP; static final List<Range<Token>> ALL_R; static { try { EP1 = InetAddressAndPort.getByName("127.0.0.1"); EP2 = InetAddressAndPort.getByName("127.0.0.2"); EP3 = InetAddressAndPort.getByName("127.0.0.3"); EP4 = InetAddressAndPort.getByName("127.0.0.4"); EP5 = InetAddressAndPort.getByName("127.0.0.5"); BROADCAST_EP = FBUtilities.getBroadcastAddressAndPort(); NULL_EP = InetAddressAndPort.getByName("127.255.255.255"); R1 = range(0, 1); R2 = range(1, 2); R3 = range(2, 3); R4 = range(3, 4); R5 = range(4, 0); BROADCAST_RANGE = range(10, 11); NULL_RANGE = range(10000, 10001); ALL_EP = ImmutableList.of(EP1, EP2, EP3, EP4, EP5, BROADCAST_EP); ALL_R = ImmutableList.of(R1, R2, R3, R4, R5, BROADCAST_RANGE); } catch (UnknownHostException e) { throw new RuntimeException(e); } } static Token tk(long t) { return new Murmur3Partitioner.LongToken(t); } static Range<Token> range(long left, long right) { return new Range<>(tk(left), tk(right)); } static class TestCase<C extends AbstractReplicaCollection<C>> { final boolean isBuilder; final C test; final List<Replica> canonicalList; final Multimap<InetAddressAndPort, Replica> canonicalByEndpoint; final Multimap<Range<Token>, Replica> canonicalByRange; TestCase(boolean isBuilder, C test, List<Replica> canonicalList) { this.isBuilder = isBuilder; this.test = test; this.canonicalList = canonicalList; this.canonicalByEndpoint = HashMultimap.create(); this.canonicalByRange = HashMultimap.create(); for (Replica replica : canonicalList) canonicalByEndpoint.put(replica.endpoint(), replica); for (Replica replica : canonicalList) canonicalByRange.put(replica.range(), replica); if (isBuilder) Assert.assertTrue(test instanceof ReplicaCollection.Builder<?>); } void testSize() { Assert.assertEquals(canonicalList.size(), test.size()); } void testEquals() { Assert.assertTrue(elementsEqual(canonicalList, test)); } void testEndpoints() { // TODO: we should do more exhaustive tests of the collection Assert.assertEquals(ImmutableSet.copyOf(canonicalByEndpoint.keySet()), ImmutableSet.copyOf(test.endpoints())); try { test.endpoints().add(EP5); Assert.fail(); } catch (UnsupportedOperationException e) {} try { test.endpoints().remove(EP5); Assert.fail(); } catch (UnsupportedOperationException e) {} Assert.assertTrue(test.endpoints().containsAll(canonicalByEndpoint.keySet())); for (InetAddressAndPort ep : canonicalByEndpoint.keySet()) Assert.assertTrue(test.endpoints().contains(ep)); for (InetAddressAndPort ep : ALL_EP) if (!canonicalByEndpoint.containsKey(ep)) Assert.assertFalse(test.endpoints().contains(ep)); } public void testOrderOfIteration() { Assert.assertEquals(canonicalList, ImmutableList.copyOf(test)); Assert.assertEquals(canonicalList, test.stream().collect(Collectors.toList())); Assert.assertTrue(Iterables.elementsEqual(new LinkedHashSet<>(Lists.transform(canonicalList, Replica::endpoint)), test.endpoints())); } private void assertSubList(C subCollection, int from, int to) { if (from == to) { Assert.assertTrue(subCollection.isEmpty()); } else { AbstractReplicaCollection.ReplicaList subList = this.test.list.subList(from, to); if (!isBuilder) Assert.assertSame(subList.contents, subCollection.list.contents); Assert.assertEquals(subList, subCollection.list); } } private void assertSubSequence(Iterable<Replica> subSequence, int from, int to) { AbstractReplicaCollection.ReplicaList subList = this.test.list.subList(from, to); if (!elementsEqual(subList, subSequence)) { elementsEqual(subList, subSequence); } Assert.assertTrue(elementsEqual(subList, subSequence)); } void testSubList(int subListDepth, int filterDepth, int sortDepth) { if (!isBuilder) Assert.assertSame(test, test.subList(0, test.size())); if (test.isEmpty()) return; Assert.assertSame(test.list.contents, test.subList(0, 1).list.contents); TestCase<C> skipFront = new TestCase<>(false, test.subList(1, test.size()), canonicalList.subList(1, canonicalList.size())); assertSubList(skipFront.test, 1, canonicalList.size()); skipFront.testAll(subListDepth - 1, filterDepth, sortDepth); TestCase<C> skipBack = new TestCase<>(false, test.subList(0, test.size() - 1), canonicalList.subList(0, canonicalList.size() - 1)); assertSubList(skipBack.test, 0, canonicalList.size() - 1); skipBack.testAll(subListDepth - 1, filterDepth, sortDepth); } void testFilter(int subListDepth, int filterDepth, int sortDepth) { if (!isBuilder) Assert.assertSame(test, test.filter(Predicates.alwaysTrue())); if (test.isEmpty()) return; // remove start // we recurse on the same subset in testSubList, so just corroborate we have the correct list here { Predicate<Replica> removeFirst = r -> !r.equals(canonicalList.get(0)); assertSubList(test.filter(removeFirst), 1, canonicalList.size()); assertSubList(test.filter(removeFirst, 1), 1, Math.min(canonicalList.size(), 2)); assertSubSequence(test.filterLazily(removeFirst), 1, canonicalList.size()); assertSubSequence(test.filterLazily(removeFirst, 1), 1, Math.min(canonicalList.size(), 2)); } if (test.size() <= 1) return; // remove end // we recurse on the same subset in testSubList, so just corroborate we have the correct list here { int last = canonicalList.size() - 1; Predicate<Replica> removeLast = r -> !r.equals(canonicalList.get(last)); assertSubList(test.filter(removeLast), 0, last); assertSubSequence(test.filterLazily(removeLast), 0, last); } if (test.size() <= 2) return; Predicate<Replica> removeMiddle = r -> !r.equals(canonicalList.get(canonicalList.size() / 2)); TestCase<C> filtered = new TestCase<>(false, test.filter(removeMiddle), ImmutableList.copyOf(filter(canonicalList, removeMiddle::test))); filtered.testAll(subListDepth, filterDepth - 1, sortDepth); Assert.assertTrue(elementsEqual(filtered.canonicalList, test.filterLazily(removeMiddle, Integer.MAX_VALUE))); Assert.assertTrue(elementsEqual(limit(filter(canonicalList, removeMiddle::test), canonicalList.size() - 2), test.filterLazily(removeMiddle, canonicalList.size() - 2))); } void testCount() { Assert.assertEquals(0, test.count(Predicates.alwaysFalse())); if (test.isEmpty()) { Assert.assertEquals(0, test.count(Predicates.alwaysTrue())); return; } for (int i = 0 ; i < canonicalList.size() ; ++i) { Replica discount = canonicalList.get(i); Assert.assertEquals(canonicalList.size() - 1, test.count(r -> !r.equals(discount))); } } void testContains() { for (Replica replica : canonicalList) Assert.assertTrue(test.contains(replica)); Assert.assertFalse(test.contains(fullReplica(NULL_EP, NULL_RANGE))); } void testGet() { for (int i = 0 ; i < canonicalList.size() ; ++i) Assert.assertEquals(canonicalList.get(i), test.get(i)); } void testSort(int subListDepth, int filterDepth, int sortDepth) { final Comparator<Replica> comparator = (o1, o2) -> { boolean f1 = o1.equals(canonicalList.get(0)); boolean f2 = o2.equals(canonicalList.get(0)); return f1 == f2 ? 0 : f1 ? 1 : -1; }; TestCase<C> sorted = new TestCase<>(false, test.sorted(comparator), ImmutableList.sortedCopyOf(comparator, canonicalList)); sorted.testAll(subListDepth, filterDepth, sortDepth - 1); } void testAll(int subListDepth, int filterDepth, int sortDepth) { testEndpoints(); testOrderOfIteration(); testContains(); testGet(); testEquals(); testSize(); testCount(); if (subListDepth > 0) testSubList(subListDepth, filterDepth, sortDepth); if (filterDepth > 0) testFilter(subListDepth, filterDepth, sortDepth); if (sortDepth > 0) testSort(subListDepth, filterDepth, sortDepth); } public void testAll() { testAll(2, 2, 2); } } static class RangesAtEndpointTestCase extends TestCase<RangesAtEndpoint> { RangesAtEndpointTestCase(boolean isBuilder, RangesAtEndpoint test, List<Replica> canonicalList) { super(isBuilder, test, canonicalList); } void testRanges() { Assert.assertEquals(ImmutableSet.copyOf(canonicalByRange.keySet()), ImmutableSet.copyOf(test.ranges())); try { test.ranges().add(R5); Assert.fail(); } catch (UnsupportedOperationException e) {} try { test.ranges().remove(R5); Assert.fail(); } catch (UnsupportedOperationException e) {} Assert.assertTrue(test.ranges().containsAll(canonicalByRange.keySet())); for (Range<Token> range : canonicalByRange.keySet()) Assert.assertTrue(test.ranges().contains(range)); for (Range<Token> range : ALL_R) if (!canonicalByRange.containsKey(range)) Assert.assertFalse(test.ranges().contains(range)); } void testByRange() { // check byEndppint() and byRange().entrySet() Assert.assertFalse(test.byRange().containsKey(EP1)); Assert.assertFalse(test.byRange().entrySet().contains(EP1)); try { test.byRange().entrySet().contains(null); Assert.fail(); } catch (NullPointerException | IllegalArgumentException e) {} try { test.byRange().containsKey(null); Assert.fail(); } catch (NullPointerException | IllegalArgumentException e) {} for (Range<Token> r : ALL_R) { if (canonicalByRange.containsKey(r)) { Assert.assertTrue(test.byRange().containsKey(r)); Assert.assertEquals(canonicalByRange.get(r), ImmutableSet.of(test.byRange().get(r))); for (Replica replica : canonicalByRange.get(r)) Assert.assertTrue(test.byRange().entrySet().contains(new AbstractMap.SimpleImmutableEntry<>(r, replica))); } else { Assert.assertFalse(test.byRange().containsKey(r)); Assert.assertFalse(test.byRange().entrySet().contains(new AbstractMap.SimpleImmutableEntry<>(r, Replica.fullReplica(EP1, r)))); } } } @Override public void testOrderOfIteration() { super.testOrderOfIteration(); Assert.assertTrue(Iterables.elementsEqual(Lists.transform(canonicalList, Replica::range), test.ranges())); Assert.assertTrue(Iterables.elementsEqual(canonicalList, test.byRange().values())); Assert.assertTrue(Iterables.elementsEqual( Lists.transform(canonicalList, r -> new AbstractMap.SimpleImmutableEntry<>(r.range(), r)), test.byRange().entrySet())); } public void testUnwrap(int subListDepth, int filterDepth, int sortDepth) { List<Replica> canonUnwrap = new ArrayList<>(); for (Replica replica : canonicalList) for (Range<Token> range : replica.range().unwrap()) canonUnwrap.add(replica.decorateSubrange(range)); RangesAtEndpoint testUnwrap = test.unwrap(); if (testUnwrap == test) { Assert.assertEquals(canonicalList, canonUnwrap); } else { new RangesAtEndpointTestCase(false, testUnwrap, canonUnwrap) .testAllExceptUnwrap(subListDepth, filterDepth, sortDepth); } } void testAllExceptUnwrap(int subListDepth, int filterDepth, int sortDepth) { super.testAll(subListDepth, filterDepth, sortDepth); testRanges(); testByRange(); } @Override void testAll(int subListDepth, int filterDepth, int sortDepth) { testAllExceptUnwrap(subListDepth, filterDepth, sortDepth); testUnwrap(subListDepth, filterDepth, sortDepth); } } static class EndpointsTestCase<E extends Endpoints<E>> extends TestCase<E> { EndpointsTestCase(boolean isBuilder, E test, List<Replica> canonicalList) { super(isBuilder, test, canonicalList); } void testByEndpoint() { // check byEndppint() and byEndpoint().entrySet() Assert.assertFalse(test.byEndpoint().containsKey(R1)); Assert.assertFalse(test.byEndpoint().entrySet().contains(EP1)); try { test.byEndpoint().entrySet().contains(null); Assert.fail(); } catch (NullPointerException | IllegalArgumentException e) {} try { test.byEndpoint().containsKey(null); Assert.fail(); } catch (NullPointerException | IllegalArgumentException e) {} for (InetAddressAndPort ep : ALL_EP) { if (canonicalByEndpoint.containsKey(ep)) { Assert.assertTrue(test.byEndpoint().containsKey(ep)); Assert.assertEquals(canonicalByEndpoint.get(ep), ImmutableSet.of(test.byEndpoint().get(ep))); for (Replica replica : canonicalByEndpoint.get(ep)) Assert.assertTrue(test.byEndpoint().entrySet().contains(new AbstractMap.SimpleImmutableEntry<>(ep, replica))); } else { Assert.assertFalse(test.byEndpoint().containsKey(ep)); Assert.assertFalse(test.byEndpoint().entrySet().contains(new AbstractMap.SimpleImmutableEntry<>(ep, Replica.fullReplica(ep, R1)))); } } } @Override public void testOrderOfIteration() { super.testOrderOfIteration(); Assert.assertTrue(Iterables.elementsEqual(canonicalList, test.byEndpoint().values())); Assert.assertTrue(Iterables.elementsEqual( Lists.transform(canonicalList, r -> new AbstractMap.SimpleImmutableEntry<>(r.endpoint(), r)), test.byEndpoint().entrySet())); } @Override void testAll(int subListDepth, int filterDepth, int sortDepth) { super.testAll(subListDepth, filterDepth, sortDepth); testByEndpoint(); } } private static final ImmutableList<Replica> RANGES_AT_ENDPOINT = ImmutableList.of( fullReplica(EP1, R1), fullReplica(EP1, R2), transientReplica(EP1, R3), fullReplica(EP1, R4), transientReplica(EP1, R5) ); @Test public void testRangesAtEndpoint() { ImmutableList<Replica> canonical = RANGES_AT_ENDPOINT; new RangesAtEndpointTestCase( false, RangesAtEndpoint.copyOf(canonical), canonical ).testAll(); } @Test public void testMutableRangesAtEndpoint() { ImmutableList<Replica> canonical1 = RANGES_AT_ENDPOINT.subList(0, RANGES_AT_ENDPOINT.size()); RangesAtEndpoint.Builder test = new RangesAtEndpoint.Builder(RANGES_AT_ENDPOINT.get(0).endpoint(), canonical1.size()); test.addAll(canonical1, Conflict.NONE); try { // incorrect range test.addAll(canonical1, Conflict.NONE); Assert.fail(); } catch (IllegalArgumentException e) { } test.addAll(canonical1, Conflict.DUPLICATE); // we ignore exact duplicates try { // invalid endpoint; always error test.add(fullReplica(EP2, BROADCAST_RANGE), Conflict.ALL); Assert.fail(); } catch (IllegalArgumentException e) { } try { // conflict on isFull/isTransient test.add(fullReplica(EP1, R3), Conflict.DUPLICATE); Assert.fail(); } catch (IllegalArgumentException e) { } test.add(fullReplica(EP1, R3), Conflict.ALL); new RangesAtEndpointTestCase(true, test, canonical1).testAll(); RangesAtEndpoint snapshot = test.subList(0, test.size()); ImmutableList<Replica> canonical2 = RANGES_AT_ENDPOINT; test.addAll(canonical2.reverse(), Conflict.DUPLICATE); new TestCase<>(false, snapshot, canonical1).testAll(); new TestCase<>(true, test, canonical2).testAll(); } private static final ImmutableList<Replica> ENDPOINTS_FOR_X = ImmutableList.of( fullReplica(EP1, R1), fullReplica(EP2, R1), transientReplica(EP3, R1), fullReplica(EP4, R1), transientReplica(EP5, R1) ); @Test public void testEndpointsForRange() { ImmutableList<Replica> canonical = ENDPOINTS_FOR_X; new EndpointsTestCase<>( false, EndpointsForRange.copyOf(canonical), canonical ).testAll(); } @Test public void testMutableEndpointsForRange() { ImmutableList<Replica> canonical1 = ENDPOINTS_FOR_X.subList(0, ENDPOINTS_FOR_X.size() - 1); EndpointsForRange.Builder test = new EndpointsForRange.Builder(R1, canonical1.size()); test.addAll(canonical1, Conflict.NONE); try { // incorrect range test.addAll(canonical1, Conflict.NONE); Assert.fail(); } catch (IllegalArgumentException e) { } test.addAll(canonical1, Conflict.DUPLICATE); // we ignore exact duplicates try { // incorrect range test.add(fullReplica(BROADCAST_EP, R2), Conflict.ALL); Assert.fail(); } catch (IllegalArgumentException e) { } try { // conflict on isFull/isTransient test.add(transientReplica(EP1, R1), Conflict.DUPLICATE); Assert.fail(); } catch (IllegalArgumentException e) { } test.add(transientReplica(EP1, R1), Conflict.ALL); new EndpointsTestCase<>(true, test, canonical1).testAll(); EndpointsForRange snapshot = test.subList(0, test.size()); ImmutableList<Replica> canonical2 = ENDPOINTS_FOR_X; test.addAll(canonical2.reverse(), Conflict.DUPLICATE); new EndpointsTestCase<>(false, snapshot, canonical1).testAll(); new EndpointsTestCase<>(true, test, canonical2).testAll(); } @Test public void testEndpointsForToken() { ImmutableList<Replica> canonical = ENDPOINTS_FOR_X; new EndpointsTestCase<>( false, EndpointsForToken.copyOf(tk(1), canonical), canonical ).testAll(); } @Test public void testMutableEndpointsForToken() { ImmutableList<Replica> canonical1 = ENDPOINTS_FOR_X.subList(0, ENDPOINTS_FOR_X.size() - 1); EndpointsForToken.Builder test = new EndpointsForToken.Builder(tk(1), canonical1.size()); test.addAll(canonical1, Conflict.NONE); try { // incorrect range test.addAll(canonical1, Conflict.NONE); Assert.fail(); } catch (IllegalArgumentException e) { } test.addAll(canonical1, Conflict.DUPLICATE); // we ignore exact duplicates try { // incorrect range test.add(fullReplica(BROADCAST_EP, R2), Conflict.ALL); Assert.fail(); } catch (IllegalArgumentException e) { } try { // conflict on isFull/isTransient test.add(transientReplica(EP1, R1), Conflict.DUPLICATE); Assert.fail(); } catch (IllegalArgumentException e) { } test.add(transientReplica(EP1, R1), Conflict.ALL); new EndpointsTestCase<>(true, test, canonical1).testAll(); EndpointsForToken snapshot = test.subList(0, test.size()); ImmutableList<Replica> canonical2 = ENDPOINTS_FOR_X; test.addAll(canonical2.reverse(), Conflict.DUPLICATE); new EndpointsTestCase<>(false, snapshot, canonical1).testAll(); new EndpointsTestCase<>(true, test, canonical2).testAll(); } }
39.853181
180
0.600573
b5b8d6c56da29eb710bae62e65eec2a104311bea
43,509
/* * 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.codehaus.groovy.antlr.treewalker; import org.codehaus.groovy.antlr.GroovySourceAST; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * A composite of many visitors. Any call to a method from Visitor * will invoke each visitor in turn, and reverse the invocation * order on a closing visit. * i.e. * with the list of visitors = [a,b,c] * composite.visitDefault() would... * call on the opening visit - a.visitDefault() then b.visitDefault() then c.visitDefault() * call on the closing visit - c.visitDefault() then b.visitDefault() then a.visitDefault() */ public class CompositeVisitor implements Visitor{ final List visitors; final List backToFrontVisitors; /** * A composite of the supplied list of antlr AST visitors. * @param visitors a List of implementations of the Visitor interface */ public CompositeVisitor(List visitors) { this.visitors = visitors; backToFrontVisitors = new ArrayList(); backToFrontVisitors.addAll(visitors); Collections.reverse(backToFrontVisitors); } private Iterator itr(int visit) { Iterator itr=visitors.iterator(); if (visit == CLOSING_VISIT) { itr = backToFrontVisitors.iterator(); } return itr; } public void setUp() { for (Object visitor : visitors) { ((Visitor) visitor).setUp(); } } public void visitAbstract(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAbstract(t,visit);} } public void visitAnnotation(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotation(t,visit);} } public void visitAnnotations(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotations(t,visit);} } public void visitAnnotationArrayInit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotationArrayInit(t,visit);} } public void visitAnnotationDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotationDef(t,visit);} } public void visitAnnotationFieldDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotationFieldDef(t,visit);} } public void visitAnnotationMemberValuePair(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAnnotationMemberValuePair(t,visit);} } public void visitArrayDeclarator(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitArrayDeclarator(t,visit);} } public void visitAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAssign(t,visit);} } public void visitAt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitAt(t,visit);} } public void visitBand(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBand(t,visit);} } public void visitBandAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBandAssign(t,visit);} } public void visitBigSuffix(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBigSuffix(t,visit);} } public void visitBlock(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBlock(t,visit);} } public void visitBnot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBnot(t,visit);} } public void visitBor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBor(t,visit);} } public void visitBorAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBorAssign(t,visit);} } public void visitBsr(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBsr(t,visit);} } public void visitBsrAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBsrAssign(t,visit);} } public void visitBxor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBxor(t,visit);} } public void visitBxorAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitBxorAssign(t,visit);} } public void visitCaseGroup(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitCaseGroup(t,visit);} } public void visitClassDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitClassDef(t,visit);} } public void visitClosedBlock(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitClosedBlock(t,visit);} } public void visitClosureList(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitClosureList(t,visit);} } public void visitClosureOp(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitClosureOp(t,visit);} } public void visitColon(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitColon(t,visit);} } public void visitComma(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitComma(t,visit);} } public void visitCompareTo(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitCompareTo(t,visit);} } public void visitCtorCall(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitCtorCall(t,visit);} } public void visitCtorIdent(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitCtorIdent(t,visit);} } public void visitDec(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDec(t,visit);} } public void visitDigit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDigit(t,visit);} } public void visitDiv(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDiv(t,visit);} } public void visitDivAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDivAssign(t,visit);} } public void visitDollar(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDollar(t,visit);} } public void visitDot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDot(t,visit);} } public void visitDynamicMember(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDynamicMember(t,visit);} } public void visitElist(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitElist(t,visit);} } public void visitEmptyStat(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEmptyStat(t,visit);} } public void visitEnumConstantDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEnumConstantDef(t,visit);} } public void visitEnumDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEnumDef(t,visit);} } public void visitEof(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEof(t,visit);} } public void visitEqual(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEqual(t,visit);} } public void visitEsc(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitEsc(t,visit);} } public void visitExponent(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitExponent(t,visit);} } public void visitExpr(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitExpr(t,visit);} } public void visitExtendsClause(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitExtendsClause(t,visit);} } public void visitFinal(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitFinal(t,visit);} } public void visitFloatSuffix(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitFloatSuffix(t,visit);} } public void visitForCondition(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForCondition(t,visit);} } public void visitForEachClause(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForEachClause(t,visit);} } public void visitForInit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForInit(t,visit);} } public void visitForInIterable(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForInIterable(t,visit);} } public void visitForIterator(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitForIterator(t,visit);} } public void visitGe(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitGe(t,visit);} } public void visitGt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitGt(t,visit);} } public void visitHexDigit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitHexDigit(t,visit);} } public void visitIdent(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitIdent(t,visit);} } public void visitImplementsClause(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitImplementsClause(t,visit);} } public void visitImplicitParameters(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitImplicitParameters(t,visit);} } public void visitImport(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitImport(t,visit);} } public void visitInc(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitInc(t,visit);} } public void visitIndexOp(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitIndexOp(t,visit);} } public void visitInstanceInit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitInstanceInit(t,visit);} } public void visitInterfaceDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitInterfaceDef(t,visit);} } public void visitLabeledArg(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLabeledArg(t,visit);} } public void visitLabeledStat(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLabeledStat(t,visit);} } public void visitLand(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLand(t,visit);} } public void visitLbrack(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLbrack(t,visit);} } public void visitLcurly(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLcurly(t,visit);} } public void visitLe(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLe(t,visit);} } public void visitLetter(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLetter(t,visit);} } public void visitListConstructor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitListConstructor(t,visit);} } public void visitLiteralAs(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralAs(t,visit);} } public void visitLiteralAssert(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralAssert(t,visit);} } public void visitLiteralBoolean(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralBoolean(t,visit);} } public void visitLiteralBreak(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralBreak(t,visit);} } public void visitLiteralByte(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralByte(t,visit);} } public void visitLiteralCase(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralCase(t,visit);} } public void visitLiteralCatch(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralCatch(t,visit);} } public void visitLiteralChar(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralChar(t,visit);} } public void visitLiteralClass(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralClass(t,visit);} } public void visitLiteralContinue(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralContinue(t,visit);} } public void visitLiteralDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralDef(t,visit);} } public void visitLiteralDefault(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralDefault(t,visit);} } public void visitLiteralDouble(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralDouble(t,visit);} } public void visitLiteralElse(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralElse(t,visit);} } public void visitLiteralEnum(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralEnum(t,visit);} } public void visitLiteralExtends(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralExtends(t,visit);} } public void visitLiteralFalse(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralFalse(t,visit);} } public void visitLiteralFinally(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralFinally(t,visit);} } public void visitLiteralFloat(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralFloat(t,visit);} } public void visitLiteralFor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralFor(t,visit);} } public void visitLiteralIf(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralIf(t,visit);} } public void visitLiteralImplements(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralImplements(t,visit);} } public void visitLiteralImport(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralImport(t,visit);} } public void visitLiteralIn(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralIn(t,visit);} } public void visitLiteralInstanceof(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralInstanceof(t,visit);} } public void visitLiteralInt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralInt(t,visit);} } public void visitLiteralInterface(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralInterface(t,visit);} } public void visitLiteralLong(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralLong(t,visit);} } public void visitLiteralNative(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralNative(t,visit);} } public void visitLiteralNew(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralNew(t,visit);} } public void visitLiteralNull(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralNull(t,visit);} } public void visitLiteralPackage(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralPackage(t,visit);} } public void visitLiteralPrivate(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralPrivate(t,visit);} } public void visitLiteralProtected(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralProtected(t,visit);} } public void visitLiteralPublic(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralPublic(t,visit);} } public void visitLiteralReturn(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralReturn(t,visit);} } public void visitLiteralShort(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralShort(t,visit);} } public void visitLiteralStatic(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralStatic(t,visit);} } public void visitLiteralSuper(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralSuper(t,visit);} } public void visitLiteralSwitch(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralSwitch(t,visit);} } public void visitLiteralSynchronized(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralSynchronized(t,visit);} } public void visitLiteralThis(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralThis(t,visit);} } public void visitLiteralThreadsafe(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralThreadsafe(t,visit);} } public void visitLiteralThrow(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralThrow(t,visit);} } public void visitLiteralThrows(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralThrows(t,visit);} } public void visitLiteralTransient(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralTransient(t,visit);} } public void visitLiteralTrue(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralTrue(t,visit);} } public void visitLiteralTry(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralTry(t,visit);} } public void visitLiteralVoid(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralVoid(t,visit);} } public void visitLiteralVolatile(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralVolatile(t,visit);} } public void visitLiteralWhile(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLiteralWhile(t,visit);} } public void visitLnot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLnot(t,visit);} } public void visitLor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLor(t,visit);} } public void visitLparen(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLparen(t,visit);} } public void visitLt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitLt(t,visit);} } public void visitMapConstructor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMapConstructor(t,visit);} } public void visitMemberPointer(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMemberPointer(t,visit);} } public void visitMethodCall(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMethodCall(t,visit);} } public void visitMethodDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMethodDef(t,visit);} } public void visitMinus(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMinus(t,visit);} } public void visitMinusAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMinusAssign(t,visit);} } public void visitMlComment(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMlComment(t,visit);} } public void visitMod(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMod(t,visit);} } public void visitModifiers(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitModifiers(t,visit);} } public void visitModAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitModAssign(t,visit);} } public void visitMultiCatch(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMultiCatch(t, visit);} } public void visitMultiCatchTypes(final GroovySourceAST t, final int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitMultiCatchTypes(t, visit);} } public void visitNls(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNls(t,visit);} } public void visitNotEqual(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNotEqual(t,visit);} } public void visitNullTreeLookahead(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNullTreeLookahead(t,visit);} } public void visitNumBigDecimal(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumBigDecimal(t,visit);} } public void visitNumBigInt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumBigInt(t,visit);} } public void visitNumDouble(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumDouble(t,visit);} } public void visitNumFloat(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumFloat(t,visit);} } public void visitNumInt(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumInt(t,visit);} } public void visitNumLong(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitNumLong(t,visit);} } public void visitObjblock(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitObjblock(t,visit);} } public void visitOneNl(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitOneNl(t,visit);} } public void visitOptionalDot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitOptionalDot(t,visit);} } public void visitPackageDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPackageDef(t,visit);} } public void visitParameters(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitParameters(t,visit);} } public void visitParameterDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitParameterDef(t,visit);} } public void visitPlus(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPlus(t,visit);} } public void visitPlusAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPlusAssign(t,visit);} } public void visitPostDec(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPostDec(t,visit);} } public void visitPostInc(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitPostInc(t,visit);} } public void visitQuestion(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitQuestion(t,visit);} } public void visitRangeExclusive(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRangeExclusive(t,visit);} } public void visitRangeInclusive(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRangeInclusive(t,visit);} } public void visitRbrack(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRbrack(t,visit);} } public void visitRcurly(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRcurly(t,visit);} } public void visitRegexpCtorEnd(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexpCtorEnd(t,visit);} } public void visitRegexpLiteral(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexpLiteral(t,visit);} } public void visitRegexpSymbol(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexpSymbol(t,visit);} } public void visitRegexFind(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexFind(t,visit);} } public void visitRegexMatch(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRegexMatch(t,visit);} } public void visitRparen(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitRparen(t,visit);} } public void visitSelectSlot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSelectSlot(t,visit);} } public void visitSemi(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSemi(t,visit);} } public void visitShComment(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitShComment(t,visit);} } public void visitSl(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSl(t,visit);} } public void visitSlist(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSlist(t,visit);} } public void visitSlAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSlAssign(t,visit);} } public void visitSlComment(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSlComment(t,visit);} } public void visitSpreadArg(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSpreadArg(t,visit);} } public void visitSpreadDot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSpreadDot(t,visit);} } public void visitSpreadMapArg(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSpreadMapArg(t,visit);} } public void visitSr(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSr(t,visit);} } public void visitSrAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSrAssign(t,visit);} } public void visitStar(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStar(t,visit);} } public void visitStarAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStarAssign(t,visit);} } public void visitStarStar(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStarStar(t,visit);} } public void visitStarStarAssign(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStarStarAssign(t,visit);} } public void visitStaticImport(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStaticImport(t,visit);} } public void visitStaticInit(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStaticInit(t,visit);} } public void visitStrictfp(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStrictfp(t,visit);} } public void visitStringCh(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringCh(t,visit);} } public void visitStringConstructor(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringConstructor(t,visit);} } public void visitStringCtorEnd(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringCtorEnd(t,visit);} } public void visitStringCtorMiddle(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringCtorMiddle(t,visit);} } public void visitStringCtorStart(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringCtorStart(t,visit);} } public void visitStringLiteral(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringLiteral(t,visit);} } public void visitStringNl(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitStringNl(t,visit);} } public void visitSuperCtorCall(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitSuperCtorCall(t,visit);} } public void visitTraitDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTraitDef(t,visit);} } public void visitTripleDot(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTripleDot(t,visit);} } public void visitType(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitType(t,visit);} } public void visitTypecast(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypecast(t,visit);} } public void visitTypeArgument(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeArgument(t,visit);} } public void visitTypeArguments(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeArguments(t,visit);} } public void visitTypeLowerBounds(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeLowerBounds(t,visit);} } public void visitTypeParameter(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeParameter(t,visit);} } public void visitTypeParameters(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeParameters(t,visit);} } public void visitTypeUpperBounds(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitTypeUpperBounds(t,visit);} } public void visitUnaryMinus(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnaryMinus(t,visit);} } public void visitUnaryPlus(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnaryPlus(t,visit);} } public void visitUnusedConst(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnusedConst(t,visit);} } public void visitUnusedDo(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnusedDo(t,visit);} } public void visitUnusedGoto(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitUnusedGoto(t,visit);} } public void visitVariableDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitVariableDef(t,visit);} } public void visitVariableParameterDef(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitVariableParameterDef(t,visit);} } public void visitVocab(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitVocab(t,visit);} } public void visitWildcardType(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitWildcardType(t,visit);} } public void visitWs(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitWs(t,visit);} } public void visitDefault(GroovySourceAST t, int visit) { Iterator itr = itr(visit); while (itr.hasNext()) {((Visitor)itr.next()).visitDefault(t,visit);} } public void tearDown() { for (Object backToFrontVisitor : backToFrontVisitors) { ((Visitor) backToFrontVisitor).tearDown(); } } public void push(GroovySourceAST t) { for (Object visitor : visitors) { ((Visitor) visitor).push(t); } } public GroovySourceAST pop() { GroovySourceAST lastNodePopped = null; for (Object backToFrontVisitor : backToFrontVisitors) { lastNodePopped = ((Visitor) backToFrontVisitor).pop(); } return lastNodePopped; } }
36.809645
94
0.63642
325159f66d663717eb6bf3f408d390f70445d0f4
21,502
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.wearable.watchface.CanvasWatchFaceService; import android.support.wearable.watchface.WatchFaceStyle; import android.util.Log; import android.view.SurfaceHolder; import android.view.WindowInsets; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.DataApi; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataMapItem; import com.google.android.gms.wearable.Wearable; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; /** * Digital watch face with seconds. In ambient mode, the seconds aren't displayed. On devices with * low-bit ambient mode, the text is drawn without anti-aliasing in ambient mode. */ public class MyWatchFace extends CanvasWatchFaceService { private static final Typeface NORMAL_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL); private static final Typeface BOLD_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD); /** * Update rate in milliseconds for interactive mode. We update once a second since seconds are * displayed in interactive mode. */ private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1); /** * Handler message id for updating the time periodically in interactive mode. */ private static final int MSG_UPDATE_TIME = 0; @Override public Engine onCreateEngine() { return new Engine(); } private static class EngineHandler extends Handler { private final WeakReference<MyWatchFace.Engine> mWeakReference; public EngineHandler(MyWatchFace.Engine reference) { mWeakReference = new WeakReference<>(reference); } @Override public void handleMessage(Message msg) { MyWatchFace.Engine engine = mWeakReference.get(); if (engine != null) { switch (msg.what) { case MSG_UPDATE_TIME: engine.handleUpdateTimeMessage(); break; } } } } private class Engine extends CanvasWatchFaceService.Engine implements ConnectionCallbacks, OnConnectionFailedListener, DataApi.DataListener{ final String WEARABLE_PATH = "/wearable"; final String SUNSHINE_TEMP_HIGH_KEY = "sunshine_temp_high_key"; final String SUNSHINE_TEMP_LOW_KEY = "sunshine_temp_low_key"; final String SUNSHINE_WEATHER_ID_KEY = "sunshine_weather_id_key"; private final Handler mUpdateTimeHandler = new EngineHandler(this); private boolean mRegisteredTimeZoneReceiver = false; private Paint mBackgroundInteractivePaint; private Paint mBackgroundAmbientPaint; private Paint mTimeHourPaint; private Paint mTimeMinPaint; private Paint mTimeSecPaint; private Paint mDatePaint; private Paint mTemperatureMinPaint; private Paint mTemperatureMaxPaint; private Paint mWeatherInfoNotAvailablePaint; private Paint mLinePaint; private Rect mTextBounds=new Rect(); private Bitmap mWeatherInteractiveIcon; private Bitmap mWeatherAmbientIcon; /** * Whether the display supports fewer bits for each color in ambient mode. When true, we * disable anti-aliasing in ambient mode. */ boolean mLowBitAmbient; boolean mAmbient; final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mDateFormat.setTimeZone(TimeZone.getDefault()); mHourFormat.setTimeZone(TimeZone.getDefault()); mMinFormat.setTimeZone(TimeZone.getDefault()); invalidate(); } }; private Date mToday; private SimpleDateFormat mDateFormat; private SimpleDateFormat mHourFormat; private SimpleDateFormat mMinFormat; private String mHighTemperature; private String mLowTemperature; private String mWeatherIcon; private GoogleApiClient mGoogleApiClient; @Override public void onCreate(SurfaceHolder holder) { super.onCreate(holder); setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFace.this) .setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE) .setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE) .setShowSystemUiTime(false) .build()); Resources resources = MyWatchFace.this.getResources(); mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext()) .addApi(Wearable.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mBackgroundAmbientPaint = new Paint(); mBackgroundAmbientPaint.setColor(resources.getColor(R.color.ambient_background)); mBackgroundInteractivePaint = new Paint(); mBackgroundInteractivePaint.setColor(resources.getColor(R.color.interactive_background)); mTimeHourPaint = new Paint(); mTimeHourPaint = createBoldTextPaint(resources.getColor(R.color.interactive_primary_text)); mTimeMinPaint = new Paint(); mTimeMinPaint = createTextPaint(resources.getColor(R.color.interactive_primary_text)); mTimeSecPaint = new Paint(); mTimeSecPaint = createTextPaint(resources.getColor(R.color.interactive_primary_text)); mDatePaint = new Paint(); mDatePaint = createTextPaint(resources.getColor(R.color.interactive_secondary_text)); mTemperatureMaxPaint = new Paint(); mTemperatureMaxPaint = createBoldTextPaint(resources.getColor(R.color.interactive_primary_text)); mTemperatureMinPaint = new Paint(); mTemperatureMinPaint = createTextPaint(resources.getColor(R.color.interactive_secondary_text)); mWeatherInfoNotAvailablePaint = new Paint(); mWeatherInfoNotAvailablePaint = createTextPaint(resources.getColor(R.color.interactive_secondary_text)); mLinePaint=new Paint(); mLinePaint.setColor(getResources().getColor(R.color.interactive_secondary_text)); mLinePaint.setStrokeWidth(0.8f); mLinePaint.setAntiAlias(true); mToday=Calendar.getInstance().getTime(); mDateFormat=new SimpleDateFormat("EEE, d MMM yyyy", Locale.getDefault()); mHourFormat=new SimpleDateFormat("HH:", Locale.getDefault()); mMinFormat=new SimpleDateFormat("mm", Locale.getDefault()); mDateFormat.setTimeZone(TimeZone.getDefault()); mHourFormat.setTimeZone(TimeZone.getDefault()); mMinFormat.setTimeZone(TimeZone.getDefault()); } private Bitmap setWeatherInteractiveIcon(String weatherIcon) { int resID = getResources().getIdentifier("ic_" + weatherIcon , "drawable", getPackageName()); return BitmapFactory.decodeResource(getResources(), resID); } private Bitmap setWeatherAmbientIcon(String weatherIcon) { int resIDBW = getResources().getIdentifier("ic_" + weatherIcon + "_bw" , "drawable", getPackageName()); return BitmapFactory.decodeResource(getResources(), resIDBW); } @Override public void onDestroy() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); super.onDestroy(); } private Paint createTextPaint(int textColor) { Paint paint = new Paint(); paint.setColor(textColor); paint.setTypeface(NORMAL_TYPEFACE); paint.setAntiAlias(true); return paint; } private Paint createBoldTextPaint(int textColor) { Paint paint = new Paint(); paint.setColor(textColor); paint.setTypeface(BOLD_TYPEFACE); paint.setAntiAlias(true); return paint; } @Override public void onVisibilityChanged(boolean visible) { super.onVisibilityChanged(visible); if (visible) { registerReceiver(); // Update time zone in case it changed while we weren't visible. mDateFormat.setTimeZone(TimeZone.getDefault()); mHourFormat.setTimeZone(TimeZone.getDefault()); mMinFormat.setTimeZone(TimeZone.getDefault()); mGoogleApiClient.connect(); } else { unregisterReceiver(); if(mGoogleApiClient!=null&&mGoogleApiClient.isConnected()){ Wearable.DataApi.removeListener(mGoogleApiClient, this); mGoogleApiClient.disconnect(); } } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } private void registerReceiver() { if (mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = true; IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED); MyWatchFace.this.registerReceiver(mTimeZoneReceiver, filter); } private void unregisterReceiver() { if (!mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = false; MyWatchFace.this.unregisterReceiver(mTimeZoneReceiver); } @Override public void onApplyWindowInsets(WindowInsets insets) { super.onApplyWindowInsets(insets); Resources resources = MyWatchFace.this.getResources(); mTimeHourPaint.setTextSize(resources.getDimension(R.dimen.time_text_size)); mTimeMinPaint.setTextSize(resources.getDimension(R.dimen.time_text_size)); mTimeSecPaint.setTextSize(resources.getDimension(R.dimen.time_text_size)); mDatePaint.setTextSize(resources.getDimension(R.dimen.date_text_size)); mTemperatureMinPaint.setTextSize(resources.getDimension(R.dimen.temp_text_size)); mTemperatureMaxPaint.setTextSize(resources.getDimension(R.dimen.temp_text_size)); mWeatherInfoNotAvailablePaint.setTextSize(resources.getDimension(R.dimen.date_text_size)); } @Override public void onPropertiesChanged(Bundle properties) { super.onPropertiesChanged(properties); mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false); } @Override public void onTimeTick() { super.onTimeTick(); invalidate(); } @Override public void onAmbientModeChanged(boolean inAmbientMode) { super.onAmbientModeChanged(inAmbientMode); if (mAmbient != inAmbientMode) { mAmbient = inAmbientMode; if (mLowBitAmbient) { mTimeHourPaint.setAntiAlias(!inAmbientMode); mTimeMinPaint.setAntiAlias(!inAmbientMode); mTimeSecPaint.setAntiAlias(!inAmbientMode); mDatePaint.setAntiAlias(!inAmbientMode); mTemperatureMaxPaint.setAntiAlias(!inAmbientMode); mTemperatureMinPaint.setAntiAlias(!inAmbientMode); mWeatherInfoNotAvailablePaint.setAntiAlias(!inAmbientMode); } if(mAmbient){ mBackgroundInteractivePaint.setColor(getResources().getColor(R.color.ambient_background)); mTimeHourPaint.setColor(getResources().getColor(R.color.ambient_primary_secondary_text)); mTimeMinPaint.setColor(getResources().getColor(R.color.ambient_primary_secondary_text)); mDatePaint.setColor(getResources().getColor(R.color.ambient_primary_secondary_text)); mTemperatureMaxPaint.setColor(getResources().getColor(R.color.ambient_primary_secondary_text)); mTemperatureMinPaint.setColor(getResources().getColor(R.color.ambient_primary_secondary_text)); mWeatherInfoNotAvailablePaint.setColor(getResources().getColor(R.color.ambient_primary_secondary_text)); mTimeHourPaint.setTypeface(NORMAL_TYPEFACE); mTemperatureMaxPaint.setTypeface(NORMAL_TYPEFACE); } else{ mBackgroundInteractivePaint.setColor(getResources().getColor(R.color.interactive_background)); mTimeHourPaint.setColor(getResources().getColor(R.color.interactive_primary_text)); mTimeMinPaint.setColor(getResources().getColor(R.color.interactive_primary_text)); mDatePaint.setColor(getResources().getColor(R.color.interactive_secondary_text)); mTemperatureMaxPaint.setColor(getResources().getColor(R.color.interactive_primary_text)); mTemperatureMinPaint.setColor(getResources().getColor(R.color.interactive_secondary_text)); mWeatherInfoNotAvailablePaint.setColor(getResources().getColor(R.color.interactive_secondary_text)); mTimeHourPaint.setTypeface(BOLD_TYPEFACE); mTemperatureMaxPaint.setTypeface(BOLD_TYPEFACE); } invalidate(); } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } @Override public void onDraw(Canvas canvas, Rect bounds) { Paint backgroundPaint; Bitmap weatherIcon; if (isInAmbientMode()) { backgroundPaint=mBackgroundAmbientPaint; weatherIcon=mWeatherAmbientIcon; } else { backgroundPaint=mBackgroundInteractivePaint; weatherIcon=mWeatherInteractiveIcon; } canvas.drawRect(0, 0, bounds.width(), bounds.height(), backgroundPaint); int spaceY = 20; int spaceX = 10; int mTextDatePaintHeight; int centerX = bounds.width() / 2; int centerY = bounds.height() / 2; mToday.setTime(System.currentTimeMillis()); String text; text = mDateFormat.format(mToday); mDatePaint.getTextBounds(text, 0, text.length(), mTextBounds); canvas.drawText(text, centerX - mTextBounds.width() / 2, centerY, mDatePaint); mTextDatePaintHeight= mTextBounds.height(); text = mHourFormat.format(mToday); mTimeHourPaint.getTextBounds(text, 0, text.length(), mTextBounds); canvas.drawText(text, centerX - mTextBounds.width(), centerY - spaceY-mTextDatePaintHeight, mTimeHourPaint); text = mMinFormat.format(mToday); mTimeMinPaint.getTextBounds(text, 0, text.length(), mTextBounds); canvas.drawText(text, centerX + 4, centerY - spaceY - mTextDatePaintHeight, mTimeMinPaint); canvas.drawLine(centerX - 20, centerY + spaceY, centerX + 20, centerY + spaceY, mLinePaint); if(mHighTemperature !=null && mLowTemperature !=null && weatherIcon!=null) { mTemperatureMaxPaint.getTextBounds(mHighTemperature, 0, mHighTemperature.length(), mTextBounds); canvas.drawText(mHighTemperature, centerX - mTextBounds.width() / 2, centerY + spaceY + spaceY + mTextBounds.height(), mTemperatureMaxPaint); canvas.drawText(mLowTemperature, centerX + mTextBounds.width() / 2 + spaceX, centerY + spaceY + spaceY + mTextBounds.height(), mTemperatureMinPaint); canvas.drawBitmap(weatherIcon, centerX - mTextBounds.width() / 2 - spaceX - weatherIcon.getWidth(), centerY + spaceY + spaceY + mTextBounds.height() / 2 - weatherIcon.getHeight() / 2, null); }else{ text=getResources().getString(R.string.weather_info_not_available); mWeatherInfoNotAvailablePaint.getTextBounds(text, 0, text.length(), mTextBounds); canvas.drawText(text, centerX - mTextBounds.width() / 2, centerY + spaceY + spaceY + mTextBounds.height(), mWeatherInfoNotAvailablePaint); } } /** * Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently * or stops it if it shouldn't be running but currently is. */ private void updateTimer() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); if (shouldTimerBeRunning()) { mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME); } } /** * Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should * only run when we're visible and in interactive mode. */ private boolean shouldTimerBeRunning() { return isVisible() && !isInAmbientMode(); } /** * Handle updating the time periodically in interactive mode. */ private void handleUpdateTimeMessage() { invalidate(); if (shouldTimerBeRunning()) { long timeMs = System.currentTimeMillis(); long delayMs = INTERACTIVE_UPDATE_RATE_MS - (timeMs % INTERACTIVE_UPDATE_RATE_MS); mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs); } } @Override //GoogleApiClient.ConnectionCallbacks public void onConnected(Bundle bundle) { Log.v("Handheld log", "Handheld connected to wearable device"); Wearable.DataApi.addListener(mGoogleApiClient, this); } @Override //GoogleApiClient.ConnectionCallbacks public void onConnectionSuspended(int i) { Log.v("Handheld Log", "Handheld connection to wearable device is suspended"); } @Override //GoogleApiClient.OnConnectionFailedListener public void onConnectionFailed(ConnectionResult connectionResult) { Log.e("Handheld Log", "Handheld connection failed"); } @Override //DataApi.DataListener public void onDataChanged(DataEventBuffer dataEvents) { for (DataEvent event : dataEvents) { if (event.getType() == DataEvent.TYPE_CHANGED) { String path = event.getDataItem().getUri().getPath(); if (WEARABLE_PATH.equals(path)) { DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem()); mHighTemperature = dataMapItem.getDataMap().getString(SUNSHINE_TEMP_HIGH_KEY); mLowTemperature = dataMapItem.getDataMap().getString(SUNSHINE_TEMP_LOW_KEY); mWeatherIcon = Utility.getArtUrlForWeatherCondition((long)dataMapItem.getDataMap().getInt(SUNSHINE_WEATHER_ID_KEY)); mWeatherInteractiveIcon = setWeatherInteractiveIcon(mWeatherIcon); mWeatherAmbientIcon = setWeatherAmbientIcon(mWeatherIcon); invalidate(); }else{ Log.e("Watch Log", "Unrecognized path: " + path); } } } } } }
43.09018
165
0.648126
0cec75e6df8097b94544bd993264e25c17132818
2,434
/* * StringType.java * * Created on 16 de noviembre de 2004, 19:24 */ package com.innowhere.jnieasy.core.impl.common.classtype.model.mustbe.data; import com.innowhere.jnieasy.core.impl.common.classtype.model.ClassTypeManagerImpl; import com.innowhere.jnieasy.core.impl.common.classtype.model.natobj.data.ClassTypeNativeStringBufferWrapperImpl; import com.innowhere.jnieasy.core.impl.common.typedec.model.TypeNativeImpl; import com.innowhere.jnieasy.core.impl.common.typedec.model.mustbe.data.TypeCanBeNativeCapableImpl; import com.innowhere.jnieasy.core.impl.common.typedec.model.mustbe.data.TypeNativeStringBufferImpl; import com.innowhere.jnieasy.core.impl.common.typedec.model.natobj.data.TypeCanBeNativeCapableWrapperImpl; import com.innowhere.jnieasy.core.impl.common.typedec.model.natobj.data.TypeNativeStringBufferWrapperImpl; /** * * @author jmarranz */ public class ClassTypeNativeStringBufferImpl extends ClassTypeNativeStringBasedImpl { public static final Class CLASS = StringBuffer.class; /** Creates a new instance of StringType */ public ClassTypeNativeStringBufferImpl(ClassTypeManagerImpl classTypeMgr) { super(classTypeMgr); } public static void registerClassTypeStringBuffer(ClassTypeManagerImpl mgr) { ClassTypeNativeStringBufferImpl classType = new ClassTypeNativeStringBufferImpl(mgr); classType.registerClassType(); } public static ClassTypeNativeStringBufferImpl getClassTypeStringBuffer(ClassTypeManagerImpl mgr) { return (ClassTypeNativeStringBufferImpl)mgr.findClassType(CLASS.getName()); } public String getVMClassName() { return CLASS.getName(); } public Class getDefaultImplClass() { return CLASS; } public Object newValueDefaultClass() { return new StringBuffer(); } public ClassTypeNativeStringBufferWrapperImpl getClassTypeStringBufferWrapper() { return (ClassTypeNativeStringBufferWrapperImpl)wrapperClassType; } public TypeNativeImpl newTypeNative() { return new TypeNativeStringBufferImpl(this); } public TypeCanBeNativeCapableImpl newTypeCanBeNativeCapable(TypeCanBeNativeCapableWrapperImpl wrapperType) { return new TypeNativeStringBufferImpl(this,(TypeNativeStringBufferWrapperImpl)wrapperType); } }
33.805556
113
0.74774
753d12b91136fbd1443728d63c055de625774453
1,020
package org.dddjava.jig.domain.model.sources.jigreader; public class AdditionalTextSourceReader { KotlinTextSourceReader kotlinTextSourceReader; ScalaSourceAliasReader scalaSourceAliasReader; public AdditionalTextSourceReader(Object... objects) { for (Object object : objects) { if (object instanceof KotlinTextSourceReader) { this.kotlinTextSourceReader = (KotlinTextSourceReader) object; } if (object instanceof ScalaSourceAliasReader) { this.scalaSourceAliasReader = (ScalaSourceAliasReader) object; } } } public KotlinTextSourceReader kotlinTextSourceReader() { if (kotlinTextSourceReader == null) return arg -> ClassAndMethodComments.empty(); return kotlinTextSourceReader; } public ScalaSourceAliasReader scalaSourceAliasReader() { if (scalaSourceAliasReader == null) return arg -> ClassAndMethodComments.empty(); return scalaSourceAliasReader; } }
35.172414
89
0.697059
9c169bdc058130b66ae4d8437ad26cb50286ef76
2,068
package org.usfirst.frc1225.DeepSpace36.subsystems; import org.usfirst.frc1225.DeepSpace36.RobotMap; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.command.PIDSubsystem; import com.revrobotics.CANSparkMax; import com.revrobotics.CANEncoder; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import com.revrobotics.CANSparkMax.IdleMode; public class Arm extends PIDSubsystem { private CANSparkMax m_motor; private CANEncoder m_encoder; public Arm() { super("Arm", RobotMap.armP, RobotMap.armI, RobotMap.armD, RobotMap.armF ); setAbsoluteTolerance(RobotMap.armTolerance); getPIDController().setContinuous(false); getPIDController().setOutputRange(RobotMap.armMinOutput, RobotMap.armMaxOutput); getPIDController().setName("Arm", "Arm Controller"); LiveWindow.add(getPIDController()); m_motor = new CANSparkMax(RobotMap.ArmCANId, MotorType.kBrushless); m_encoder = m_motor.getEncoder(); m_encoder.setPosition(0); m_motor.setIdleMode(IdleMode.kBrake); m_motor.setInverted(true); } @Override public void initDefaultCommand() { } @Override public void periodic() { SmartDashboard.putNumber("Encoder Position", m_encoder.getPosition()); } protected double returnPIDInput() { return m_encoder.getPosition(); // returns the sensor value that is providing the feedback for the system } protected void usePIDOutput(double output) { m_motor.pidWrite(output); // this is where the computed output value from the PIDController is applied to the motor } public void raise() { m_motor.set(0.25); } public void lower() { m_motor.set(-0.15); } public void stop() { m_motor.set(0); } public double getEncoderValue() { return m_encoder.getPosition(); } }
28.722222
120
0.687621
a449a4d98790df37dc17ce89c841548a792fa0f4
7,495
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.tiems.v20190416; import java.lang.reflect.Type; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import com.tencentcloudapi.common.exception.TencentCloudSDKException; import com.tencentcloudapi.common.AbstractClient; import com.tencentcloudapi.common.profile.ClientProfile; import com.tencentcloudapi.common.JsonResponseModel; import com.tencentcloudapi.common.Credential; import com.tencentcloudapi.tiems.v20190416.models.*; public class TiemsClient extends AbstractClient{ private static String endpoint = "tiems.tencentcloudapi.com"; private static String version = "2019-04-16"; /** * 构造client * @param credential 认证信息实例 * @param region 产品地域 */ public TiemsClient(Credential credential, String region) { this(credential, region, new ClientProfile()); } /** * 构造client * @param credential 认证信息实例 * @param region 产品地域 * @param profile 配置实例 */ public TiemsClient(Credential credential, String region, ClientProfile profile) { super(TiemsClient.endpoint, TiemsClient.version, credential, region, profile); } /** *创建服务 * @param req CreateServiceRequest * @return CreateServiceResponse * @throws TencentCloudSDKException */ public CreateServiceResponse CreateService(CreateServiceRequest req) throws TencentCloudSDKException{ JsonResponseModel<CreateServiceResponse> rsp = null; try { Type type = new TypeToken<JsonResponseModel<CreateServiceResponse>>() { }.getType(); rsp = gson.fromJson(this.internalRequest(req, "CreateService"), type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException(e.getMessage()); } return rsp.response; } /** *创建服务配置 * @param req CreateServiceConfigRequest * @return CreateServiceConfigResponse * @throws TencentCloudSDKException */ public CreateServiceConfigResponse CreateServiceConfig(CreateServiceConfigRequest req) throws TencentCloudSDKException{ JsonResponseModel<CreateServiceConfigResponse> rsp = null; try { Type type = new TypeToken<JsonResponseModel<CreateServiceConfigResponse>>() { }.getType(); rsp = gson.fromJson(this.internalRequest(req, "CreateServiceConfig"), type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException(e.getMessage()); } return rsp.response; } /** *删除服务 * @param req DeleteServiceRequest * @return DeleteServiceResponse * @throws TencentCloudSDKException */ public DeleteServiceResponse DeleteService(DeleteServiceRequest req) throws TencentCloudSDKException{ JsonResponseModel<DeleteServiceResponse> rsp = null; try { Type type = new TypeToken<JsonResponseModel<DeleteServiceResponse>>() { }.getType(); rsp = gson.fromJson(this.internalRequest(req, "DeleteService"), type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException(e.getMessage()); } return rsp.response; } /** *删除服务配置 * @param req DeleteServiceConfigRequest * @return DeleteServiceConfigResponse * @throws TencentCloudSDKException */ public DeleteServiceConfigResponse DeleteServiceConfig(DeleteServiceConfigRequest req) throws TencentCloudSDKException{ JsonResponseModel<DeleteServiceConfigResponse> rsp = null; try { Type type = new TypeToken<JsonResponseModel<DeleteServiceConfigResponse>>() { }.getType(); rsp = gson.fromJson(this.internalRequest(req, "DeleteServiceConfig"), type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException(e.getMessage()); } return rsp.response; } /** *描述服务运行环境 * @param req DescribeRuntimesRequest * @return DescribeRuntimesResponse * @throws TencentCloudSDKException */ public DescribeRuntimesResponse DescribeRuntimes(DescribeRuntimesRequest req) throws TencentCloudSDKException{ JsonResponseModel<DescribeRuntimesResponse> rsp = null; try { Type type = new TypeToken<JsonResponseModel<DescribeRuntimesResponse>>() { }.getType(); rsp = gson.fromJson(this.internalRequest(req, "DescribeRuntimes"), type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException(e.getMessage()); } return rsp.response; } /** *描述服务配置 * @param req DescribeServiceConfigsRequest * @return DescribeServiceConfigsResponse * @throws TencentCloudSDKException */ public DescribeServiceConfigsResponse DescribeServiceConfigs(DescribeServiceConfigsRequest req) throws TencentCloudSDKException{ JsonResponseModel<DescribeServiceConfigsResponse> rsp = null; try { Type type = new TypeToken<JsonResponseModel<DescribeServiceConfigsResponse>>() { }.getType(); rsp = gson.fromJson(this.internalRequest(req, "DescribeServiceConfigs"), type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException(e.getMessage()); } return rsp.response; } /** *描述服务 * @param req DescribeServicesRequest * @return DescribeServicesResponse * @throws TencentCloudSDKException */ public DescribeServicesResponse DescribeServices(DescribeServicesRequest req) throws TencentCloudSDKException{ JsonResponseModel<DescribeServicesResponse> rsp = null; try { Type type = new TypeToken<JsonResponseModel<DescribeServicesResponse>>() { }.getType(); rsp = gson.fromJson(this.internalRequest(req, "DescribeServices"), type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException(e.getMessage()); } return rsp.response; } /** *更新服务 * @param req UpdateServiceRequest * @return UpdateServiceResponse * @throws TencentCloudSDKException */ public UpdateServiceResponse UpdateService(UpdateServiceRequest req) throws TencentCloudSDKException{ JsonResponseModel<UpdateServiceResponse> rsp = null; try { Type type = new TypeToken<JsonResponseModel<UpdateServiceResponse>>() { }.getType(); rsp = gson.fromJson(this.internalRequest(req, "UpdateService"), type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException(e.getMessage()); } return rsp.response; } }
38.239796
132
0.674049
c3343e81a69f6bb27a49e168c0110cf740b2512b
7,444
package frc.robot.subsystems.utilities; import java.util.function.DoubleConsumer; import frc.robot.subsystems.DriveTrainMotionControl; //import edu.wpi.first.wpilibj.PIDOutput; import java.util.function.DoubleConsumer; //import edu.wpi.first.wpilibj.PIDSource; import java.util.function.DoubleSupplier; //import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * * @author Rich Topolewski * * Used to take the speed calculated from the PID control and pass it to the drive train, but * before we passes it to the drivetrain we adjust the power difference between the wheels to drive on an arc of specified Radius * * There is a separate PID controller that is constantly adjusting the turn power on the wheel to be proper for the current speed of the robot. * * */ public class PIDOutputArcMotion implements DoubleConsumer/*PIDOutput*/ { final double Kp = 0.05;//1/200; // so at denominator off in the spin-Rate (RPMP the power will reach the max final double Ki = 0.000; final double Kd = 0.0; final double MaxRotationPower = 0.5; //Gyro gyro = Robot.getRobotSensors().getGyro(); // This is just a simple P control, Proportional control of the arc follow // if we assume angle is in degrees and if we were off by 20 Degrees then we would want how much correction // for example id Kp is 0.025 at 20 degrees we would have 0.5 or half the power toward rotating the robot private DriveTrainMotionControl m_RobotDrive; // private double Kp; // private PIDSource m_Gyro; private DoubleSupplier m_Gyro; // private double m_TargetAngle; private double m_RotationPower; private double m_ForwardPower; private double m_ArcRadius; PIDController m_ArcRotationSpeedPID; /* * arcRadius in Inches */ public PIDOutputArcMotion(DriveTrainMotionControl drive, DoubleSupplier /*PIDSource*/ anglePIDSource, double arcRadius) { //SmartDashboard.putString("DriveSpinPIDOutput", "constructor called"); m_RobotDrive = drive; m_Gyro = anglePIDSource ; // m_TargetAngle = Double.MAX_VALUE; m_ArcRadius = arcRadius; // Kp = 0d/20d; //0.025;// // m_TargetAngle = 0.0d; m_RotationPower = 0.0d; m_ForwardPower = 0.0d; // double slowRotation = m_TargetAngle + 90; WrapArcPIDOutput wrappedArcPIDOutput = new WrapArcPIDOutput(this); m_ArcRotationSpeedPID = createArcPIDController(m_Gyro, wrappedArcPIDOutput); //WrapRotationPIDInput wrapRotationPIDInput = new WrapRotationPIDOutput(rotationPID, (PIDSource) m_gyro); } protected synchronized double getRotationPower() { return m_RotationPower; } protected synchronized void setRotationPower(double rotationPower) { m_RotationPower = rotationPower; } @Override //public synchronized void pidWrite(double forwardPower) public void accept(double forwardPower) { // TODO Auto-generated method stub //rotationPower //double rotationPower = 0; //RobotMap.driveTrainRobotDrive21.arcadeDrive(/*moveValue*/ motorPower, /*rotateValue*/ rotationPower); //store it away so rotation can be set appropriately m_ForwardPower = forwardPower; //Adjust the target rotation speed to correct amount so will trace arch of Radius R. m_ArcRotationSpeedPID.setSetpoint(getTargetRotationalSpeed()); SmartDashboard.putNumber("Arc - Target Rotational Speed", m_ArcRotationSpeedPID.getSetpoint()); //Debugging m_RotationPower = 0; double leftPower; double rightPower; // Reduce forward power in case when turn would require more then 100% power. // This can get full and even turning effect // also may help if quickly reduce from full throttle, to avoid a jerk in the rotation as the PID would convert from 1/2 to all all rotation power if (forwardPower + m_RotationPower > 1.0){ forwardPower = 1 - m_RotationPower; } SmartDashboard.putNumber("Arc - Rotational Power", m_RotationPower); SmartDashboard.putNumber("Arc - Forward Power", forwardPower); leftPower = m_ForwardPower + m_RotationPower; rightPower = m_ForwardPower - m_RotationPower; SmartDashboard.putNumber("Arc - Left Power Output", leftPower); SmartDashboard.putNumber("Arc - Right Power Output", rightPower); m_RobotDrive.tankDrive(-leftPower, -rightPower ); } private double getTargetRotationalSpeed(){ boolean debug = true; //calculate the correct rotation speed based on the current speed of the robot. //arched-turn for a robot in a big circle of radius R and // it seems the the rate of angler change just needs to be proportional to the speed, // to get a target R circle: // RateAngularChange = 360*Speed/2pi*R, // where: Speed is the speed of the robot in in/sec // pi is the constant pi // R is the Radius of the turn path we want the robot to take in inches // 360 is number of degrees in full circle. double speed = m_RobotDrive.GetAverageSpeed(); // if (debug) print double angularChangeSpeed = (speed * 360)/(2 * Math.PI * m_ArcRadius); return angularChangeSpeed; } public PIDController createArcPIDController(DoubleSupplier /*PIDSource*/ rotationInput, DoubleConsumer /*PIDOutput*/ rotationPowerOutput) { // rotation speed proportional to the average speed of the wheels // Okay this had been adjusting the speedOfRotation based on how far off they were instead it needs to be adjusted based // on the speed of the robot double targetSpin = getTargetRotationalSpeed(); // PIDController localRotationSpeedPID = new PIDController(Kp,Ki,Kd, rotationInput,rotationPowerOutput); PIDController localRotationSpeedPID = new PIDController(Kp, Ki, Kd); //TODO get the calculate called on PIDController.calclate(rotationInput,rotationPowerOutput); localRotationSpeedPID.setSetpoint(targetSpin); // localRotationSpeedPID.setOutputRange(-MaxRotationPower, MaxRotationPower);// No longer exists, have to do it manually, docs suggest using funciton clamp(..) // localRotationSpeedPID.enable(); //TODO figure out where the calcuate method is going to be called on thie PIDController return localRotationSpeedPID; } public double getForwardPower() { return m_ForwardPower; } //OLD public void disableRotationPIDController(){ //OLD m_ArcRotationSpeedPID.disable(); //OLD //m_RotationController.free(); //OLD } private class WrapArcPIDOutput implements DoubleConsumer /*PIDOutput*/ { private PIDOutputArcMotion m_RotationPowerDestination; //Constructor public WrapArcPIDOutput(PIDOutputArcMotion rotationPowerDesintation) { if (rotationPowerDesintation == null){ throw new NullPointerException("Given rotationPowerDestination was null"); } else{ m_RotationPowerDestination = rotationPowerDesintation; } } @Override //public void pidWrite(double rotationPower) { public void accept(double rotationPower) { this.m_RotationPowerDestination.setRotationPower(rotationPower); } } }
36.490196
167
0.710236
5675800f0cdebc8dd2f2eb95c655eb4a28d8b8f5
906
package it.unicam.cs.pa.pacal; public abstract class WrapperCalcState<T extends CalcState> implements CalcState { protected final T state; public WrapperCalcState(T state) { this.state = state; } @Override public double getValue1() { return state.getValue1(); } @Override public double getValue2() { return state.getValue2(); } @Override public void setValue(double value) { state.setValue(value); } @Override public boolean isOn() { return state.isOn(); } @Override public void turnOff() { state.turnOff(); } @Override public final void reset() { state.reset(); doReset(); } public T getInnerState() { return state; } protected abstract void doReset(); @Override public void delete() { state.delete(); } }
17.423077
82
0.580574
8c2999b2f8196d8a8c46357a1ae8e6432d8269d3
3,047
package de.aaaaaaah.velcom.backend.access.benchmarkaccess.entities; import de.aaaaaaah.velcom.backend.access.benchmarkaccess.entities.sources.CommitSource; import de.aaaaaaah.velcom.backend.access.benchmarkaccess.entities.sources.TarSource; import de.aaaaaaah.velcom.backend.access.dimensionaccess.entities.Dimension; import de.aaaaaaah.velcom.backend.access.repoaccess.entities.RepoId; import de.aaaaaaah.velcom.shared.util.Either; import java.time.Instant; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * A run is a single execution of the benchmark script. * * <p> It can either be successful, in which case it may contain multiple successful and failed * {@link Measurement}s, or it can be failed, in which case it only contains an error message and no * {@link Measurement}s. Specifically, a successful {@link Run} can still contain failed {@link * Measurement}s. */ public class Run { private final RunId id; private final String author; private final String runnerName; private final String runnerInfo; private final Instant startTime; private final Instant stopTime; private final Either<CommitSource, TarSource> source; private final Either<RunError, Collection<Measurement>> result; public Run(RunId id, String author, String runnerName, String runnerInfo, Instant startTime, Instant stopTime, Either<CommitSource, TarSource> source, Either<RunError, Collection<Measurement>> result) { this.id = Objects.requireNonNull(id); this.author = Objects.requireNonNull(author); this.runnerName = Objects.requireNonNull(runnerName); this.runnerInfo = Objects.requireNonNull(runnerInfo); this.startTime = Objects.requireNonNull(startTime); this.stopTime = Objects.requireNonNull(stopTime); this.source = Objects.requireNonNull(source); this.result = result; } public RunId getId() { return id; } public String getAuthor() { return author; } public String getRunnerName() { return runnerName; } public String getRunnerInfo() { return runnerInfo; } public Either<CommitSource, TarSource> getSource() { return source; } public Instant getStartTime() { return startTime; } public Instant getStopTime() { return stopTime; } public Either<RunError, Collection<Measurement>> getResult() { return result; } public Optional<RepoId> getRepoId() { return getSource().consume( commitSource -> Optional.of(commitSource.getRepoId()), TarSource::getRepoId ); } public Set<Dimension> getAllDimensionsUsed() { return result.getRight().stream() .flatMap(Collection::stream) .map(Measurement::getDimension) .collect(Collectors.toSet()); } @Override public String toString() { return "Run{" + "id=" + id + ", author='" + author + '\'' + ", runnerName='" + runnerName + '\'' + ", runnerInfo='" + runnerInfo + '\'' + ", startTime=" + startTime + ", stopTime=" + stopTime + ", source=" + source + ", result=" + result + '}'; } }
27.954128
100
0.734493
b3db5738133a4aae163d3f053174680456ba07a3
3,430
package models; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIgnore; import play.db.ebean.Model; import play.data.validation.Constraints; @Entity public class User extends Model { /*** * Table id */ @Id public Long id; private String authToken; @Column(length = 256, unique = true, nullable = false) @Constraints.MaxLength(256) @Constraints.Required @Constraints.Email private String emailAddress; @Column(length = 64, nullable = false) private byte[] shaPassword; @Transient @Constraints.Required @Constraints.MinLength(6) @Constraints.MaxLength(256) @JsonIgnore private String password; @Column(length = 256, nullable = false) @Constraints.Required @Constraints.MinLength(2) @Constraints.MaxLength(256) public String fullName; @Column(nullable = false) public Date creationDate; @OneToMany(cascade = CascadeType.ALL, mappedBy = "user") @JsonIgnore public List<Todo> todos = new ArrayList<Todo>(); /** * Create a token for a logged in user * * @return Token * */ public String createToken() { authToken = UUID.randomUUID().toString(); this.save(); return authToken; } /*** * delete auth token */ public void deleteAuthToken() { authToken = null; this.save(); } public User() { this.creationDate = new Date(); } public User(String emailAddress, String password, String fullName) { setEmailAddress(emailAddress); setPassword(password); this.fullName = fullName; this.creationDate = new Date(); } // region methods public String getEmailAddres() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; shaPassword = getSha512(password); } public static byte[] getSha512(String value) { try { return MessageDigest.getInstance("SHA-512").digest( value.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } // endregion // region Finder methods public static Finder<Long, User> find = new Finder<Long, User>(Long.class, User.class); public static User findByAuthToken(String authToken) { System.out.println("searching user..."); if (authToken == null) { System.out.println("null token"); return null; } try { System.out.println("finding by token"); return find.where().eq("authToken", authToken).findUnique(); } catch (Exception e) { e.printStackTrace(); return null; } } public static User findByEmailAddressAndPassword(String emailAddress, String password) { // todo: verify this query is correct. Does it need an "and" statement? return find.where().eq("emailAddress", emailAddress.toLowerCase()) .eq("shaPassword", getSha512(password)).findUnique(); } // endregion }
19.712644
75
0.714286
5645c89cbc6fa582b4dbc93c586a7cd1952c4ad3
284
package ch.ergon.adam.integrationtest.postgresql; import ch.ergon.adam.integrationtest.testcases.RemoveFieldTests; public class PostgreSqlRemoveFieldTests extends RemoveFieldTests { public PostgreSqlRemoveFieldTests() { super(new PostgreSqlTestDbUrlProvider()); } }
28.4
66
0.799296
0ffb26a8da399e6b8f0d164143fd8ff9637e1817
16,794
/* * Copyright 2019 ICON Foundation * Copyright (c) 2018 Aion Foundation https://aion.network/ */ package foundation.icon.ee.tooling.abi; import foundation.icon.ee.score.EEPType; import foundation.icon.ee.struct.StructDB; import foundation.icon.ee.types.Method; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.util.ASMifier; import org.objectweb.asm.util.TraceMethodVisitor; import score.annotation.EventLog; import score.annotation.External; import score.annotation.Optional; import score.annotation.Payable; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; public class ABICompilerMethodVisitor extends MethodVisitor { private final int access; private final String methodName; private final String methodDescriptor; private final List<String> paramNames = new ArrayList<>(); private boolean[] optional; private int flags; private int indexed; private boolean isOnInstall = false; private boolean isFallback = false; private boolean isEventLog = false; private MethodVisitor pmv = null; private final StructDB structDB; private final boolean stripLineNumber; private static final int MAX_INDEXED_COUNT = 3; private static final Set<String> reservedEventNames = Set.of( "ICXTransfer", "ICXBurned", "DepositAdded", "DepositWithdrawn" ); public ABICompilerMethodVisitor(int access, String methodName, String methodDescriptor, MethodVisitor mv, StructDB structDB, boolean stripLineNumber) { super(Opcodes.ASM7, mv); this.access = access; this.methodName = methodName; this.methodDescriptor = methodDescriptor; if (methodName.equals("<init>") && checkIfPublicAndNonStatic(access)) { if (Type.getReturnType(methodDescriptor) != Type.VOID_TYPE) { throw new ABICompilerException("<init> method must have void return type", methodName); } isOnInstall = true; } else if (methodName.equals("fallback") && checkIfPublicAndNonStatic(access)) { if (Type.getReturnType(methodDescriptor) != Type.VOID_TYPE) { throw new ABICompilerException("fallback method must have void return type", methodName); } if (Type.getArgumentTypes(methodDescriptor).length != 0) { throw new ABICompilerException("fallback method cannot take arguments", methodName); } isFallback = true; } this.structDB = structDB; this.stripLineNumber = stripLineNumber; } @Override public void visitParameter(String name, int access) { if (access == 0) { paramNames.add(name); } } @Override public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { if (Type.getType(descriptor).getClassName().equals(External.class.getName())) { if (!checkIfPublicAndNonStatic(this.access)) { throw new ABICompilerException("@External methods must be public and non-static", methodName); } checkArgumentsAndReturnType(); flags |= Method.Flags.EXTERNAL; // to process readonly element return new AnnotationVisitor(Opcodes.ASM7) { @Override public void visit(String name, Object value) { if ("readonly".equals(name) && Boolean.TRUE.equals(value)) { flags |= Method.Flags.READONLY; } } }; } else if (Type.getType(descriptor).getClassName().equals(Payable.class.getName())) { if (!checkIfPublicAndNonStatic(this.access)) { throw new ABICompilerException("@Payable methods must be public and non-static", methodName); } flags |= Method.Flags.PAYABLE; return null; } else if (Type.getType(descriptor).getClassName().equals(EventLog.class.getName())) { boolean isStatic = (this.access & Opcodes.ACC_STATIC) != 0; if (isStatic) { throw new ABICompilerException("@EventLog methods must be non-static", methodName); } if (Type.getReturnType(methodDescriptor) != Type.VOID_TYPE) { throw new ABICompilerException("@EventLog methods must have void return type", methodName); } if (reservedEventNames.contains(methodName)) { throw new ABICompilerException("Reserved event log name", methodName); } if (isFallback()) { throw new ABICompilerException("fallback method cannot be eventlog", methodName); } var args = Type.getArgumentTypes(methodDescriptor); for (Type t : args) { if (!EEPType.isValidEventParameterType(t)) { throw new ABICompilerException("Bad argument type for @EventLog method", methodName); } } isEventLog = true; return new AnnotationVisitor(Opcodes.ASM7) { @Override public void visit(String name, Object value) { if ("indexed".equals(name) && (value instanceof Integer)) { indexed = (int) value; } } }; } return super.visitAnnotation(descriptor, visible); } @Override public void visitAnnotableParameterCount(int parameterCount, boolean visible) { optional = new boolean[parameterCount]; } @Override public AnnotationVisitor visitParameterAnnotation(int parameter, String descriptor, boolean visible) { if (Type.getType(descriptor).getClassName().equals(Optional.class.getName())) { optional[parameter] = true; } return null; } @Override public void visitCode() { super.visitCode(); if (isEventLog()) { pmv = mv; mv = null; } } private void emitSetValueArrayElementString(int index, String value) { super.visitInsn(Opcodes.DUP); if (index <= 5) { super.visitInsn(Opcodes.ICONST_0 + index); } else { super.visitIntInsn(Opcodes.BIPUSH, index); } super.visitLdcInsn(value); super.visitInsn(Opcodes.AASTORE); } private void emitSetValueArrayElementByArg(int index, Type argType, int argPos) { super.visitInsn(Opcodes.DUP); if (index <= 5) { super.visitInsn(Opcodes.ICONST_0 + index); } else { super.visitIntInsn(Opcodes.BIPUSH, index); } switch (argType.getSort()) { case Type.BYTE: case Type.SHORT: case Type.INT: case Type.CHAR: case Type.BOOLEAN: super.visitVarInsn(Opcodes.ILOAD, argPos); super.visitInsn(Opcodes.I2L); super.visitMethodInsn(Opcodes.INVOKESTATIC, "java/math/BigInteger", "valueOf", "(J)Ljava/math/BigInteger;", false); break; case Type.LONG: super.visitVarInsn(Opcodes.LLOAD, argPos); super.visitMethodInsn(Opcodes.INVOKESTATIC, "java/math/BigInteger", "valueOf", "(J)Ljava/math/BigInteger;", false); break; case Type.ARRAY: case Type.OBJECT: super.visitVarInsn(Opcodes.ALOAD, argPos); break; default: assert false : "bad param type "+argType+" for @EventLog"; } super.visitInsn(Opcodes.AASTORE); } private static String getEventParamType(Type type) { switch (type.getSort()) { case Type.BYTE: case Type.SHORT: case Type.INT: case Type.CHAR: case Type.LONG: return "int"; case Type.BOOLEAN: return "bool"; case Type.ARRAY: if (type.getDescriptor().equals("[B")) { return "bytes"; } case Type.OBJECT: if (type.getDescriptor().equals("Ljava/lang/String;")) { return "str"; } else if (type.getDescriptor().equals("Ljava/math/BigInteger;")) { return "int"; } else if (type.getDescriptor().equals("Lscore/Address;")) { return "Address"; } default: assert false : "bad param type "+type+" for @EventLog"; } return null; } private String getEventSignature(Type[] args) { StringBuilder sb = new StringBuilder(); sb.append(methodName); sb.append("("); for (int i=0; i<args.length; i++) { if (i>0) { sb.append(","); } sb.append(getEventParamType(args[i])); } sb.append(")"); return sb.toString(); } private void emitEventLogBody(Type[] args, int argsSize) { int argPos = 1; // Object[] indexedArr = new Object[${indexed+1}]; super.visitIntInsn(Opcodes.BIPUSH, indexed+1); super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); // indexedArr[0] = ${event signature}; emitSetValueArrayElementString(0, getEventSignature(args)); for (int i=0; i<indexed; i++) { // indexedArr[${i+1}] = ${args[i]}; emitSetValueArrayElementByArg(i+1, args[i], argPos); argPos += args[i].getSize(); } super.visitVarInsn(Opcodes.ASTORE, argsSize+1); // Object[] dataArr = new Object[${args.len-indexed}]; super.visitIntInsn(Opcodes.BIPUSH, args.length-indexed); super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); for (int i=0; i<args.length-indexed; i++) { // dataArr[$i] = ${args[indexed+i]}; emitSetValueArrayElementByArg(i, args[indexed+i], argPos); argPos += args[indexed+i].getSize(); } super.visitVarInsn(Opcodes.ASTORE, argsSize+2); // Context.log(indexedArr, dataArr); super.visitVarInsn(Opcodes.ALOAD, argsSize+1); super.visitVarInsn(Opcodes.ALOAD, argsSize+2); super.visitMethodInsn(Opcodes.INVOKESTATIC, "score/Context", "logEvent", "([Ljava/lang/Object;[Ljava/lang/Object;)V", false); super.visitInsn(Opcodes.RETURN); super.visitMaxs(0, 0); } @Override public void visitEnd() { if (isOnInstall() && this.flags != 0) { throw new ABICompilerException("<init> method cannot be annotated", methodName); } if (isFallback() && isExternal()) { throw new ABICompilerException("fallback method cannot be external", methodName); } if (isPayable() && isReadonly()) { throw new ABICompilerException("Method annotated @Payable cannot be readonly", methodName); } if (isEventLog() && this.flags != 0) { throw new ABICompilerException("Method annotated @EventLog cannot have other annotations", methodName); } if ((isOnInstall() || isExternal() || isEventLog()) && paramNames.size() != Type.getArgumentTypes(methodDescriptor).length) { throw new ABICompilerException( "Method parameters size mismatch (must compile with '-parameters')", methodName); } if (pmv != null) { mv = pmv; pmv = null; } if (isEventLog()) { final boolean TRACE = false; MethodNode node; if (TRACE) { node = new MethodNode(Opcodes.ASM7); pmv = mv; mv = node; } var args = Type.getArgumentTypes(methodDescriptor); if (args.length >= Byte.MAX_VALUE) { throw new ABICompilerException("Too many args in @EventLog method", methodName); } var argsSize = (Type.getArgumentsAndReturnSizes(methodDescriptor)>>2)-1; emitEventLogBody(args, argsSize); if (TRACE) { var asmifier = new ASMifier(); node.accept(new TraceMethodVisitor(asmifier)); var pw = new PrintWriter(System.out); asmifier.print(pw); pw.flush(); node.accept(pmv); mv = pmv; pmv = null; } } super.visitEnd(); } private boolean checkIfPublicAndNonStatic(int access) { boolean isPublic = (access & Opcodes.ACC_PUBLIC) != 0; boolean isStatic = (access & Opcodes.ACC_STATIC) != 0; return isPublic && !isStatic; } private void checkArgumentsAndReturnType() { for (Type type : Type.getArgumentTypes(this.methodDescriptor)) { if (!structDB.isValidParamType(type)) { throw new ABICompilerException( type.getClassName() + " is not an allowed parameter type", methodName); } } Type returnType = Type.getReturnType(methodDescriptor); if (!structDB.isValidReturnType(returnType)) { throw new ABICompilerException( returnType.getClassName() + " is not an allowed return type", methodName); } } public Method getCallableMethodInfo() { if (isExternal() || isOnInstall()) { Type type = Type.getReturnType(this.methodDescriptor); int output; try { output = structDB.getEEPTypeFromReturnType(type); } catch (IllegalArgumentException e) { throw new ABICompilerException("Invalid return type: " + type.getClassName(), methodName); } int optionalCount = 0; if (optional != null) { for (int i = optional.length - 1; i >= 0; i--) { if (optional[i]) { if (i < optional.length - 1 && !optional[i + 1]) { throw new ABICompilerException("Non-optional parameter follows @Optional parameter", methodName); } optionalCount++; } } } Type[] types = Type.getArgumentTypes(this.methodDescriptor); for (var t : types) { structDB.addParameterType(t); } structDB.addReturnType(type); return Method.newFunction(methodName, flags, optionalCount, getMethodParameters(), output, type.getDescriptor()); } if (isFallback() && isPayable()) { return Method.newFallback(); } if (isEventLog()) { Method.Parameter[] params = getMethodParameters(); if (indexed < 0 || indexed > params.length || indexed > MAX_INDEXED_COUNT) { throw new ABICompilerException("Invalid indexed count=" + indexed, methodName); } return Method.newEvent(methodName, indexed, params); } return null; } private Method.Parameter[] getMethodParameters() { Type[] types = Type.getArgumentTypes(this.methodDescriptor); Method.Parameter[] params; params = new Method.Parameter[types.length]; for (int i = 0; i < types.length; i++) { params[i] = new Method.Parameter( paramNames.get(i), types[i].getDescriptor(), structDB.getDetailFromParameterType(types[i]), optional != null && optional[i]); } return params; } public boolean isExternal() { return (this.flags & Method.Flags.EXTERNAL) != 0; } public boolean isReadonly() { return (this.flags & Method.Flags.READONLY) != 0; } public boolean isPayable() { return (this.flags & Method.Flags.PAYABLE) != 0; } public boolean isOnInstall() { return isOnInstall; } public boolean isFallback() { return isFallback; } public boolean isEventLog() { return isEventLog; } public String getMethodName() { return methodName; } public String getDescriptor() { return methodDescriptor; } public void visitLineNumber(int line, Label start) { if (stripLineNumber) { return; } super.visitLineNumber(line, start); } }
37.403118
133
0.576218
8ccc16a4946ff0029a69c6a80b3814bebc7c7f63
559
package wusc.edu.pay.webservice.merchant.utils; import java.util.Map; import wusc.edu.pay.common.utils.ResourceUtils; /** * balanceRate.properties * @desc * @date 2013-10-31,下午4:28:01 */ public class Context { final static String SYSTEM_FILE="service";//系统配置文件 /** * 系统文件配置 加载。 */ public static Map<String,String> SYSTEM_CONFIG=ResourceUtils.getResource(SYSTEM_FILE).getMap(); public final static String SUCCESS="100"; public static String notityReceiveUrl = SYSTEM_CONFIG.get("NOTIFY_RECEIVE_URL"); }
21.5
97
0.697674
680cdcefa061decbe73ed90f437d670c4b0972a4
5,644
package com.ruoyi.project.performance.slave.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.gridfs.GridFsResource; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; 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.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.mongodb.client.MongoDatabase; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBuckets; import com.mongodb.client.gridfs.GridFSDownloadStream; import com.mongodb.client.gridfs.GridFSFindIterable; import com.mongodb.client.gridfs.model.GridFSFile; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; import com.ruoyi.framework.aspectj.lang.annotation.Log; import com.ruoyi.framework.aspectj.lang.constant.BusinessType; import com.ruoyi.framework.mongo.MongoFileUtils; import com.ruoyi.project.performance.slave.domain.Slave; import com.ruoyi.project.performance.slave.service.ISlaveService; import com.ruoyi.framework.web.controller.BaseController; import com.ruoyi.framework.web.page.TableDataInfo; import com.ruoyi.framework.web.domain.AjaxResult; import static org.springframework.data.mongodb.core.query.Query.query; import static org.springframework.data.mongodb.gridfs.GridFsCriteria.whereFilename; /** * 执行机 信息操作处理 * * @author ruoyi * @date 2018-08-24 */ @Controller @RequestMapping("/performance/slave") public class SlaveController extends BaseController { private String prefix = "performance/slave"; @Autowired private ISlaveService slaveService; @Autowired private MongoTemplate mongoTemplate; @Autowired private GridFsTemplate gridFsTemplate; @Autowired private MongoDbFactory mongoDbFactory; /* @Autowired private GridFSBucket gridFSBucket;*/ @RequiresPermissions("performance:slave:view") @GetMapping() public String slave() { return prefix + "/slave"; } /** * 查询执行机列表 * @throws IOException */ @RequiresPermissions("performance:slave:list") @PostMapping("/list") @ResponseBody public TableDataInfo list(Slave slave) throws IOException { /*Resource file = new ClassPathResource("C:\\weiji.jtl");*/ /* String path="C:\\weiji1.jtl"; path=path.replace("\\\\", "/"); File file= new File(path); InputStream input = new FileInputStream(file); try { gridFsTemplate.store(input, file.getName(), "jtl"); } catch (Exception e) { e.printStackTrace(); } //下载 String file1=file.getName(); GridFSFindIterable result = gridFsTemplate.find(query(whereFilename().is(file1))); GridFSFile gridFsFile= result.first(); MongoDatabase db = mongoDbFactory.getDb(); GridFSDownloadStream gridFSDownloadStream = GridFSBuckets.create(db).openDownloadStream(gridFsFile.getObjectId()); GridFsResource gr= new GridFsResource(gridFsFile, gridFSDownloadStream); File file3=new File("C:\\ceshi\\weiji2.jtl"); file3.createNewFile(); OutputStream os = new FileOutputStream(file); InputStream inputStream=gr.getInputStream(); OutputStream os = new FileOutputStream(file3); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead =inputStream.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); inputStream.close(); */ MongoFileUtils.addFileMongo("C:\\ceshi\\jojo1.txt"); /*MongoFileUtils.getFileMongo("jojo", "C:\\ceshi\\jojo1.txt");*/ startPage(); List<Slave> list = slaveService.selectSlaveList(slave); return getDataTable(list); } /** * 新增执行机 */ @GetMapping("/add") public String add() { return prefix + "/add"; } /** * 新增保存执行机 */ @RequiresPermissions("performance:slave:add") @Log(title = "执行机", action = BusinessType.INSERT) @PostMapping("/add") @ResponseBody public AjaxResult addSave(Slave slave) { return toAjax(slaveService.insertSlave(slave)); } /** * 修改执行机 */ @GetMapping("/edit/{slaveId}") public String edit(@PathVariable("slaveId") Integer slaveId, ModelMap mmap) { Slave slave = slaveService.selectSlaveById(slaveId); mmap.put("slave", slave); return prefix + "/edit"; } /** * 修改保存执行机 */ @RequiresPermissions("performance:slave:edit") @Log(title = "执行机", action = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(Slave slave) { return toAjax(slaveService.updateSlave(slave)); } /** * 删除执行机 */ @RequiresPermissions("performance:slave:remove") @Log(title = "执行机", action = BusinessType.DELETE) @PostMapping( "/remove") @ResponseBody public AjaxResult remove(String ids) { return toAjax(slaveService.deleteSlaveByIds(ids)); } }
28.94359
122
0.723423
db34b0681b4e248721af0b2de2913d3804ca89f0
714
package moe.kyokobot.bot.util; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class NetworkUtil { private static final String USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0"; private static OkHttpClient client = new OkHttpClient(); public static byte[] download(String url) throws IOException { Request request = new Request.Builder() .header("User-Agent", USER_AGENT) .url(url) .build(); Response response = client.newCall(request).execute(); return response.body() == null ? new byte[0] : response.body().bytes(); } }
32.454545
116
0.663866
af3e0279e455f57673f5fdcd58fe2863a702a82a
1,748
/*^ =========================================================================== Diff Detector - FX =========================================================================== Copyright (C) 2017 Gianluca Costa =========================================================================== 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 info.gianlucacosta.diffdetector.fx; import info.gianlucacosta.diffdetector.diffdetector_fx.ArtifactInfo; import info.gianlucacosta.diffdetector.fx.main.MainScene; import info.gianlucacosta.diffdetector.icons.MainIcon; import javafx.application.Application; import javafx.scene.image.Image; import javafx.stage.Stage; public class App extends Application { @Override public void start(Stage primaryStage) throws Exception { MainScene mainScene = MainScene.create(); primaryStage.getIcons().add( new Image(MainIcon.get(32) ) ); primaryStage.setTitle(ArtifactInfo.getName()); primaryStage.setScene(mainScene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
33.615385
77
0.586957
094162da3eb122d46d2ace78e2a28d217e772dc1
597
package springContextContainer.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import springContextContainer.model.NameEntity; import springContextContainer.repositories.NameEntityRepository; import java.util.List; @Component public class NameContainer { @Autowired NameEntityRepository nameEntityRepository; public void add(NameEntity entity) { nameEntityRepository.save(entity); } public List<NameEntity> out() { return (List<NameEntity>) nameEntityRepository.findAll(); } }
24.875
65
0.782245
d51261ab96a179eb39f36bb133124e319d1a67ff
2,398
/** * (C) Copyright 2015 Adam Wasila and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: */ package org.wasila.ntree; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class NTreeTest { @Test public void testCreateWithNoRoot() { DataNTree<String> tree = new DataNTree<>(); assertNull(tree.getRoot()); } @Test public void testCreateWithRoot() { DataNTree<String> tree = new DataNTree<>("root"); assertEquals("root", tree.getRoot().getData()); } @Test public void testCreateAndAddChildren() { DataNTree<String> tree = new DataNTree<>("root"); tree.addChild(tree.getRoot(), "firstChild"); tree.addChild(tree.getRoot(), "secondChild"); tree.addChild(tree.getRoot(), "thirdChild"); assertEquals("root", tree.getRoot().getData()); assertEquals("firstChild", tree.getRoot().getChildNodeOf(0).getData()); assertEquals("secondChild", tree.getRoot().getChildNodeOf(1).getData()); assertEquals("thirdChild", tree.getRoot().getChildNodeOf(2).getData()); } @Test public void testCreateAndInsertChildren() { DataNTree<String> tree = new DataNTree<>("root"); tree.addChild(tree.getRoot(), 0, "secondChild"); tree.addChild(tree.getRoot(), 1, "thirdChild"); tree.addChild(tree.getRoot(), 0, "firstChild"); assertEquals("root", tree.getRoot().getData()); assertEquals("firstChild", tree.getRoot().getChildNodeOf(0).getData()); assertEquals("secondChild", tree.getRoot().getChildNodeOf(1).getData()); assertEquals("thirdChild", tree.getRoot().getChildNodeOf(2).getData()); } @Test public void testFluentCreate() { //TODO } }
33.774648
80
0.669725
e4fe7cd2f9ec08637f1e934862b332ef4b5490c7
3,406
package springboot; import com.alibaba.druid.pool.DruidDataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.Banner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.PlatformTransactionManager; import springboot.config.HttpPortCfg; import springboot.config.NettyServerConfig; import javax.annotation.Resource; import javax.sql.DataSource; @SpringBootApplication @EnableScheduling @MapperScan("springboot.dao") public class StartApplication { @Resource private HttpPortCfg httpPortCfg; @Resource private NettyServerConfig nettyConfig; public static void main(String[] args) throws Exception{ SpringApplication app = new SpringApplication(StartApplication.class); app.setBannerMode(Banner.Mode.OFF); app.setBannerMode(Banner.Mode.OFF); app.run(args); } // datasource注入 @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return new DruidDataSource(); } //mybatis SQLSession注入 @Bean public SqlSessionFactory sqlSessionFactoryBean() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource()); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:/mapper/*.xml")); return sqlSessionFactoryBean.getObject(); } //事务支持 @Bean public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } // // 配置8080端口自动转向8443 // @Bean // public EmbeddedServletContainerFactory servletContainer() { // TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { // @Override // protected void postProcessContext(Context context) { // SecurityConstraint securityConstraint = new SecurityConstraint(); // securityConstraint.setUserConstraint("CONFIDENTIAL"); // SecurityCollection collection = new SecurityCollection(); // collection.addPattern("/*"); // securityConstraint.addCollection(collection); // context.addConstraint(securityConstraint); // } // }; // // Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); // connector.setScheme("http"); // connector.setPort(Integer.valueOf(httpPortCfg.getHttp_port())); // connector.setSecure(false); // connector.setRedirectPort(Integer.valueOf(httpPortCfg.getHttps_port())); // // tomcat.addAdditionalTomcatConnectors(connector); // return tomcat; // } }
36.234043
102
0.737816
b1c9040b67912ae68114a6aa6b72b294b8e4ba4d
5,820
/* * Copyright 2009 Kantega AS * * 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 no.kantega.openaksess.search.controller; import no.kantega.openaksess.search.index.rebuild.IndexRebuilder; import no.kantega.publishing.security.SecuritySession; import no.kantega.search.api.index.ProgressReporter; import no.kantega.search.api.provider.IndexableDocumentProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.*; import static no.kantega.openaksess.search.index.rebuild.ProgressReporterUtils.notAllProgressReportersAreMarkedAsFinished; @Controller public class RebuildIndexAction { private final Logger log = LoggerFactory.getLogger(getClass()); private String formView; private String statusView; @Autowired private IndexRebuilder indexRebuilder; private List<ProgressReporter> progressReporters; @Autowired private List<IndexableDocumentProvider> indexableDocumentProviders; @RequestMapping(value = "/admin/administration/RebuildIndex.action", method = RequestMethod.GET) public ModelAndView handleGet() throws Exception { Map<String, Object> map = new HashMap<>(); if(progressReporters == null || !notAllProgressReportersAreMarkedAsFinished(progressReporters)) { progressReporters = null; map.put("providers", indexableDocumentProviders); return new ModelAndView(formView, map); } else { map.put("progressReporters", progressReporters); return new ModelAndView(statusView, map); } } @RequestMapping(value = "/admin/administration/RebuildIndex.action", method = RequestMethod.POST) public ModelAndView handlePost(HttpServletRequest request) throws Exception { Map<String, Object> map = new HashMap<>(); if (progressReporters == null) { List<String> providersToInclude = getProvidersToInclude(request); SecuritySession securitySession = SecuritySession.getInstance(request); log.info("Rebuild index started by {}. Providers: {}", securitySession.getUser().getId(), providersToInclude); progressReporters = indexRebuilder.startIndexing(providersToInclude); } return new ModelAndView(statusView, map); } @RequestMapping(value = "/admin/administration/RebuildIndexStatus.action", method = RequestMethod.GET) public @ResponseBody Map<String, Object> getStatus(){ Map<String, Object> model = new HashMap<>(); List<Map<String, String>> status = new ArrayList<>(); if(progressReporters != null){ for (ProgressReporter progressReporter : progressReporters) { Map<String, String> statusMap = new LinkedHashMap<>(); statusMap.put("current", String.valueOf(progressReporter.getCurrent())); statusMap.put("total", String.valueOf(progressReporter.getTotal())); statusMap.put("type", String.valueOf(progressReporter.getDocType())); status.add(statusMap); } model.put("status", status); model.put("allDone", !notAllProgressReportersAreMarkedAsFinished(progressReporters)); } return model; } @RequestMapping(value = "/admin/administration/DeleteIndex.action", method = RequestMethod.POST) public ModelAndView deleteIndex(HttpServletRequest request) throws Exception { SecuritySession securitySession = SecuritySession.getInstance(request); log.info("{} deleted the search index", securitySession.getUser().getId()); indexRebuilder.deleteIndex(); return handleGet(); } @RequestMapping(value = "/admin/administration/StopIndex.action", method = RequestMethod.POST) public ResponseEntity stopIndex(HttpServletRequest request) throws Exception { SecuritySession securitySession = SecuritySession.getInstance(request); log.info("{} stopped reindexing", securitySession.getUser().getId()); indexRebuilder.stopIndexing(); return new ResponseEntity(HttpStatus.OK); } public void setFormView(String formView) { this.formView = formView; } public void setStatusView(String statusView) { this.statusView = statusView; } private List<String> getProvidersToInclude(HttpServletRequest request) { List<String> includedProviders = new ArrayList<>(); for (IndexableDocumentProvider provider : indexableDocumentProviders) { String simpleName = provider.getName(); if(ServletRequestUtils.getBooleanParameter(request, "include." + simpleName, false)){ includedProviders.add(simpleName); } } return includedProviders; } }
42.173913
122
0.719072
beefbf053ff75aa1712023bb96707228a2df41d4
4,563
/* * Copyright 2020 Dmitry Romanyuta * * 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 su.void_.api; import javax.naming.NotContextException; import javax.net.ssl.*; import java.io.IOException; import java.net.ConnectException; import java.net.UnknownHostException; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.List; public class SocketService { public static final String CIPHER_SUITE_NULL = "SSL_NULL_WITH_NULL_NULL"; public static final String PROTOCOL_NONE = "NONE"; private String address = null; private Integer port = null; private String serverName = null; private SSLSocket sslSocket = null; private SSLSession sslSession = null; public SocketService(String address, Integer port, String serverName) { this.address = address; this.port = port; this.serverName = serverName; } private SSLParameters createSslParameters() { SSLParameters sslParameters = new SSLParameters(); List<SNIServerName> sniHostNameList = Arrays.asList(new SNIHostName(serverName)); sslParameters.setServerNames(sniHostNameList); return sslParameters; } public void create() throws NotContextException { SSLSocketFactory sslSocketFactory = null; try { sslSocketFactory = createSslSocketFactory(); } catch (Exception e) { e.printStackTrace(); } try { sslSocket = (SSLSocket) sslSocketFactory.createSocket(address, port); } catch (ConnectException e) { e.printStackTrace(); throw new NotContextException(e.getMessage()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } SSLParameters sslParameters = this.createSslParameters(); sslSocket.setSSLParameters(sslParameters); sslSession = sslSocket.getSession(); } public ServerCertificate fetchServerCertificate() { TransformerService transformerService = new TransformerService(); X509Certificate serverCertificate = null; try { boolean isCipherSuiteNull = SocketService.CIPHER_SUITE_NULL.equals(sslSession.getCipherSuite()); boolean isProtocolNone = SocketService.PROTOCOL_NONE.equals(sslSession.getProtocol()); if (!(isCipherSuiteNull && isProtocolNone)) { Certificate[] certificates = sslSession.getPeerCertificates(); X509Certificate[] x509Certificates = transformerService.transformToX509CertificateV3(certificates); PurposeService purposeService = new PurposeService(x509Certificates); serverCertificate = purposeService.findServerCertificate(); } } catch (SSLPeerUnverifiedException e) { e.printStackTrace(); } ServerCertificateMapper serverCertificateMapper = new ServerCertificateMapper(serverCertificate); return serverCertificateMapper.toServerCertificate(serverName); } public void close() { try { sslSocket.close(); } catch (IOException e) { e.printStackTrace(); } } private SSLSocketFactory createSslSocketFactory() throws Exception { TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] chain, String authType) { } public void checkServerTrusted(X509Certificate[] chain, String authType) { } } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManager, new SecureRandom()); return sslContext.getSocketFactory(); } }
38.025
115
0.672584
dba8fdc6b372a572bcbc76b67b2161083318f312
410
package fxy.oop.servelet; import fxy.oop.server.Request; import fxy.oop.server.Response; public class TestServelet extends Servelet{ @Override public void doGet(Response res, Request req) throws Exception { // TODO Auto-generated method stub res.println("success..."); } @Override public void doPost(Response res, Request req) throws Exception { // TODO Auto-generated method stub } }
17.826087
65
0.731707
ac70d0d6053f0e5c42441cf21ae1be65d842076d
1,375
package org.springframework.boot.actuate.autoconfigure.flyway; import org.flywaydb.core.Flyway; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.flyway.FlywayEndpoint; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * {@link EnableAutoConfiguration Auto-configuration} for {@link FlywayEndpoint}. * * @author Phillip Webb * @since 2.0.0 */ @Configuration @ConditionalOnClass(Flyway.class) @AutoConfigureAfter(FlywayAutoConfiguration.class) public class FlywayEndpointAutoConfiguration { @Bean @ConditionalOnBean(Flyway.class) @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint public FlywayEndpoint flywayEndpoint(ApplicationContext context) { return new FlywayEndpoint(context); } }
35.25641
102
0.853091
6f60ab3708f93f12c04ff830e0b34b5f0dee281f
6,554
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 com.google.jse4conf; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class Conf2JSTest extends ConfTestBase { // NOTE: to skip a test, replace @Test with @Ignore. @Test public void comments() { // # comments are removed, "key=jse" => "const key=exp;" in a closure. String input = "[test1] #comment\nk1 =1 #one\n k2=k1+1; ; \n"; String output = "var test1 = function() {\n const k1 = 1;\n" + " const k2 = k1 + 1;\n return {k1:k1,k2:k2,};\n}();\n"; assertEquals(output, compileConf(input)); } @Test public void semicolons() { // Semicolons start line comments to EOL in JGit Config parser. // Use double quotes to include special characters. // * e1: 1;2;3;; ==> 1 // * e2: {3;5} ==> {3 => {3;} // * g1: "{3;5}" ==> {3;5} => {3;5;} String input = "[s1]\ne1=1;2;3;;\ne2={3;5}\ng1=\"{3;5}\"\n"; String output = "var s1 = function() {\n const e1 = 1;\n const e2 = { 3; };\n" + " const g1 = { 3; 5; };\n return {e1:e1,e2:e2,g1:g1,};\n}();\n"; assertEquals(output, compileConf(input)); } @Test public void escapeChars() { // JGit Config parser accepts: \" \\ \n \t \b String input = "[s1]\ne1='\\\"a\\\\\\\"bx\\tcd\\be'\n"; String output = "var s1 = function() {\n" + " const e1 = '\"a\"bx\\tcd\\be';\n" + " return {e1:e1,};\n}();\n"; assertEquals(output, compileConf(input)); } @Test public void escapeSemicolon() { // JGit Config parser does not recognize \; String input = "[s1]\ne1={3\\;5}\n"; // Older JGit Config.java returns error message as: String output = "ERROR: Bad escape: ;"; // Newer JGit Config.java returns error message as: // "ERROR: Bad escape: \\u003b"; assertEquals(output, compileConf(input).replace("\\u003b", ";")); input = "[s2]\ne2=\"{3\\;5}\"\n"; assertEquals(output, compileConf(input).replace("\\u003b", ";")); } @Test public void sectionOrder() { // Order of sections in .conf are preserved. String input = "[sEc-1]\nk1=1\n[sEC-2]\nk2=2\n"; String sec1 = "var sEc1 = function() {\n const k1 = 1;\n" + " return {k1:k1,};\n}();\n"; String sec2 = "var sEC2 = function() {\n const k2 = 2;\n" + " return {k2:k2,};\n}();\n"; String output = sec1 + sec2; assertEquals(output, compileConf(input)); input = "[sEC-2]\nk2=2\n[sEc-1]\nk1=1\n"; output = sec2 + sec1; assertEquals(output, compileConf(input)); } @Test public void referenceOtherKeys() { String input = "[t1]\nk1=k2.x\nk2=({d:1,x:2})\nk3=k4().y\nk4=()=>({a:1,y:3})\n"; String output = "var t1 = function() {\n const k2 = ({ d: 1, x: 2});\n" + " const k1 = k2.x;\n const k4 = () => ({ a: 1, y: 3});\n" + " const k3 = k4().y;\n return {k1:k1,k2:k2,k3:k3,k4:k4,};\n}();\n"; String result = compileConf(input); assertEquals(output, result); assertThat(result).doesNotContain("ERROR"); } @Test public void propertyGet() { // Collect used names in ast.PropertyGet and eval them in dependency order.. String input = "[t1]\nk1=k2.x\nk2=({d:1,x:2})\nk3=k4(5).y\nk4=(n)=>({a:n,y:n*n})\n"; evalJS(compileConf(input)); js.check("t1.k1", 2); js.check("t1.k3", 25); js.check("t1.k2.d", 1); js.check("t1.k4(3).a", 3); } @Test public void subSection() { // Subsections are ordered as if sections, and named as <sectionSubsection>. // Empty sections are skipped. String input = "[sEc-1]\nk1=1\n[sEC-2 \"sUb--seC\"]\nk2=2\n"; String sec1 = "var sEc1 = function() {\n const k1 = 1;\n" + " return {k1:k1,};\n}();\n"; String sec2sub = "var sEC2SUbSeC = function() {\n const k2 = 2;\n" + " return {k2:k2,};\n}();\n"; String output = sec1 + sec2sub; assertEquals(output, compileConf(input)); input = "[sEC-2 \"sUb-..-seC\"]\nk2=2\n[sEc-1]\nk1=1\n"; output = sec2sub + sec1; assertEquals(output, compileConf(input)); } @Test public void defaultString() { // JSE with errors are treated as strings. String input = "[tsec]\nk1=k2+1\nk2=2\nk3=OWNERS\nk4=a.b.c\n"; String output = "var tsec = function() {\n const k2 = 2;\n" + " const k1 = k2 + 1;\n const k3 = 'OWNERS';\n const k4 = 'a.b.c';\n" + JS.undefinedError("k3", "OWNERS", "OWNERS") + JS.undefinedError("k4", "a.b.c", "a") + " return {k1:k1,k2:k2,k3:k3,k4:k4,};\n}();\n"; assertEquals(output, compileConf(input, true)); } @Test public void toJSName() { // Section and subsection names are converted to valid JavaScript // identifiers, skipping invalid characters, and with the Camel notation. String[][] pairs = { {null, null}, {"", ""}, {"3", "3"}, {"_", "_"}, {"a", "a"}, {"123", "123"}, {"456", "_456"}, {"Abc", "_abc"}, {"aaBbCc", "aa.bb..-cc"}, {"AaBbDd", "_aa_bb_.-dd"}, {"123aaBbCc", "123aa_bb_.-cc"}, {"s1D1", "s1.d1"}, {"secAbc", "sec.abc"}, {"secXyZ", "sec--.--.xyZ"}, {"pluginFindOwners", "plugin-find-owners"} }; for (String[] pair : pairs) { assertEquals(pair[0], JS.toJSName(pair[1])); } } @Test public void renameSections() { String input = "[s1.d1]\nk1=1\n[s2--d2]\nk2=2\n[s3.-.d3]\nk3=3\n[s4]\nk4=4\n"; String output = "var s1D1 = function() {\n const k1 = 1;\n return {k1:k1,};\n}();\n" + "var s2D2 = function() {\n const k2 = 2;\n return {k2:k2,};\n}();\n" + "var s3D3 = function() {\n const k3 = 3;\n return {k3:k3,};\n}();\n" + "var s4 = function() {\n const k4 = 4;\n return {k4:k4,};\n}();\n"; assertEquals(output, compileConf(input)); } }
37.028249
94
0.565151
e674fa3151c8835f41ca001b4850782beef0438d
10,634
package EBM_tool.OWL2Prefuse.tree; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.border.TitledBorder; import EBM_tool.OWL2Prefuse.OWL2Prefuse.ExportableGraphic; import prefuse.Constants; /** * This class represents a tree in a JPanel. * <p/> * Project OWL2Prefuse <br/> * TreePanel.java created 2 januari 2007, 14:05 * <p/> * Copyright &copy 2006 Jethro Borsje * * @author <a href="mailto:info@jborsje.nl">Jethro Borsje</a> * @version $$Revision:$$, $$Date:$$ */ public class TreePanel extends JPanel implements ActionListener, ExportableGraphic { private static final long serialVersionUID = -8165702852610633094L; /** * The Display which takes care of displaying the Prefuse tree. */ protected TreeDisplay m_display; /** * The radiobutton for the left-to-right orientation. */ private JRadioButton m_rbLtr; /** * The radiobutton for the top-to-bottom orientation. */ private JRadioButton m_rbTtb; /** * The radiobutton for the right-to-left orientation. */ private JRadioButton m_rbRtl; /** * The radiobutton for the bottom-to-top orientation. */ private JRadioButton m_rbBtt; /** * Creates a new instance of TreePanel * @param p_display The Display which takes care of displaying the Prefuse tree. * @param p_legend Indicates whether or not a legend should be added to the * panel. * @param p_orientationControl Indicates whether or not a widget for controlling the * orientation of the tree should be added to the panel. */ public TreePanel(TreeDisplay p_display, boolean p_legend, boolean p_orientationControl) { super(new BorderLayout()); m_display = p_display; initPanel(p_legend, p_orientationControl); } /** * Export the display of the tree, to the given file type. * @param p_file The file which is going to contain the export, valid file types * are: "png" and "jpg". * @param p_fileType The file type of the image to be created. */ public void export(File p_file, String p_fileType) { try { // Export the display to an image. OutputStream out = new BufferedOutputStream(new FileOutputStream(p_file)); m_display.saveImage(out, p_fileType, 1.0); out.close(); } catch(IOException e) { e.printStackTrace(); } } /** * Initialize this panel. * @param p_legend Indicates whether or not a legend should be added to the * panel. * @param p_orientationControl Indicates whether or not a widget for controlling the * orientation of the tree should be added to the panel. */ protected void initPanel(boolean p_legend, boolean p_orientationControl) { setBackground(m_display.getBackground()); setForeground(m_display.getForeground()); add(m_display, BorderLayout.CENTER); add(createBox(), BorderLayout.SOUTH); if (p_legend || p_orientationControl) add(getSideBar(p_legend), BorderLayout.EAST); } /** * Initialize the sidebar of the tree panel. * @param p_legend Indicates whether or not a legend should be added to the * panel. * @param p_orientationControl Indicates whether or not a widget for controlling the * orientation of the tree should be added to the panel. * @return The side bar. */ private JPanel getSideBar(boolean p_legend) { // Create the panel. JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.FIRST_LINE_START; int y = 0; constraints.gridx = 0; constraints.gridy = y++; //if (!p_orientationControl) constraints.weighty = 1; if (p_legend) panel.add(getLegend(), constraints); //if (p_orientationControl) //{ constraints.gridy = 1; constraints.weighty = y++; constraints.fill = GridBagConstraints.HORIZONTAL; panel.add(getOrientationWidgets(), constraints); //} // Set the background of the panel. panel.setBackground(m_display.getBackground()); return panel; } /** * Create a legend pane and return it. * @return The legend in an editor pane. */ public JEditorPane getLegend() { String content = "<html><body>" + "<table>" + "<tr><td bgcolor=\"" + Integer.toHexString(EBM_tool.OWL2Prefuse.OWL2Prefuse.Constants.NODE_COLOR_CLASS & 0x00ffffff) + "\" width=\"20px\"></td><td>OWL class</td></tr>" + "<tr><td bgcolor=\"" + Integer.toHexString(EBM_tool.OWL2Prefuse.OWL2Prefuse.Constants.NODE_COLOR_INDIVIDUAL & 0x00ffffff) + "\"></td><td>OWL individual</td></tr>" + "<tr><td bgcolor=\"" + Integer.toHexString(EBM_tool.OWL2Prefuse.OWL2Prefuse.Constants.NODE_COLOR_SELECTED & 0x00ffffff) + "\"></td><td>Selected node</td></tr>" + "<tr><td bgcolor=\"" + Integer.toHexString(EBM_tool.OWL2Prefuse.OWL2Prefuse.Constants.NODE_COLOR_HIGHLIGHTED & 0x00ffffff) + "\"></td><td>Path to selected node</td></tr>" + "<tr><td bgcolor=\"" + Integer.toHexString(EBM_tool.OWL2Prefuse.OWL2Prefuse.Constants.NODE_COLOR_SEARCH & 0x00ffffff) + "\"></td><td>Node in search result set</td></tr>" + "<tr><td bgcolor=\"" + Integer.toHexString(EBM_tool.OWL2Prefuse.OWL2Prefuse.Constants.NODE_DEFAULT_COLOR & 0x00ffffff) + "\"></td><td>Default color</td></tr>" + "<tr><td bgcolor=\"" + Integer.toHexString(EBM_tool.OWL2Prefuse.OWL2Prefuse.Constants.NODE_COLOR_HAS_RULE & 0x00ffffff) + "\"></td><td>Node with rule color</td></tr>" + "</body></html>"; JEditorPane legend = new JEditorPane("text/html", content); legend.setEditable(false); legend.setBorder(new TitledBorder("Legend")); JPanel panel = new JPanel(); panel.setBorder(new TitledBorder("Legend")); panel.add(legend); return legend; } /** * Get the radio buttons which enable the user to change the orientation of * the graph. * @return The orientation radio buttons in a JPanel. */ private JPanel getOrientationWidgets() { // Create the panel. JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.FIRST_LINE_START; // Create a label. JLabel label = new JLabel("Orientation: "); // Create a button group. ButtonGroup btnGroup = new ButtonGroup(); // Create the radiobuttons. m_rbLtr = new JRadioButton("left-to-right", true); m_rbLtr.setBackground(m_display.getBackground()); m_rbLtr.addActionListener(this); m_rbTtb = new JRadioButton("top-to-bottom"); m_rbTtb.setBackground(m_display.getBackground()); m_rbTtb.addActionListener(this); m_rbRtl = new JRadioButton("right-to-left"); m_rbRtl.setBackground(m_display.getBackground()); m_rbRtl.addActionListener(this); m_rbBtt = new JRadioButton("bottom-to-top"); m_rbBtt.setBackground(m_display.getBackground()); m_rbBtt.addActionListener(this); // Add the radiobuttons to the button group. btnGroup.add(m_rbLtr); btnGroup.add(m_rbTtb); btnGroup.add(m_rbRtl); btnGroup.add(m_rbBtt); // Add the label and the radiobuttons to the panel. constraints.gridx = 0; constraints.gridy = 0; panel.add(label, constraints); constraints.gridy = 1; panel.add(m_rbLtr, constraints); constraints.gridy = 2; panel.add(m_rbTtb, constraints); constraints.gridy = 3; panel.add(m_rbRtl, constraints); constraints.gridy = 4; constraints.weighty = 1; panel.add(m_rbBtt, constraints); // Set the background of the panel. panel.setBackground(m_display.getBackground()); // Add a titled border to the panel. panel.setBorder(new TitledBorder("Orientation control")); return panel; } /** * Create the title and search panel widgets which are displayed at the bottom * of the graph panel. * @return The title and searchpanel widgets in a Box. */ private Box createBox() { // Create a box to display the node title label and the search box. Box box = new Box(BoxLayout.X_AXIS); box.add(Box.createHorizontalStrut(10)); box.add(m_display.getTitleLabel()); box.add(Box.createHorizontalGlue()); box.add(m_display.getSearchPanel()); box.add(Box.createHorizontalStrut(3)); box.setBackground(m_display.getBackground()); box.setForeground(m_display.getForeground()); return box; } /** * This method is implemented because this class implements the ActionListener * interface. It takes care of the event that user click on one of the orientation * radio buttons. It changes the orientation appropriately. * @param e The ActionEvent. */ public void actionPerformed(ActionEvent e) { int orientation = 0; if (e.getSource() == m_rbLtr) orientation = Constants.ORIENT_LEFT_RIGHT; else if (e.getSource() == m_rbTtb) orientation = Constants.ORIENT_TOP_BOTTOM; else if (e.getSource() == m_rbRtl) orientation = Constants.ORIENT_RIGHT_LEFT; else if (e.getSource() == m_rbBtt) orientation = Constants.ORIENT_BOTTOM_TOP; m_display.setOrientation(orientation); m_display.getVisualization().cancel("orient"); m_display.getVisualization().run("treeLayout"); m_display.getVisualization().run("orient"); } }
37.843416
188
0.642844
7b39c090a56c3afcafbff2b973a78c851e17de7e
2,751
package com.forsrc.boot.resource.web.plantuml; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import net.sourceforge.plantuml.FileFormat; import net.sourceforge.plantuml.FileFormatOption; import net.sourceforge.plantuml.SourceStringReader; @RestController @RequestMapping(value = "/plantuml") public class PlantUmlController { private static final Map<FileFormat, String> CONTENT_TYPE; static { Map<FileFormat, String> map = new HashMap<FileFormat, String>(); map.put(FileFormat.PNG, "image/png"); map.put(FileFormat.SVG, "image/svg+xml"); map.put(FileFormat.EPS, "application/postscript"); map.put(FileFormat.UTXT, "text/plain;charset=UTF-8"); CONTENT_TYPE = Collections.unmodifiableMap(map); } @RequestMapping(value = "/{type}", method = { RequestMethod.GET, RequestMethod.POST }) public ResponseEntity<byte[]> type(@PathVariable("type") String type, @RequestParam("uml") String uml, UriComponentsBuilder ucBuilder) throws IOException { SourceStringReader reader = new SourceStringReader(param(uml)); ByteArrayOutputStream out = new ByteArrayOutputStream(); FileFormat fileFormat = FileFormat.valueOf(type.toUpperCase()); if (fileFormat == null) { fileFormat = FileFormat.PNG; } reader.outputImage(out, new FileFormatOption(FileFormat.SVG, false)); HttpHeaders headers = new HttpHeaders(); // headers.setContentType(MediaType.IMAGE_JPEG); headers.set(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE.get(fileFormat)); return new ResponseEntity<>(out.toByteArray(), headers, HttpStatus.OK); } @RequestMapping(value = "/uml", method = { RequestMethod.GET, RequestMethod.POST }) public ResponseEntity<byte[]> uml(@RequestParam("type") String type, @RequestParam("uml") String uml, UriComponentsBuilder ucBuilder) throws IOException { return type(type, uml, ucBuilder); } private String param(String uml) { return uml.replaceAll("(%0A)|(\\\\n)", "\n"); } }
42.323077
106
0.733915
aa810dd702654823ab0ab1dd757ab11a4a1a70dd
413
package org.jc.framework.kaleido.instancer; import org.jc.framework.kaleido.annotation.Instancer; import java.util.ArrayList; import java.util.List; /** * @author jc * @date 2019/9/3 23:42 */ @Instancer public class ListInstancer extends AbstractInstancer<List> { public ListInstancer() { super(null); } @Override public List newInstance() { return new ArrayList(); } }
17.956522
60
0.682809
ceced55ac1a642104d045f02df21127ff5ca7f6d
2,519
// // This file was generated with the JavaTM Architecture for XML Binding (JAXB) Reference Implementation, v2.2.5-2 // Seehref="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Changes to this file are lost when the source schema is recompiled. // Generated: 02/04/2014 at 12:22:03 PM CET // package org.onvif.ver10.schema; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p> * Java-Klasse f�r Merge complex type. * * <p> * The following schema fragment indicates the expected content contained in this class. * * <pre>{@code * <complexType name="Merge"> <complexContent> <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> <sequence> * <element name="from" type="{http://www.onvif.org/ver10/schema}ObjectId" maxOccurs="unbounded" minOccurs="2"/> * <element name="to" type="{http://www.onvif.org/ver10/schema}ObjectId"/> </sequence> </restriction> </complexContent> </complexType> * }</pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Merge", propOrder = { "from", "to" }) public class Merge { /** * */ @XmlElement(required = true) protected List<ObjectId> from; /** * */ @XmlElement(required = true) protected ObjectId to; /** * Gets the value of the from property. * * <p> * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the from property. * * <p> * For example, to add a new item, do as follows: * * <pre>{@code * getFrom().add(newItem); * }</pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link ObjectId } * * * @return */ public List<ObjectId> getFrom() { if (from == null) { from = new ArrayList<>(); } return this.from; } /** * Ruft den Wert der to-Eigenschaft ab. * * @return possible object is {@link ObjectId } * */ public ObjectId getTo() { return to; } /** * Legt den Wert der to-Eigenschaft fest. * * @param value * allowed object is {@link ObjectId } * */ public void setTo(ObjectId value) { this.to = value; } }
23.990476
175
0.638349
7d364ff1063e4b9d5a7d8294865ea73843a27283
974
package me.chanjar.weixin.cp.bean.templatecard; import com.google.gson.JsonObject; import kotlin.text.UStringsKt; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; /** * 卡片二级垂直内容,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过4 * @author yzts * @date 2021/9/22 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class VerticalContent implements Serializable { private static final long serialVersionUID = -1383852553854573558L; /** * 卡片二级标题,建议不超过38个字.必填字段 */ private String title; /** * 二级普通文本,建议不超过160个字 */ private String desc; public JsonObject toJson() { JsonObject vContentJson = new JsonObject(); vContentJson.addProperty("title", this.getTitle()); if (StringUtils.isNotBlank(this.getDesc())) { vContentJson.addProperty("desc", this.getDesc()); } return vContentJson; } }
21.644444
69
0.741273
2db288c6555b7ccabfe6a81a8082c978ddd88feb
1,069
package org.dizitart.no2.index.fulltext.languages; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.Test; public class ItalianTest { @Test public void testStopWords() { Set<String> actualStopWordsResult = (new Italian()).stopWords(); assertEquals(660, actualStopWordsResult.size()); assertTrue(actualStopWordsResult.contains("fare")); assertTrue(actualStopWordsResult.contains("lui")); assertTrue(actualStopWordsResult.contains("triplo")); assertTrue(actualStopWordsResult.contains("nove")); assertTrue(actualStopWordsResult.contains("governo")); assertTrue(actualStopWordsResult.contains("avevo")); assertTrue(actualStopWordsResult.contains("avranno")); assertTrue(actualStopWordsResult.contains("chiunque")); assertTrue(actualStopWordsResult.contains("dei")); assertTrue(actualStopWordsResult.contains("sugli")); assertTrue(actualStopWordsResult.contains("del")); } }
36.862069
72
0.724041
fa9adc5155291c9db34b4c274b5fb97a28dcc4fe
2,991
/* * 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 newsCategorization; import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * * @author dee */ public class Preprocessing { private HashMap<String, Double> preprocessedData; public Preprocessing() { preprocessedData = new HashMap<>(); } public String removeUrl(String article) { String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)"; Pattern p = Pattern.compile(urlPattern, Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(article); int i = 0; while (m.find()) { article = article.replaceAll(m.group(i), "").trim(); i++; } return article; } public String[] stopwordRemoval(String[] tokens) { String[] stopword = loadFile("stopword.txt"); List<String> stp = Arrays.asList(stopword); List<String> tkn = Arrays.asList(tokens); List<String> res = tkn.stream() .filter(o -> !(stp.contains(o))) .collect(Collectors.toList()); return res.toArray(new String[0]); } public String[] preprocess(String article) { String[] result; article = article.toLowerCase(); article = removeUrl(article); article = article.replaceAll("[^a-zA-Z|^ ]", ""); String[] tokens = article.split(" "); String[] rootword = new String[1]; Set<String> rootwordSet = new HashSet(Arrays.asList(rootword)); Set<String> tokenSet = new HashSet(Arrays.asList(tokens)); rootwordSet.retainAll(tokenSet); String[] nonKataDasar = rootwordSet.toArray(new String[rootwordSet.size()]); result = stopwordRemoval(tokens); return result; } public void preprocessInput(String[] input, int[] cls) { if (input.length != cls.length) { throw new IllegalStateException("Wrong Input size"); } for (int i = 0; i < input.length; i++) { } } public HashMap<String, Double> getPreprocessedData() { return preprocessedData; } public String[] loadFile(String filename) { String s = ""; try (BufferedReader b = new BufferedReader(new FileReader(filename))) { String line; while ((line = b.readLine()) != null) { s = s + line + "\n"; } } catch (Exception e) { } return s.split("\n"); } }
29.038835
126
0.573387
dea2ecec15d866a4bdece78c566d12b39b20432a
6,941
package com.carlosparra.githubjobs.githubjobsapi.activities; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.carlosparra.githubjobs.githubjobsapi.R; import com.carlosparra.githubjobs.githubjobsapi.adapters.JobCustomAdapter; import com.carlosparra.githubjobs.githubjobsapi.models.Job; import com.carlosparra.githubjobs.githubjobsapi.services.API; import com.carlosparra.githubjobs.githubjobsapi.services.contracts.GitHubJobsService; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { private final static String TAG = MainActivity.class.getSimpleName(); private final static String DEFAULT_SEARCH_CRITERIA = "Android"; private RecyclerView recyclerView; private JobCustomAdapter adapter; private List<Job> jobsList; private ProgressBar loadingIndicator; private TextView loadingIndicatorText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recyclerViewJobsList); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.addItemDecoration( new DividerItemDecoration( this, DividerItemDecoration.VERTICAL) ); loadingIndicator = findViewById(R.id.pb_loading_jobs); loadingIndicatorText = findViewById(R.id.tv_loading_jobs); toggleLoaderIndicator(true); adapter = new JobCustomAdapter(new ArrayList<Job>(), this); adapter.setOnItemClickListener(new JobCustomAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { startActivity(jobsList.get(position)); } }); recyclerView.setAdapter(adapter); if (isNetworkAvailable()) { getContentFromService(DEFAULT_SEARCH_CRITERIA); } else { displayMessage(getString(R.string.no_network_available_error), Toast.LENGTH_LONG); toggleLoaderIndicator(false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_search) { displaySearchDialog(); return true; } return super.onOptionsItemSelected(item); } private void getContentFromService(String searchCriteria) { GitHubJobsService service = API.getService().create(GitHubJobsService.class); Call<List<Job>> jobCall = service.getJobs(searchCriteria); jobCall.enqueue(new Callback<List<Job>>() { @Override public void onResponse(Call<List<Job>> call, Response<List<Job>> response) { Log.d(TAG, String.valueOf(response.code())); toggleLoaderIndicator(false); if (response.body().size() <= 0) { displayMessage(getString(R.string.no_jobs_found), Toast.LENGTH_LONG); return; } displayMessage(getString(R.string.jobs_found_response, response.body().size(), response.code()), Toast.LENGTH_SHORT); jobsList = response.body(); adapter.updateDataSet(jobsList); } @Override public void onFailure(Call<List<Job>> call, Throwable t) { Log.e(TAG, t.getMessage()); toggleLoaderIndicator(false); displayMessage(t.getMessage(), Toast.LENGTH_SHORT); } }); } private void toggleLoaderIndicator(boolean isDisplay) { if (isDisplay) { recyclerView.setVisibility(View.INVISIBLE); loadingIndicator.setVisibility(View.VISIBLE); loadingIndicatorText.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); loadingIndicator.setVisibility(View.INVISIBLE); loadingIndicatorText.setVisibility(View.INVISIBLE); } } private void startActivity(Job job) { Intent intent = new Intent(this, JobDetailsActivity.class); intent.putExtra("JOB", job); startActivity(intent); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null; return (networkInfo != null && networkInfo.isConnectedOrConnecting()); } private void displayMessage(String message, int duration) { Toast.makeText(this, message, duration).show(); } private void displaySearchDialog() { final AlertDialog.Builder builder = new AlertDialog.Builder(this); View inflater = getLayoutInflater().inflate(R.layout.dialog_search, null); final EditText searchCriteria = inflater.findViewById(R.id.et_search_criteria); builder.setView(inflater) .setTitle(R.string.search_dialog_title) .setPositiveButton(R.string.search_dialog_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { if (!searchCriteria.getText().toString().isEmpty()) { toggleLoaderIndicator(true); getContentFromService(searchCriteria.getText().toString()); } } }) .setNegativeButton(R.string.search_dialog_negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.create().show(); } }
35.963731
107
0.654661
e1811fcc87ee3a62125057e494f2ec4db1e340b8
1,096
package com.neusoft.bsp.user.service.impl; import com.neusoft.bsp.user.entity.User; import com.neusoft.bsp.user.mapper.PermissionMapper; import com.neusoft.bsp.user.service.MenuService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; @Service public class MenuServiceImpl implements MenuService { @Resource private PermissionMapper permissionMapper; @Override public List<User> getAllMenu() { return permissionMapper.getPermissionsOfUser(); } @Override public void addMenu(Map<String, String> params) { String userId = params.get("userId"); String permissionId = params.get("permissionId"); permissionMapper.addPermissionForUser(userId, permissionId); } @Override public void deleteMenu(Map<String, String> params) { String userId = params.get("userId"); String permissionId = params.get("permissionId"); permissionMapper.deletePermissionForUser(userId, permissionId); } }
28.842105
72
0.70438
16b607c2ca02c4e04e1d16f1e630f2fe12d3c398
938
package com.pay.fakepay.jsf; import com.pay.fakepay.ejb.AdministratorCreateService; import javax.annotation.security.DeclareRoles; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.inject.Named; @Named @DeclareRoles({"admin"}) @Stateless public class AdministratorCreateBean { @EJB AdministratorCreateService administratorCreateService; String username; String password; public AdministratorCreateBean() { } public String register() { administratorCreateService.create(username, password); return "admin"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
22.333333
63
0.654584
ca69eefcfa21f25f0e3b089ebd339b7634b03832
3,020
/* * Copyright (c) 2000-2005 Regents of the University of California. * All rights reserved. * * This software was developed at the University of California, Irvine. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Irvine. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ package edu.uci.isr.xarch.instancemapping; import java.util.Collection; import edu.uci.isr.xarch.XArchActionMetadata; import edu.uci.isr.xarch.XArchTypeMetadata; import edu.uci.isr.xarch.XArchPropertyMetadata; /** * Interface for accessing objects of the * MappedInterfaceInstance <code>xsi:type</code> in the * instancemapping namespace. Extends and * inherits the properties of the * InterfaceInstance <code>xsi:type</code>. * * @author xArch apigen */ public interface IMappedInterfaceInstance extends edu.uci.isr.xarch.instance.IInterfaceInstance, edu.uci.isr.xarch.IXArchElement{ public final static XArchTypeMetadata TYPE_METADATA = new XArchTypeMetadata( XArchTypeMetadata.XARCH_ELEMENT, "instancemapping", "MappedInterfaceInstance", edu.uci.isr.xarch.instance.IInterfaceInstance.TYPE_METADATA, new XArchPropertyMetadata[]{ XArchPropertyMetadata.createElement("type", "instance", "XMLLink", 0, 1)}, new XArchActionMetadata[]{}); /** * Set the type for this MappedInterfaceInstance. * @param value new type */ public void setType(edu.uci.isr.xarch.instance.IXMLLink value); /** * Clear the type from this MappedInterfaceInstance. */ public void clearType(); /** * Get the type from this MappedInterfaceInstance. * @return type */ public edu.uci.isr.xarch.instance.IXMLLink getType(); /** * Determine if this MappedInterfaceInstance has the given type * @param typeToCheck type to compare * @return <code>true</code> if the types are equivalent, * <code>false</code> otherwise */ public boolean hasType(edu.uci.isr.xarch.instance.IXMLLink typeToCheck); /** * Determine if another MappedInterfaceInstance is equivalent to this one, ignoring * ID's. * @param MappedInterfaceInstanceToCheck MappedInterfaceInstance to compare to this one. * @return <code>true</code> if all the child elements of this * MappedInterfaceInstance are equivalent, <code>false</code> otherwise. */ public boolean isEquivalent(IMappedInterfaceInstance MappedInterfaceInstanceToCheck); }
38.717949
130
0.75
72bb1629cade4fe9d53df22d46a42d0045357561
8,123
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.join.fetch; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.join.ParentJoinPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.test.ESSingleNodeTestCase; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.hamcrest.Matchers.equalTo; public class ParentJoinFieldSubFetchPhaseTests extends ESSingleNodeTestCase { @Override protected Collection<Class<? extends Plugin>> getPlugins() { return Collections.singletonList(ParentJoinPlugin.class); } public void testSingleParentJoinField() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject("join_field") .field("type", "join") .startObject("relations") .field("parent", "child") .field("child", "grand_child") .field("product", "item") .endObject() .endObject() .endObject() .endObject().string(); IndexService service = createIndex("test", Settings.EMPTY); service.mapperService().merge("doc", new CompressedXContent(mapping), MapperService.MergeReason.MAPPING_UPDATE, true); // empty document client().prepareIndex("test", "doc", "0") .setSource().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); // parent document client().prepareIndex("test", "doc", "1") .setSource("join_field", Collections.singletonMap("name", "parent")) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); // child document Map<String, String> joinField = new HashMap<>(); joinField.put("name", "child"); joinField.put("parent", "1"); client().prepareIndex("test", "doc", "2") .setSource("join_field", joinField).setRouting("1") .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); // grand_child document joinField.clear(); joinField.put("name", "grand_child"); joinField.put("parent", "2"); client().prepareIndex("test", "doc", "3") .setSource("join_field", joinField).setRouting("2") .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); // product document client().prepareIndex("test", "doc", "4") .setSource("join_field", Collections.singletonMap("name", "product")) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); // item document joinField.clear(); joinField.put("name", "item"); joinField.put("parent", "4"); client().prepareIndex("test", "doc", "5") .setSource("join_field", joinField).setRouting("4").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); SearchResponse response = client().prepareSearch("test") .setQuery(QueryBuilders.termQuery("join_field", "parent")) .get(); assertThat(response.getHits().totalHits, equalTo(1L)); assertThat(response.getHits().getHits().length, equalTo(1)); assertThat(response.getHits().getHits()[0].field("join_field").getValue(), equalTo("parent")); assertNull(response.getHits().getHits()[0].field("join_field#parent")); response = client().prepareSearch("test") .setQuery(QueryBuilders.termQuery("join_field", "child")) .get(); assertThat(response.getHits().totalHits, equalTo(1L)); assertThat(response.getHits().getHits().length, equalTo(1)); assertThat(response.getHits().getHits()[0].field("join_field").getValue(), equalTo("child")); assertThat(response.getHits().getHits()[0].field("join_field#parent").getValue(), equalTo("1")); assertNull(response.getHits().getHits()[0].field("join_field#child")); response = client().prepareSearch("test") .setQuery(QueryBuilders.termQuery("join_field", "grand_child")) .get(); assertThat(response.getHits().totalHits, equalTo(1L)); assertThat(response.getHits().getHits().length, equalTo(1)); assertThat(response.getHits().getHits()[0].field("join_field").getValue(), equalTo("grand_child")); assertThat(response.getHits().getHits()[0].field("join_field#child").getValue(), equalTo("2")); response = client().prepareSearch("test") .setQuery(QueryBuilders.termQuery("join_field", "product")) .get(); assertThat(response.getHits().totalHits, equalTo(1L)); assertThat(response.getHits().getHits().length, equalTo(1)); assertThat(response.getHits().getHits()[0].field("join_field").getValue(), equalTo("product")); assertNull(response.getHits().getHits()[0].field("join_field#product")); response = client().prepareSearch("test") .setQuery(QueryBuilders.termQuery("join_field", "item")) .get(); assertThat(response.getHits().totalHits, equalTo(1L)); assertThat(response.getHits().getHits().length, equalTo(1)); assertThat(response.getHits().getHits()[0].field("join_field").getValue(), equalTo("item")); assertThat(response.getHits().getHits()[0].field("join_field#product").getValue(), equalTo("4")); response = client().prepareSearch("test") .addSort(SortBuilders.fieldSort("join_field")) .get(); assertThat(response.getHits().totalHits, equalTo(6L)); assertThat(response.getHits().getHits().length, equalTo(6)); assertThat(response.getHits().getHits()[0].field("join_field").getValue(), equalTo("child")); assertThat(response.getHits().getHits()[0].field("join_field#parent").getValue(), equalTo("1")); assertNull(response.getHits().getHits()[0].field("join_field#child")); assertThat(response.getHits().getHits()[1].field("join_field").getValue(), equalTo("grand_child")); assertThat(response.getHits().getHits()[1].field("join_field#child").getValue(), equalTo("2")); assertThat(response.getHits().getHits()[2].field("join_field").getValue(), equalTo("item")); assertThat(response.getHits().getHits()[2].field("join_field#product").getValue(), equalTo("4")); assertThat(response.getHits().getHits()[3].field("join_field").getValue(), equalTo("parent")); assertNull(response.getHits().getHits()[3].field("join_field#parent")); assertThat(response.getHits().getHits()[4].field("join_field").getValue(), equalTo("product")); assertNull(response.getHits().getHits()[4].field("join_field#product")); assertNull(response.getHits().getHits()[5].field("join_field")); } }
50.141975
125
0.661824
249b1c9dda0d74d4e397c1533165e98f2375110d
1,509
package l2f.gameserver.network.serverpackets; import l2f.gameserver.model.Effect; public class ShortBuffStatusUpdate extends L2GameServerPacket { /** * This is client's row 2 buff packet. * * Example (C4): * F4 CD 04 00 00 07 00 00 00 0F 00 00 00 - overlord's healing, panel2 * * structure cddd * * NOTES: * 1). hex converting: * Skill 1229 is in hex 4CD, but in packet it is CD 04 00 00. * So i think that we must read the skill's hex id form behind ^^ * 2). multipe skills on row 2: * i don't know what more skills can go at row2 @ offie. * please contact me to test it. Currently packet is working for one skill. * 3). Removing buff icon * must be sended empty packet * F4 00 00 00 00 00 00 00 00 00 00 00 00 * to remove buff icon. Or it will be lasted forever. */ int _skillId; int _skillLevel; int _skillDuration; public ShortBuffStatusUpdate(Effect effect) { _skillId = effect.getSkill().getDisplayId(); _skillLevel = effect.getSkill().getDisplayLevel(); _skillDuration = effect.getTimeLeft(); } /** * Zero packet to delete skill icon. */ public ShortBuffStatusUpdate() { _skillId = 0; _skillLevel = 0; _skillDuration = 0; } @Override protected final void writeImpl() { writeC(0xfa); //Packet type writeD(_skillId); // skill id??? CD 04 00 00 = skill 1229, hex 4CD writeD(_skillLevel); //Skill Level??? 07 00 00 00 = casted by heal 7 lvl. writeD(_skillDuration); //DURATION???? 0F 00 00 00 = 15 sec = overlord's heal } }
26.473684
79
0.684559
3e0fd4216f10118c013e267173c31425efc57406
2,050
package com.dzonesoft.exam.controller.student; import com.dzonesoft.exam.base.BaseApiController; import com.dzonesoft.exam.base.RestResponse; import com.dzonesoft.exam.domain.ExamPaper; import com.dzonesoft.exam.service.ExamPaperAnswerService; import com.dzonesoft.exam.service.ExamPaperService; import com.dzonesoft.exam.utility.DateTimeUtil; import com.dzonesoft.exam.utility.PageInfoHelper; import com.dzonesoft.exam.viewmodel.admin.exam.ExamPaperEditRequestVM; import com.dzonesoft.exam.viewmodel.student.exam.ExamPaperPageResponseVM; import com.dzonesoft.exam.viewmodel.student.exam.ExamPaperPageVM; import com.github.pagehelper.PageInfo; import lombok.AllArgsConstructor; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController("StudentExamPaperController") @RequestMapping(value = "/api/student/exam/paper") @AllArgsConstructor public class ExamPaperController extends BaseApiController { private final ExamPaperService examPaperService; private final ExamPaperAnswerService examPaperAnswerService; private final ApplicationEventPublisher eventPublisher; @RequestMapping(value = "/select/{id}", method = RequestMethod.POST) public RestResponse<ExamPaperEditRequestVM> select(@PathVariable Integer id) { ExamPaperEditRequestVM vm = examPaperService.examPaperToVM(id); return RestResponse.ok(vm); } @RequestMapping(value = "/pageList", method = RequestMethod.POST) public RestResponse<PageInfo<ExamPaperPageResponseVM>> pageList(@RequestBody @Valid ExamPaperPageVM model) { PageInfo<ExamPaper> pageInfo = examPaperService.studentPage(model); PageInfo<ExamPaperPageResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> { ExamPaperPageResponseVM vm = modelMapper.map(e, ExamPaperPageResponseVM.class); vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime())); return vm; }); return RestResponse.ok(page); } }
42.708333
112
0.789756
b35ae2d284e524119d16bd30213cd296c6512ddc
1,491
/******************************************************************************* * Copyright © 2019 by California Community Colleges Chancellor's Office * * 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.cccnext.tesuto.content.dto.section; import org.cccnext.tesuto.content.dto.AbstractAssessmentDto; /** * @author Richard Scott Smith <scott.smith@isostech.com> */ public class AssessmentOrderingDto implements AbstractAssessmentDto { private static final long serialVersionUID = 1l; private boolean shuffle; private String extensions; // Not for pilot public boolean isShuffle() { return shuffle; } public void setShuffle(boolean shuffle) { this.shuffle = shuffle; } public String getExtensions() { return extensions; } public void setExtensions(String extensions) { this.extensions = extensions; } }
33.133333
80
0.644534
01558c1181eecb877c1754b46efbb5f9bc3e78ae
3,695
package view; import controller.Student; import javafx.application.Platform; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.stage.Stage; import model.Error; import java.io.IOException; import java.util.Optional; public class StudentMain { private Student student; private ListProperty<model.Submission> listProperty = new SimpleListProperty<>(); @FXML private Button btnDownloadData; @FXML private Button btnNewAssignment; @FXML private ListView<model.Submission> lstPreviousAssignments; @FXML private TextArea txaContentPane; @FXML private Label lblStudentNum; @FXML private Button btnLogout; public StudentMain() { } public static Alert createAlert(String message, Error error, Alert.AlertType type) { Alert alert = new Alert(type); alert.setTitle("Error"); alert.setHeaderText(message); if (error != null) { alert.setContentText(error.toString()); } return alert; } @FXML void downloadData(ActionEvent event) { try { student.getData(btnDownloadData.getScene().getWindow()); } catch (Error error) { createAlert("Problem creating file", error, Alert.AlertType.ERROR); } } @FXML void logout(ActionEvent event) { Alert a = createAlert("Are you sure you want to logout?", null, Alert.AlertType.CONFIRMATION); Optional<ButtonType> result = a.showAndWait(); if (result.get() == ButtonType.OK) { System.exit(0); } } @FXML void newAssignment(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("StudentAssignment.fxml")); Parent root = fxmlLoader.load(); StudentAssignment controller = fxmlLoader.getController(); controller.setStudent(student); Stage stage = (Stage) btnNewAssignment.getScene().getWindow(); stage.setScene(new Scene(root)); } catch (IOException e) { createAlert("Problem starting assignment", new Error(e), Alert.AlertType.ERROR); } } private void print(String text) { txaContentPane.setText(txaContentPane.getText() + text); } private void println(String text) { print(text + "\n"); } private void println() { println(""); } private void clean() { txaContentPane.setText(""); } public void setStudent(Student student) { this.student = student; lblStudentNum.setText(this.student.getStudentNum()); lstPreviousAssignments.itemsProperty().bind(listProperty); listProperty.set(FXCollections.observableArrayList(student.getPastSubmissions())); lstPreviousAssignments.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> { if (newValue != null) { Platform.runLater(() -> { try { clean(); println("Total mark: " + newValue.getTotalMark()); println(); println(newValue.getFeedback()); } catch (Error error) { createAlert("Problem displaying feedback", error, Alert.AlertType.ERROR); } }); } }); } }
28.643411
116
0.618945
ac7016f163f78713451fa39c449c201446ec6b6b
12,888
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * 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. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * 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. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.pkg; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import org.w3c.dom.DOMException; /** This factory determines what elements are being used in the DOC layer * (ie. the convenient layer). * * The mapping of ODF element to convenient class can be changed from the user * during run time. * * For example, a user might want to create a table always with a certain style or default data and * might want to overwrite the mapping for <code>{odf.element table:table}</code>, that a different * class instead of <code>OdfTable</code> is being used. * */ public class OdfXMLFactory { private static Map<OdfName, Class> mElementTypes = new HashMap<OdfName, Class>(); private static Map<OdfName, Class> mAttributeTypes = new HashMap<OdfName, Class>(); private static Map<String, String> mElementRenames = new HashMap<String, String>(); //a set for the element which need to load class from incubator package. private static Set<String> mIncubatorElements = new HashSet<String>(); private static final String LOCAL_NAME_DELIMITER = "-"; private static final String ELEMENT_NAME_DELIMITER = ":"; private static final String ELEMENT_PACKAGE_NAME = "element"; private static final String ATTRIBUTE_PACKAGE_NAME = "attribute"; static { mElementRenames.put("text:h", "text:heading"); mElementRenames.put("text:p", "text:paragraph"); mIncubatorElements.add("draw:frame"); mIncubatorElements.add("draw:image"); mIncubatorElements.add("number:currency-style"); mIncubatorElements.add("number:date-style"); mIncubatorElements.add("number:percentage-style"); mIncubatorElements.add("number:number-style"); mIncubatorElements.add("number:time-style"); mIncubatorElements.add("office:automatic-styles"); mIncubatorElements.add("office:master-styles"); mIncubatorElements.add("office:styles"); mIncubatorElements.add("style:default-style"); mIncubatorElements.add("style:style"); mIncubatorElements.add("style:page-layout"); mIncubatorElements.add("text:h"); mIncubatorElements.add("text:list"); mIncubatorElements.add("text:list-level-style-bullet"); mIncubatorElements.add("text:list-level-style-image"); mIncubatorElements.add("text:list-level-style-number"); mIncubatorElements.add("text:list-style"); mIncubatorElements.add("text:outline-level-style"); mIncubatorElements.add("text:outline-style"); mIncubatorElements.add("text:p"); mIncubatorElements.add("text:span"); } /** Mapping an ODF element to a new Java DOM element class. * Note: There is a default class for each element being generated from the latest ODF schema */ private static void setOdfElementClass(OdfName odfName, Class className) { mElementTypes.put(odfName, className); } /** Mapping an ODF attribute to a new Java DOM attribute class. * Note: There is a default class for each element being generated from the latest ODF schema. */ private static void setOdfAttributeClass(OdfName odfName, Class className) { mAttributeTypes.put(odfName, className); } /** * @param odfName the name of the ODF attribute the desired DOM class should represent. * @return the Java DOM attribute class to be mapped to a certain ODF attribute. */ private static Class getOdfAttributeClass(OdfName odfName) { return getOdfNodeClass(odfName, ATTRIBUTE_PACKAGE_NAME, mAttributeTypes, true); } /** * @param odfName the name of the ODF element the desired DOM class should represent. * @return the Java DOM element class to be mapped to a certain ODF element. */ private static Class getOdfElementClass(OdfName odfName) { return getOdfNodeClass(odfName, ELEMENT_PACKAGE_NAME, mElementTypes, false); } private static Class getOdfNodeClass(OdfName odfName, String nodeType, Map<OdfName, Class> classCache, boolean isAttribute) { Class c = null; String className = ""; c = classCache.get(odfName); if (c == null) { // Ignore looking for XML namespace attributes or ODF elements without prefix, // as there are no typed ODF classes // (NOTE: For any ODF node from the schema the ODF prefix would ALWAYS exist // as there is a prefix normalization during the previous loading) String prefix = odfName.getPrefix(); if (prefix != null && !(isAttribute && prefix.equals("xmlns"))) { String qName = odfName.getQName(); String localName = odfName.getLocalName(); //judge whether the element need to load class from incubator package. if (mIncubatorElements.contains(qName) && !isAttribute) { //judge whether the element need to rename before find class name. if (mElementRenames.containsKey(qName)) { String renameName = mElementRenames.get(qName); StringTokenizer stok = new StringTokenizer(renameName, ELEMENT_NAME_DELIMITER); prefix = stok.nextToken(); localName = stok.nextToken(); } className = getOdfIncubatorNodeClassName(prefix, localName); } else if ("manifest".equals(prefix)) { className = getOdfPKGNodeClassName(prefix, localName, nodeType); } else { className = getOdfDOMNodeClassName(prefix, localName, nodeType); } try { c = Class.forName(className); classCache.put(odfName, c); } catch (ClassNotFoundException ex) { // all classes are first tring to load and warning is given later } catch (NoClassDefFoundError dex) { Logger.getLogger(OdfXMLFactory.class.getName()).log(Level.INFO, "NoClassDefFoundError: " + className, dex.getMessage()); } } } return c; } private static String getOdfIncubatorNodeClassName(String prefix, String localName) { boolean contains = false; StringBuilder className = new StringBuilder(); if (localName.indexOf(LOCAL_NAME_DELIMITER) != -1) { StringTokenizer stok = new StringTokenizer(localName, LOCAL_NAME_DELIMITER); while (stok.hasMoreElements()) { String substr = stok.nextToken(); if (substr.equals(prefix)) { contains = true; } className = className.append(toUpperCaseFirstCharacter(substr)); } } else { className = className.append(toUpperCaseFirstCharacter(localName)); } if (!((contains && !localName.endsWith("table")) || (localName.equals(prefix)) || (localName.startsWith(prefix) && prefix.equals("anim")))) { className = className.insert(0, toUpperCaseFirstCharacter(prefix)); } className = className.insert(0, "org.odftoolkit.odfdom.incubator.doc." + prefix + "." + "Odf"); return className.toString(); } private static String getOdfPKGNodeClassName(String prefix, String localName, String nodeType) { StringBuilder className = new StringBuilder("org.odftoolkit.odfdom.pkg." + prefix + "."); if (localName.indexOf(LOCAL_NAME_DELIMITER) != -1) { StringTokenizer stok = new StringTokenizer(localName, LOCAL_NAME_DELIMITER); while (stok.hasMoreElements()) { className = className.append(toUpperCaseFirstCharacter(stok.nextToken())); } } else { className = className.append(toUpperCaseFirstCharacter(localName)); } className.append(toUpperCaseFirstCharacter(nodeType)); return className.toString(); } private static String getOdfDOMNodeClassName(String prefix, String localName, String nodeType) { StringBuilder className = new StringBuilder("org.odftoolkit.odfdom.dom." + nodeType + "." + prefix + "."); className = className.append(toUpperCaseFirstCharacter(prefix)); if (localName.indexOf(LOCAL_NAME_DELIMITER) != -1) { StringTokenizer stok = new StringTokenizer(localName, LOCAL_NAME_DELIMITER); while (stok.hasMoreElements()) { className = className.append(toUpperCaseFirstCharacter(stok.nextToken())); } } else { className = className.append(toUpperCaseFirstCharacter(localName)); } className.append(toUpperCaseFirstCharacter(nodeType)); return className.toString(); } private static String toUpperCaseFirstCharacter(String token) { return token.substring(0, 1).toUpperCase() + token.substring(1); } public static OdfElement newOdfElement(OdfFileDom dom, OdfName name) throws DOMException { OdfElement element = null; // lookup registered element class for qname Class elementClass = getOdfElementClass(name); // if a class was registered create an instance of that class if (elementClass != null) { element = (OdfElement) getNodeFromClass(dom, elementClass); } else { String oldPrefix = name.getPrefix(); if (oldPrefix != null) { // check if the namespace prefix is correct or add potential namespace to DOM OdfName adaptedName = addNamespaceToDom(name, dom); String newPrefix = adaptedName.getPrefix(); // in case the prefix was changed as it existed before if (oldPrefix != null && !oldPrefix.equals(newPrefix) // "_1" is the suffix added by OdfFileDom to an existing Namespace && newPrefix.indexOf("__") == -1) { // look up again if there is a class registered for this prefix element = newOdfElement(dom, adaptedName); } else { element = (OdfElement) new OdfAlienElement(dom, adaptedName); Logger.getLogger(OdfXMLFactory.class.getName()).log(Level.FINE, "None-ODF element created for {0}", adaptedName.getQName()); } } else { element = (OdfElement) new OdfAlienElement(dom, name); Logger.getLogger(OdfXMLFactory.class.getName()).log(Level.FINE, "None-ODF element created for {0}", name.getQName()); } } return element; } public static OdfAttribute newOdfAttribute(OdfFileDom dom, OdfName name) throws DOMException { OdfAttribute attr = null; // lookup registered attribute class for qname Class attributeClass = getOdfAttributeClass(name); // if a class was registered create an instance of that class if (attributeClass != null) { attr = (OdfAttribute) getNodeFromClass(dom, attributeClass); } else { // in case it is not a default ODF // add a namespace unless it is a xmlns attribute (no attr value to set the uri) String prefix = name.getPrefix(); if (prefix != null && !prefix.equals("xmlns")) { // check if the namespace prefix is correct or add potential namespace to DOM OdfName adaptedName = addNamespaceToDom(name, dom); String newPrefix = adaptedName.getPrefix(); // in case the prefix was changed as it existed before if (!prefix.equals(newPrefix) && newPrefix.indexOf("__") == -1) { // look up again if there is a class registered for this prefix attr = newOdfAttribute(dom, adaptedName); } else { attr = (OdfAttribute) new OdfAlienAttribute(dom, name); Logger.getLogger(OdfXMLFactory.class.getName()).log(Level.FINE, "None-ODF attribute created for {0}", adaptedName.getQName()); } } else { // create an alien attribute for namespace attribute "xmlns:*" attr = (OdfAttribute) new OdfAlienAttribute(dom, name); } } return attr; } private static OdfName addNamespaceToDom(OdfName name, OdfFileDom dom) { OdfNamespace newNS = dom.setNamespace(name.getPrefix(), name.getUri()); return OdfName.newName(newNS, name.getLocalName()); } /** * @param dom the XML DOM file where the node should be created on. * @param nodeClass being an XMLNode the Java class of the instance to be created. * @return an object instance of the XML node class being provided (usally an attribute or element). */ static Object getNodeFromClass(OdfFileDom dom, Class nodeClass) { Object o = null; try { Constructor ctor = nodeClass.getConstructor(new Class[]{OdfFileDom.class}); o = ctor.newInstance(new Object[]{dom}); } catch (Exception cause) { // an exception at this point is a bug. Throw an Error throw new Error("ODF DOM error in attribute factory", cause); } return o; } }
42.255738
131
0.72036
494cd292dbb45257583661eea12b53513cb78a9f
2,717
package havis.net.ui.core.client.log.config; import java.util.Date; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiConstructor; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.TakesValue; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.Widget; import havis.net.ui.shared.client.list.WidgetList; import havis.net.ui.shared.client.widgets.LoadingSpinner; import havis.net.ui.shared.client.widgets.Util; import havis.net.ui.shared.resourcebundle.ConstantsResource; public class LogConfigSection extends Composite implements LogConfigView { @UiField WidgetList configureList; LoadingSpinner spinner = new LoadingSpinner(); ConstantsResource cons = ConstantsResource.INSTANCE; private static LogConfigSectionUiBinder uiBinder = GWT.create(LogConfigSectionUiBinder.class); interface LogConfigSectionUiBinder extends UiBinder<Widget, LogConfigSection> { } @UiConstructor public LogConfigSection() { initWidget(uiBinder.createAndBindUi(this)); } @Override public void setPresenter(Presenter presenter) { } @Override public WidgetList getConfigurationList() { return configureList; } private TakesValue<Boolean> executing = new TakesValue<Boolean>() { Timer timer = new Timer() { @Override public void run() { spinner.hide(); } }; private long time = 0; private int value = 0; @Override public synchronized void setValue(Boolean value) { if (timer.isRunning()) { timer.cancel(); } if (value) { time = new Date().getTime() + 500; spinner.getElement().getStyle().setDisplay(Display.BLOCK); spinner.setPopupPositionAndShow(new PopupPanel.PositionCallback() { @Override public void setPosition(int offsetWidth, int offsetHeight) { int scrollTop = Util.getContentScrollTop(); int innerHeight = Util.getWindowParentInnerHeight(); int top = scrollTop + innerHeight / 2 - offsetHeight / 2; int left = (Window.getClientWidth() - offsetWidth) / 2; spinner.setPopupPosition(left, top); } }); this.value++; } else { this.value--; if (this.value < 1) { this.value = 0; long remaining = time - new Date().getTime(); timer.schedule((int) (remaining > 0 ? remaining : 0)); } } } @Override public Boolean getValue() { return value > 0; } }; @Override public TakesValue<Boolean> getExecuting() { return executing; } }
25.632075
95
0.724696
c84d82aa49b760236000e74a28cf1fc53fe2915a
10,161
package com.sap.olingo.jpa.processor.core.query; import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ATTRIBUTE_NOT_FOUND; import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_NOT_ALLOWED_MEMBER; import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST; import static org.apache.olingo.commons.api.http.HttpStatusCode.FORBIDDEN; import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.From; import javax.persistence.criteria.Order; import javax.persistence.criteria.Path; import org.apache.olingo.server.api.ODataApplicationException; import org.apache.olingo.server.api.uri.UriInfoResource; import org.apache.olingo.server.api.uri.UriResource; import org.apache.olingo.server.api.uri.UriResourceComplexProperty; import org.apache.olingo.server.api.uri.UriResourceCount; import org.apache.olingo.server.api.uri.UriResourceNavigation; import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; import org.apache.olingo.server.api.uri.UriResourceProperty; import org.apache.olingo.server.api.uri.queryoption.OrderByItem; import org.apache.olingo.server.api.uri.queryoption.OrderByOption; import org.apache.olingo.server.api.uri.queryoption.expression.Expression; import org.apache.olingo.server.api.uri.queryoption.expression.Member; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; import com.sap.olingo.jpa.processor.core.exception.ODataJPANotImplementedException; import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException; /** * Constructor of Order By clause. * @author Oliver Grande * @since 1.0.0 */ class JPAOrderByBuilder { private final JPAEntityType jpaEntity; private final From<?, ?> target; private final CriteriaBuilder cb; private final List<String> groups; JPAOrderByBuilder(final JPAEntityType jpaEntity, final From<?, ?> target, final CriteriaBuilder cb, final List<String> groups) { super(); this.jpaEntity = jpaEntity; this.target = target; this.cb = cb; this.groups = groups; } /** * Create a list of oder by for the root (non $expand) query part. Beside the $orderby query option, it also take $top * and $skip into account. SO that for the later once a stable sorting is guaranteed.<p> * If asc or desc is not specified, the service MUST order by the specified property in ascending order. * See: <a href= * "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398305" * >OData Version 4.0 Part 1 - 11.2.5.2 System Query Option $orderby</a> <p> * * Some OData example requests:<br> * .../Organizations?$orderby=Address/Country --> one item, two resourcePaths * [...ComplexProperty,...PrimitiveProperty]<br> * .../Organizations?$orderby=Roles/$count --> one item, two resourcePaths [...NavigationProperty,...Count]<br> * .../Organizations?$orderby=Roles/$count desc,Address/Country asc -->two items <p> * SQL example to order by number of entities<br> * <code> * SELECT t0."BusinessPartnerID" ,COUNT(t1."BusinessPartnerID")<br> * FROM "OLINGO"."org.apache.olingo.jpa::BusinessPartner" t0 <br> * LEFT OUTER JOIN "OLINGO"."org.apache.olingo.jpa::BusinessPartnerRole" t1 <br> * ON (t1."BusinessPartnerID" = t0."BusinessPartnerID")} v * WHERE (t0."Type" = ?)<br> * GROUP BY t0."BusinessPartnerID"<br> * ORDER BY COUNT(t1."BusinessPartnerID") DESC<br> * </code> * @since 1.0.0 * @param joinTables * @param uriResource * @return A list of generated orderby clauses * @throws ODataApplicationException */ @Nonnull List<Order> createOrderByList(@Nonnull final Map<String, From<?, ?>> joinTables, @Nonnull final UriInfoResource uriResource) throws ODataApplicationException { final List<Order> result = new ArrayList<>(); try { if (uriResource.getOrderByOption() != null) { addOrderByFromUriResource(joinTables, result, uriResource.getOrderByOption()); } if (uriResource.getTopOption() != null || uriResource.getSkipOption() != null) { addOrderByPrimaryKey(result); } } catch (final ODataJPAModelException e) { throw new ODataJPAQueryException(e, BAD_REQUEST); } return result; } @Nonnull List<Order> createOrderByList(final Map<String, From<?, ?>> joinTables) { return Collections.emptyList(); } private void addOrderByExpression(final List<Order> orders, final OrderByItem orderByItem, final javax.persistence.criteria.Expression<?> expression) { if (orderByItem.isDescending()) orders.add(cb.desc(expression)); else orders.add(cb.asc(expression)); } private void addOrderByFromUriResource(final Map<String, From<?, ?>> joinTables, final List<Order> orders, final OrderByOption orderByOption) throws ODataJPAProcessException, ODataJPAModelException { for (final OrderByItem orderByItem : orderByOption.getOrders()) { final Expression expression = orderByItem.getExpression(); if (expression instanceof Member) { final UriInfoResource resourcePath = ((Member) expression).getResourcePath(); JPAStructuredType type = jpaEntity; Path<?> p = target; final StringBuilder externalPath = new StringBuilder(); for (final UriResource uriResourceItem : resourcePath.getUriResourceParts()) { if (isPrimitiveSimpleProperty(uriResourceItem)) { p = convertPropertyPath(type, uriResourceItem, p); addOrderByExpression(orders, orderByItem, p); } else if (isComplexSimpleProperty(uriResourceItem)) { final JPAAttribute attribute = getAttribute(type, uriResourceItem); addPathByAttribute(externalPath, attribute); p = p.get(attribute.getInternalName()); type = attribute.getStructuredType(); } else if (uriResourceItem instanceof UriResourceNavigation || (uriResourceItem instanceof UriResourceProperty && ((UriResourceProperty) uriResourceItem).isCollection())) { // In case the orderby contains a navigation or collection a $count has to follow. This is ensured by Olingo appendPathByCollection(externalPath, uriResourceItem); final From<?, ?> join = joinTables.get(externalPath.toString()); addOrderByExpression(orders, orderByItem, cb.count(join)); } else if (!(uriResourceItem instanceof UriResourceCount)) { throw new ODataJPANotImplementedException("orderby using " + uriResourceItem.getKind().name()); } } } } } private Path<?> convertPropertyPath(final JPAStructuredType type, final UriResource uriResourceItem, final Path<?> p) throws ODataJPAQueryException, ODataJPAProcessorException, ODataJPAModelException { final JPAPath attributePath = type.getPath(((UriResourceProperty) uriResourceItem).getProperty().getName()); if (attributePath == null) throw new ODataJPAProcessorException(ATTRIBUTE_NOT_FOUND, INTERNAL_SERVER_ERROR, uriResourceItem.getSegmentValue()); if (!attributePath.isPartOfGroups(groups)) throw new ODataJPAQueryException(QUERY_PREPARATION_NOT_ALLOWED_MEMBER, FORBIDDEN, attributePath.getAlias()); Path<?> path = p; for (final JPAElement pathElement : attributePath.getPath()) { path = path.get(pathElement.getInternalName()); } return path; } private void addOrderByPrimaryKey(final List<Order> orders) throws ODataJPAModelException { for (final JPAPath keyPath : jpaEntity.getKeyPath()) { final Path<?> p = target; for (final JPAElement pathElement : keyPath.getPath()) { p.get(pathElement.getInternalName()); } orders.add(cb.asc(p)); } } private void addPathByAttribute(final StringBuilder externalPath, final JPAAttribute attribute) { externalPath.append(attribute.getExternalName()); externalPath.append(JPAPath.PATH_SEPERATOR); } private void appendPathByCollection(final StringBuilder externalPath, final UriResource uriResourceItem) { if (uriResourceItem instanceof UriResourceNavigation) externalPath.append(((UriResourceNavigation) uriResourceItem).getProperty().getName()); else externalPath.append(((UriResourceProperty) uriResourceItem).getProperty().getName()); } private JPAAttribute getAttribute(final JPAStructuredType type, final UriResource uriResourceItem) throws ODataJPAProcessorException, ODataJPAModelException, ODataJPAQueryException { final JPAAttribute attribute = type.getAttribute((UriResourceProperty) uriResourceItem); if (attribute == null) throw new ODataJPAProcessorException(ATTRIBUTE_NOT_FOUND, INTERNAL_SERVER_ERROR, uriResourceItem.getSegmentValue()); return attribute; } private boolean isComplexSimpleProperty(final UriResource uriResourceItem) { return uriResourceItem instanceof UriResourceComplexProperty && !((UriResourceProperty) uriResourceItem).isCollection(); } private boolean isPrimitiveSimpleProperty(final UriResource uriResourceItem) { return uriResourceItem instanceof UriResourcePrimitiveProperty && !((UriResourceProperty) uriResourceItem).isCollection(); } }
45.977376
152
0.742742
345efbbf1e9139d29012c185f6205f032f8c8a72
1,314
/* * To the extent possible under law, the ImageJ developers have waived * all copyright and related or neighboring rights to this tutorial code. * * See the CC0 1.0 Universal license for details: * http://creativecommons.org/publicdomain/zero/1.0/ */ package foo; import ij.IJ; import ij.ImageJ; import ij.plugin.PlugIn; import net.imagej.ImageJService; import net.imagej.tensorflow.TensorFlowService; import org.scijava.Context; import org.scijava.service.SciJavaService; public class TensorFlow_Test implements PlugIn { private TensorFlowService tfService; @Override public void run(String arg) { boolean newContext = false; Context ctx = (Context) IJ.runPlugIn("org.scijava.Context", ""); if (ctx == null) { ctx = new Context(ImageJService.class, SciJavaService.class); newContext = true; } tfService = ctx.service(TensorFlowService.class); IJ.log("TensorFlow loaded? " + tfService.getStatus().isLoaded()); tfService.initialize(); tfService.loadLibrary(); IJ.log("TensorFlow loaded now? " + tfService.getStatus().isLoaded()); if (newContext) ctx.dispose(); // we made it, we clean it up } public static void main(String[] args) throws Exception { // start ImageJ new ImageJ(); // run the plugin IJ.runPlugIn(TensorFlow_Test.class.getName(), ""); } }
26.28
73
0.726027
0d1ba6030e114cd866c8aec27232f549cd9bb1ca
1,283
package org.puc.rio.inf1636.hglm.war.objective; import org.puc.rio.inf1636.hglm.war.model.Map; import org.puc.rio.inf1636.hglm.war.model.Player; import org.puc.rio.inf1636.hglm.war.model.Territory; public class ConquerTerritoriesObjective extends WarObjective { int numberOfTerritoriesToConquer; int numberOfArmiesInEach; public ConquerTerritoriesObjective(int numberOfTerritoriesToConquer, int numberOfArmiesInEach) { super( String.format( "Conquer %d territories and occupy them with at least %d armies.", numberOfTerritoriesToConquer, numberOfArmiesInEach)); this.numberOfTerritoriesToConquer = numberOfTerritoriesToConquer; this.numberOfArmiesInEach = numberOfArmiesInEach; } @Override public boolean checkVictory(Map m, Player p) { int numberOfTerritoriesOwnedWithCondition = 0; for (Territory t : m.getTerritories()) { if (t.getOwnerName().equals(p.getName()) && t.getArmyCount() >= this.numberOfArmiesInEach) { numberOfTerritoriesOwnedWithCondition++; } } return numberOfTerritoriesOwnedWithCondition >= this.numberOfTerritoriesToConquer; } public int getNumberOfArmiesInEach() { return this.numberOfArmiesInEach; } public int getNumberOfTerritoriesToConquer() { return numberOfTerritoriesToConquer; } }
29.159091
84
0.781761
9035927c067aa427ffe4dbbf02a24f7f28b82676
337
import java.io.*; public class Main { public static void main(){ try { TableHachage t=new TableHachage(); t.remplitTableHachage("test"); t.afficheTableHachage(); } catch(IOException e) { System.out.println("Erreur"); } } }
17.736842
46
0.477745
1cba753c7e4d2d0c97bb750c9e7f350659990c9c
1,125
package org.knowm.xchart.demo.charts.dial; import org.knowm.xchart.DialChart; import org.knowm.xchart.DialChartBuilder; import org.knowm.xchart.SwingWrapper; import org.knowm.xchart.demo.charts.ExampleChart; /** * Dial Chart * * <p>Demonstrates the following: * * <ul> * <li>Dial Chart * <li>DialChartBuilder */ public class DialChart01 implements ExampleChart<DialChart> { public static void main(String[] args) { ExampleChart<DialChart> exampleChart = new DialChart01(); DialChart chart = exampleChart.getChart(); new SwingWrapper<>(chart).displayChart(); } @Override public DialChart getChart() { // Create Chart DialChart chart = new DialChartBuilder().width(800).height(600).title(getClass().getSimpleName()).build(); // Series chart.addSeries("Rate", 0.9381, "93.81 %"); chart.getStyler().setToolTipsEnabled(true); chart.getStyler().setLabelVisible(true); chart.getStyler().setLegendVisible(false); return chart; } @Override public String getExampleChartName() { return getClass().getSimpleName() + " - Basic Dial Chart"; } }
23.93617
96
0.698667
65d8748919b9615e529549f3f28239e6448f56b8
28,820
package io.github.tavernaextras.biocatalogue.integration; /* * 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. */ import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.JComponent; import javax.swing.JLabel; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import org.biocatalogue.x2009.xml.rest.ResourceLink; import org.biocatalogue.x2009.xml.rest.RestMethod; import org.biocatalogue.x2009.xml.rest.RestService; import org.biocatalogue.x2009.xml.rest.Service; import org.biocatalogue.x2009.xml.rest.ServiceTechnologyType; import org.biocatalogue.x2009.xml.rest.SoapOperation; import org.biocatalogue.x2009.xml.rest.SoapService; import org.biocatalogue.x2009.xml.rest.Service.Variants; import io.github.tavernaextras.biocatalogue.model.HTTPMethodInterpreter; import io.github.tavernaextras.biocatalogue.model.HTTPMethodInterpreter.UnsupportedHTTPMethodException; import io.github.tavernaextras.biocatalogue.model.Resource; import io.github.tavernaextras.biocatalogue.model.Resource.TYPE; import io.github.tavernaextras.biocatalogue.model.connectivity.BioCatalogueClient; import io.github.tavernaextras.biocatalogue.model.ResourceManager; import io.github.tavernaextras.biocatalogue.model.SoapOperationIdentity; import io.github.tavernaextras.biocatalogue.model.SoapOperationPortIdentity; import io.github.tavernaextras.biocatalogue.model.SoapProcessorIdentity; import io.github.tavernaextras.biocatalogue.model.Util; import org.apache.taverna.activities.rest.RESTActivity; import org.apache.taverna.activities.rest.RESTActivity.HTTP_METHOD; import org.apache.taverna.activities.wsdl.WSDLActivity; import org.apache.taverna.activities.wsdl.servicedescriptions.WSDLServiceDescription; import org.apache.taverna.ui.menu.ContextualSelection; import io.github.tavernaextras.biocatalogue.MainComponentFactory; import io.github.tavernaextras.biocatalogue.integration.service_panel.BioCatalogueRESTServiceProvider; import io.github.tavernaextras.biocatalogue.integration.service_panel.BioCatalogueWSDLOperationServiceProvider; import io.github.tavernaextras.biocatalogue.integration.service_panel.RESTFromBioCatalogueServiceDescription; import io.github.tavernaextras.biocatalogue.integration.service_panel.WSDLOperationFromBioCatalogueServiceDescription; import org.apache.taverna.workbench.file.FileManager; import org.apache.taverna.workbench.ui.workflowview.WorkflowView; import org.apache.taverna.workflowmodel.Dataflow; import org.apache.taverna.workflowmodel.Port; import org.apache.taverna.workflowmodel.Processor; import org.apache.taverna.workflowmodel.processor.activity.Activity; import org.apache.taverna.workflowmodel.processor.activity.ActivityInputPort; import org.apache.taverna.workflowmodel.processor.activity.ActivityOutputPort; import org.apache.taverna.workflowmodel.utils.Tools; /** * This class contains helpers for deeper integration with Taverna UI. * * @author Sergejs Aleksejevs */ public class Integration { private static final Logger logger = Logger.getLogger(Integration.class); // deny instantiation of this class private Integration() { } /** * Adds a processor to the current workflow. * The processor is specified by WSDL location and the operation name. * * @param processorResource Resource to add to the current workflow. * @return Outcome of inserting the processor into the current workflow as a * HTML-formatted string (with no opening and closing HTML tags). */ public static JComponent insertProcessorIntoCurrentWorkflow(ResourceLink processorResource) { // check if this type of resource can be added to workflow diagram TYPE resourceType = Resource.getResourceTypeFromResourceURL(processorResource.getHref()); if (resourceType.isSuitableForAddingToWorkflowDiagram()) { switch (resourceType) { case SOAPOperation: SoapOperation soapOp = (SoapOperation) processorResource; try { SoapService soapService = BioCatalogueClient.getInstance(). getBioCatalogueSoapService(soapOp.getAncestors().getSoapService().getHref()); try { WSDLServiceDescription myServiceDescription = new WSDLServiceDescription(); myServiceDescription.setOperation(soapOp.getName()); myServiceDescription.setUse("literal"); // or "encoded" myServiceDescription.setStyle("document"); // or "rpc" myServiceDescription.setURI(new URI(soapService.getWsdlLocation())); myServiceDescription.setDescription(StringEscapeUtils.escapeHtml(soapService.getDescription())); // TODO - not sure where this is used if (WorkflowView.importServiceDescription(myServiceDescription, false) != null) { return (new JLabel("Selected " + TYPE.SOAPOperation.getTypeName() + " was successfully added to the current workflow", ResourceManager.getImageIcon(ResourceManager.TICK_ICON), JLabel.CENTER)); } else { return (new JLabel("<html><center>Taverna was unable to add selected " + TYPE.SOAPOperation.getTypeName() + " as a service to the current workflow.<br>This could be because the service is currently not accessible.</center></html>", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } } catch (URISyntaxException e) { logger.error("Couldn't add " + TYPE.SOAPOperation + " to the current workflow", e); return (new JLabel("<html>Could not add the selected " + TYPE.SOAPOperation.getTypeName() + " to the current workflow.<br>" + "Log file will containt additional details about this error.</html>", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } } catch (Exception e) { logger.error("Failed to fetch required details to add this " + TYPE.SOAPOperation + " into the current workflow.", e); return (new JLabel("<html>Failed to fetch required details to add this<br>" + TYPE.SOAPOperation.getTypeName() + " into the current workflow.</html>", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } case RESTMethod: // received object may only contain limited data, therefore need to fetch full details first try { RestMethod restMethod = BioCatalogueClient.getInstance(). getBioCatalogueRestMethod(processorResource.getHref()); // actual import of the service into the workflow RESTFromBioCatalogueServiceDescription restServiceDescription = createRESTServiceDescriptionFromRESTMethod(restMethod); WorkflowView.importServiceDescription(restServiceDescription, false); // prepare result of the operation to be shown in the the waiting dialog window String warnings = extractWarningsFromRESTServiceDescription(restServiceDescription, false); JLabel outcomes = new JLabel("<html>Selected " + TYPE.RESTMethod.getTypeName() + " was successfully added to the current workflow" + warnings + "</html>", ResourceManager.getImageIcon(warnings.length() > 0 ? ResourceManager.WARNING_ICON : ResourceManager.TICK_ICON), JLabel.CENTER); outcomes.setIconTextGap(20); return (outcomes); } catch (UnsupportedHTTPMethodException e) { logger.error(e); return (new JLabel(e.getMessage(), ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } catch (Exception e) { logger.error("Failed to fetch required details to add this " + TYPE.RESTMethod + " as a service to the current workflow.", e); return (new JLabel("<html>Failed to fetch required details to add this " + TYPE.RESTMethod.getTypeName() + "<br>" + "as a service to the current workflow.</html>", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } // type not currently supported, but maybe in the future? default: return (new JLabel("Adding " + resourceType.getCollectionName() + " to the current workflow is not yet possible", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } } // definitely not supported type return (new JLabel("<html>It is not possible to add resources of the provided type<br>" + "into the current workflow.</html>", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } /** * * @param processorResource * @return Outcome of inserting the processor into the current workflow as a * HTML-formatted string (with no opening and closing HTML tags). */ public static JComponent insertProcesorIntoServicePanel(ResourceLink processorResource) { // check if this type of resource can be added to Service Panel TYPE resourceType = Resource.getResourceTypeFromResourceURL(processorResource.getHref()); if (resourceType.isSuitableForAddingToServicePanel()) { switch (resourceType) { case SOAPOperation: SoapOperation soapOp = (SoapOperation) processorResource; try { SoapService soapService = BioCatalogueClient.getInstance(). getBioCatalogueSoapService(soapOp.getAncestors().getSoapService().getHref()); SoapOperationIdentity soapOpId = new SoapOperationIdentity(soapService.getWsdlLocation(), soapOp.getName(), StringEscapeUtils.escapeHtml(soapOp.getDescription())); WSDLOperationFromBioCatalogueServiceDescription wsdlOperationDescription = new WSDLOperationFromBioCatalogueServiceDescription(soapOpId); BioCatalogueWSDLOperationServiceProvider.registerWSDLOperation(wsdlOperationDescription, null); return (new JLabel("Selected SOAP operation has been successfully added to the Service Panel.", ResourceManager.getImageIcon(ResourceManager.TICK_ICON), JLabel.CENTER)); } catch (Exception e) { logger.error("Failed to fetch required details to add this SOAP service into the Service Panel.", e); return (new JLabel("Failed to fetch required details to add this " + "SOAP service into the Service Panel.", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } case RESTMethod: try { // received object may only contain limited data, therefore need to fetch full details first RestMethod restMethod = BioCatalogueClient.getInstance(). getBioCatalogueRestMethod(processorResource.getHref()); RESTFromBioCatalogueServiceDescription restServiceDescription = createRESTServiceDescriptionFromRESTMethod(restMethod); // actual insertion of the REST method into Service Panel BioCatalogueRESTServiceProvider.registerNewRESTMethod(restServiceDescription, null); // prepare result of the operation to be shown in the the waiting dialog window String warnings = extractWarningsFromRESTServiceDescription(restServiceDescription, true); JLabel outcomes = new JLabel("<html>Selected REST method has been successfully added to the Service Panel" + warnings + "</html>", ResourceManager.getImageIcon(warnings.length() > 0 ? ResourceManager.WARNING_ICON : ResourceManager.TICK_ICON), JLabel.CENTER); outcomes.setIconTextGap(20); return (outcomes); } catch (UnsupportedHTTPMethodException e) { logger.error(e); return (new JLabel(e.getMessage(), ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } catch (Exception e) { logger.error("Failed to fetch required details to add this REST service into the Service Panel.", e); return (new JLabel("Failed to fetch required details to add this " + "REST service into the Service Panel.", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } // type not currently supported, but maybe in the future? default: return (new JLabel("Adding " + resourceType.getCollectionName() + " to the Service Panel is not yet possible", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } } // definitely not supported type return (new JLabel("<html>It is not possible to add resources of the provided type<br>" + "into the Service Panel.</html>", ResourceManager.getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } /** * Inserts all operations of the given parent SOAP or REST Web service resource link * into Service Panel. Works for SOAP operations only at the moment. * * @return Outcome of inserting operations into Service Panel as a * HTML-formatted string (with no opening and closing HTML tags). */ public static JComponent insertAllOperationsIntoServicePanel(ResourceLink serviceResource) { // Check if this type of resource is a parent SOAP Web service // whose operations can be added to the Service Panel TYPE resourceType = Resource .getResourceTypeFromResourceURL(serviceResource.getHref()); Service service = null; if (resourceType == TYPE.SOAPOperation) { SoapService soapService = ((SoapOperation) serviceResource) .getAncestors().getSoapService(); // Get the WSDL URL of the SOAP service String wsdlURL = soapService.getWsdlLocation(); // Import this WSDL into Service panel - it will add all // of // its operations if (BioCatalogueWSDLOperationServiceProvider.registerWSDLService( wsdlURL, null)) { return (new JLabel( "Operation(s) of the SOAP service have been successfully added to the Service Panel.", ResourceManager.getImageIcon(ResourceManager.TICK_ICON), JLabel.CENTER)); } else { return (new JLabel( "Failed to insert the operations of the SOAP service " + " to the Service Panel.", ResourceManager .getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } } else if (resourceType == TYPE.RESTMethod) { RestService restService = ((RestMethod) serviceResource) .getAncestors().getRestService(); for (RestMethod method : restService.getMethods().getRestMethodList()) { } } return (new JLabel( "<html>It is not possible to add resources of the provided type<br>" + "into the Service Panel.</html>", ResourceManager .getImageIcon(ResourceManager.ERROR_ICON), JLabel.CENTER)); } /** * Instantiates a {@link RESTFromBioCatalogueServiceDescription} object from the {@link RestMethod} * XML data obtained from BioCatalogue API. * * @param restMethod * @return */ public static RESTFromBioCatalogueServiceDescription createRESTServiceDescriptionFromRESTMethod(RestMethod restMethod) throws UnsupportedHTTPMethodException { // if the type of the HTTP method is not supported, an exception will be throws HTTP_METHOD httpMethod = HTTPMethodInterpreter.getHTTPMethodForRESTActivity(restMethod.getHttpMethodType()); RESTFromBioCatalogueServiceDescription restServiceDescription = new RESTFromBioCatalogueServiceDescription(); restServiceDescription.setServiceName(Resource.getDisplayNameForResource(restMethod)); restServiceDescription.setDescription(StringEscapeUtils.escapeHtml(restMethod.getDescription())); restServiceDescription.setHttpMethod(httpMethod); restServiceDescription.setURLSignature(restMethod.getUrlTemplate()); int outputRepresentationCount = restMethod.getOutputs().getRepresentations().getRestRepresentationList().size(); if (outputRepresentationCount > 0) { if (outputRepresentationCount > 1) { restServiceDescription.getDataWarnings().add(RESTFromBioCatalogueServiceDescription.AMBIGUOUS_ACCEPT_HEADER_VALUE); } restServiceDescription.setAcceptHeaderValue(restMethod.getOutputs().getRepresentations().getRestRepresentationList().get(0).getContentType()); } else { restServiceDescription.getDataWarnings().add(RESTFromBioCatalogueServiceDescription.DEFAULT_ACCEPT_HEADER_VALUE); } int inputRepresentationCount = restMethod.getInputs().getRepresentations().getRestRepresentationList().size(); if (inputRepresentationCount > 0) { if (inputRepresentationCount > 1) { restServiceDescription.getDataWarnings().add(RESTFromBioCatalogueServiceDescription.AMBIGUOUS_CONTENT_TYPE_HEADER_VALUE); } restServiceDescription.setOutgoingContentType(restMethod.getInputs().getRepresentations().getRestRepresentationList().get(0).getContentType()); } else if (RESTActivity.hasMessageBodyInputPort(httpMethod)) { restServiceDescription.getDataWarnings().add(RESTFromBioCatalogueServiceDescription.DEFAULT_CONTENT_TYPE_HEADER_VALUE); } return (restServiceDescription); } /** * @param restServiceDescription {@link RESTFromBioCatalogueServiceDescription} to process. * @param addingToServicePanel <code>true</code> indicates that the warning messages * will assume that the processor is added to the service panel; * <code>false</code> would mean that the processor is added to * the current workflow. * @return An HTML-formatted string (with no opening-closing HTML tags) that lists * any warnings that have been recorded during the {@link RESTFromBioCatalogueServiceDescription} * object creation. Empty string will be returned if there are no warnings. */ public static String extractWarningsFromRESTServiceDescription(RESTFromBioCatalogueServiceDescription restServiceDescription, boolean addingToServicePanel) { String messageSuffix = addingToServicePanel ? " once you add it into the workflow" : ""; String warnings = ""; if (restServiceDescription.getDataWarnings().contains(RESTFromBioCatalogueServiceDescription.AMBIGUOUS_ACCEPT_HEADER_VALUE)) { warnings += "<br><br>Service Catalogue description of this REST method contains more than one<br>" + "representation of the method's outputs - the first one was used.<br>" + "Please check value of the 'Accept' header in the configuration<br>" + "of the imported service" + messageSuffix + "."; } else if (restServiceDescription.getDataWarnings().contains(RESTFromBioCatalogueServiceDescription.DEFAULT_ACCEPT_HEADER_VALUE)) { warnings += "<br><br>Service Catalogue description of this REST method does not contain any<br>" + "representations of the method's outputs - default value was used.<br>" + "Please check value of the 'Accept' header in the configuration<br>" + "of the imported service" + messageSuffix + "."; } if (restServiceDescription.getDataWarnings().contains(RESTFromBioCatalogueServiceDescription.AMBIGUOUS_CONTENT_TYPE_HEADER_VALUE)) { warnings += "<br><br>Service Catalogue description of this REST method contains more than one<br>" + "representation of the method's input data - the first one was used.<br>" + "Please check value of the 'Content-Type' header in the configuration<br>" + "of the imported service" + messageSuffix + "."; } else if (restServiceDescription.getDataWarnings().contains(RESTFromBioCatalogueServiceDescription.DEFAULT_CONTENT_TYPE_HEADER_VALUE)) { warnings += "<br><br>Service Catalogue description of this REST method does not contain any<br>" + "representations of the method's input data - default value was used.<br>" + "Please check value of the 'Content-Type' header in the configuration<br>" + "of the imported service" + messageSuffix + "."; } if (warnings.length() > 0) { warnings = "<br><br>WARNINGS:" + warnings; } return (warnings); } /** * @param activityPort Probably comes from contextual selection - must be either * ActivityInputPort or ActivityOutputPort. * @return SOAP input / output port details (WSDL location, operation name, port name) from * ActivityInputPort/ActivityOutputPort which is obtained from contextual selection in the Dataflow. */ public static <T extends Port> SoapOperationPortIdentity extractSoapOperationPortDetailsFromActivityInputOutputPort(T activityPort) { // check that we have the correct instance of Port here - either ActivityInputPort or ActivityOutputPort boolean hasInputPort; if (activityPort instanceof ActivityInputPort) { hasInputPort = true; } else if (activityPort instanceof ActivityOutputPort) { hasInputPort = false; } else { // ERROR - wrong type supplied return new SoapOperationPortIdentity("Activity port from the contextual selection was not of correct type. Impossible to create preview."); } // get parent processor details Dataflow currentDataflow = FileManager.getInstance().getCurrentDataflow(); Collection<Processor> processors = null; if (hasInputPort) { processors = Tools.getProcessorsWithActivityInputPort(currentDataflow, (ActivityInputPort)activityPort); } else { processors = Tools.getProcessorsWithActivityOutputPort(currentDataflow, (ActivityOutputPort)activityPort); } // TODO - doesn't take into account that it's possible to have several SoapOperationIdentity soapOperationDetails = extractSoapOperationDetailsFromProcessor(processors.toArray(new Processor[]{})[0]); // if no error happened, add port details and return if (!soapOperationDetails.hasError()) { return (new SoapOperationPortIdentity(soapOperationDetails.getWsdlLocation(), soapOperationDetails.getOperationName(), activityPort.getName(), hasInputPort)); } else { // error... return (new SoapOperationPortIdentity(soapOperationDetails.getErrorDetails())); } } /** * Uses contextual selection to extract WSDL location and operation name of the * currently selected processor within the Design view of current workflow. * * @param contextualSelection Selection that was made in the Design view. * @return Details of the SOAP operation that acts as a processor wrapped into * this single instance. If any problems occurred while performing * contextual selection analysis, these are also recorded into the same * instance - before using the returned value the caller must check * <code>SoapOperationIdentity.hasError()</code> value. */ public static SoapOperationIdentity extractSoapOperationDetailsFromProcessorContextualSelection(ContextualSelection contextualSelection) { if (!(contextualSelection.getSelection() instanceof Processor)) { return (new SoapOperationIdentity("ERROR: It is only possible to extract " + "SOAP operation details from the service.")); } // now we know it's a Processor Processor processor = (Processor)contextualSelection.getSelection(); return (extractSoapOperationDetailsFromProcessor(processor)); } /** * Worker method for <code>extractSoapOperationDetailsFromProcessorContextualSelection()</code>. * * @param processor * @return */ public static SoapOperationIdentity extractSoapOperationDetailsFromProcessor(Processor processor) { List<? extends Activity> activityList = (List<? extends Activity>) processor.getActivityList(); if (activityList == null || activityList.size() == 0) { return (new SoapOperationIdentity("ERROR: Selected processor doesn't have any activities - " + "impossible to extract SOAP operation details.")); } else { // take only the first activity - TODO: figure out what should be done here... Activity activity = activityList.get(0); if (activity instanceof WSDLActivity) { WSDLActivity a = (WSDLActivity)activity; return (new SoapOperationIdentity(a.getConfiguration().getWsdl(), a.getConfiguration().getOperation(), null)); } else { return (new SoapOperationIdentity("Service Catalogue integration only works with WSDL Activities at the moment")); } } } /** * @param contextualSelection * @return A list of all WSDL activities (the only supported processors by BioCatalogue plugin for now). */ public static List<SoapProcessorIdentity> extractSupportedProcessorsFromDataflow(ContextualSelection contextualSelection) { // check that there was a correct contextual selection if (!(contextualSelection.getSelection() instanceof Dataflow)) { logger.error("It is only possible to extract supported services from the workflow."); return (new ArrayList<SoapProcessorIdentity>()); } // first extract all processors Dataflow dataflow = (Dataflow)contextualSelection.getSelection(); List<? extends Processor> allProcessors = dataflow.getEntities(Processor.class); // now filter out any processors that are not WSDL activities List<SoapProcessorIdentity> supportedProcessors = new ArrayList<SoapProcessorIdentity>(); for (Processor proc : allProcessors) { List<? extends Activity> activityList = (List<? extends Activity>) proc.getActivityList(); if (activityList != null && activityList.size() > 0) { // take only the first activity - TODO: figure out what should be done here... Activity activity = activityList.get(0); if (activity instanceof WSDLActivity) { WSDLActivity a = (WSDLActivity)activity; supportedProcessors.add(new SoapProcessorIdentity(a.getConfiguration().getWsdl(), a.getConfiguration().getOperation(), proc.getLocalName())); } } } // return all found processors return (supportedProcessors); } }
53.869159
176
0.681194
9964b3cddcdc05db68d268fa3879aef317e8af6d
1,006
package com.core.string; import java.util.Scanner; public class EmptyTest { public static void main(String[] args) { String s1=""; String s2=""; String s3="a"; String s4=new String (); String s5=new String (""); String s6=new String(""); String s7=new String ("a"); System.out.println("Is S1 Empty "+s1.isEmpty()); System.out.println("Is S2 Empty "+s2.isEmpty()); System.out.println("Is S3 Empty "+s3.isEmpty()); System.out.println("Is S4 Empty "+s4.isEmpty()); System.out.println("Is S5 Empty "+s5.isEmpty()); System.out.println("Is S6 Empty "+s6.isEmpty()); System.out.println("Is S7 Empty "+s7.isEmpty()); /*String s8=null; System.out.println("Is S8 is "+s8.isEmpty()); String s9; System.out.println("Is s9 Empty "s9.isEmpty());*/ Scanner sc=new Scanner(System.in); System.out.println("Enter A String : "); System.out.println(sc.nextLine().isEmpty()); System.out.println("Enter B String : "); System.out.println(sc.nextLine().isEmpty()); } }
30.484848
87
0.653082
6e1209e7dec69b96827e74c46e748e975ba9ff9f
53,905
package us.ihmc.euclid.tools; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Random; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.IntConsumer; import org.junit.jupiter.api.Test; import us.ihmc.euclid.Axis2D; import us.ihmc.euclid.Axis3D; import us.ihmc.euclid.matrix.Matrix3D; import us.ihmc.euclid.matrix.RotationMatrix; import us.ihmc.euclid.matrix.interfaces.Matrix3DReadOnly; import us.ihmc.euclid.matrix.interfaces.RotationMatrixBasics; import us.ihmc.euclid.matrix.interfaces.RotationMatrixReadOnly; import us.ihmc.euclid.transform.RigidBodyTransform; import us.ihmc.euclid.tuple2D.Point2D; import us.ihmc.euclid.tuple2D.UnitVector2D; import us.ihmc.euclid.tuple2D.Vector2D; import us.ihmc.euclid.tuple2D.interfaces.Point2DBasics; import us.ihmc.euclid.tuple2D.interfaces.Point2DReadOnly; import us.ihmc.euclid.tuple2D.interfaces.Tuple2DReadOnly; import us.ihmc.euclid.tuple2D.interfaces.UnitVector2DBasics; import us.ihmc.euclid.tuple2D.interfaces.UnitVector2DReadOnly; import us.ihmc.euclid.tuple2D.interfaces.Vector2DBasics; import us.ihmc.euclid.tuple2D.interfaces.Vector2DReadOnly; import us.ihmc.euclid.tuple3D.Point3D; import us.ihmc.euclid.tuple3D.UnitVector3D; import us.ihmc.euclid.tuple3D.Vector3D; import us.ihmc.euclid.tuple3D.interfaces.Point3DBasics; import us.ihmc.euclid.tuple3D.interfaces.Point3DReadOnly; import us.ihmc.euclid.tuple3D.interfaces.Tuple3DBasics; import us.ihmc.euclid.tuple3D.interfaces.Tuple3DReadOnly; import us.ihmc.euclid.tuple3D.interfaces.UnitVector3DBasics; import us.ihmc.euclid.tuple3D.interfaces.UnitVector3DReadOnly; import us.ihmc.euclid.tuple3D.interfaces.Vector3DBasics; import us.ihmc.euclid.tuple3D.interfaces.Vector3DReadOnly; import us.ihmc.euclid.tuple4D.Quaternion; import us.ihmc.euclid.tuple4D.interfaces.QuaternionBasics; import us.ihmc.euclid.tuple4D.interfaces.QuaternionReadOnly; import us.ihmc.euclid.tuple4D.interfaces.Tuple4DReadOnly; public class EuclidCoreFactoriesTest { private static final int ITERATIONS = 1000; private static final double EPSILON = 1.0e-12; @Test public void testNewLinkedPoint2DReadOnly() { Random random = new Random(5416); { // Test newLinkedPoint2DReadOnly(DoubleSupplier scaleSupplier, Tuple2DReadOnly originalTuple) double[] scale = new double[1]; Point2D originalTuple = new Point2D(); Point2DReadOnly actual = EuclidCoreFactories.newLinkedPoint2DReadOnly(() -> scale[0], originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextPoint2D(random)); scale[0] = random.nextDouble(); Point2D expected = new Point2D(); expected.setAndScale(scale[0], originalTuple); thoroughAssertionsTuple2D(expected, actual); } } { // Test newLinkedPoint2DReadOnly(DoubleSupplier xSupplier, DoubleSupplier ySupplier) Point2D expected = new Point2D(); Point2DReadOnly actual = EuclidCoreFactories.newLinkedPoint2DReadOnly(expected::getX, expected::getY); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextPoint2D(random)); thoroughAssertionsTuple2D(expected, actual); } } } @Test public void testNewLinkedVector2DReadOnly() { Random random = new Random(5416); { // Test newLinkedVector2DReadOnly(DoubleSupplier scaleSupplier, Tuple2DReadOnly originalTuple) double[] scale = new double[1]; Vector2D originalTuple = new Vector2D(); Vector2DReadOnly actual = EuclidCoreFactories.newLinkedVector2DReadOnly(() -> scale[0], originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextVector2D(random)); scale[0] = random.nextDouble(); Vector2D expected = new Vector2D(); expected.setAndScale(scale[0], originalTuple); thoroughAssertionsTuple2D(expected, actual); } } { // Test newLinkedVector2DReadOnly(DoubleSupplier xSupplier, DoubleSupplier ySupplier) Vector2D expected = new Vector2D(); Vector2DReadOnly actual = EuclidCoreFactories.newLinkedVector2DReadOnly(expected::getX, expected::getY); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextVector2D(random)); thoroughAssertionsTuple2D(expected, actual); } } } @Test public void testNewLinkedPoint3DReadOnly() { Random random = new Random(5416); { // Test newLinkedPoint3DReadOnly(DoubleSupplier scaleSupplier, Tuple3DReadOnly originalTuple) double[] scale = new double[1]; Point3D originalTuple = new Point3D(); Point3DReadOnly actual = EuclidCoreFactories.newLinkedPoint3DReadOnly(() -> scale[0], originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextPoint3D(random)); scale[0] = random.nextDouble(); Point3D expected = new Point3D(); expected.setAndScale(scale[0], originalTuple); thoroughAssertionsTuple3D(expected, actual); } } { // Test newLinkedPoint3DReadOnly(DoubleSupplier xSupplier, DoubleSupplier ySupplier, DoubleSupplier zSupplier) Point3D expected = new Point3D(); Point3DReadOnly actual = EuclidCoreFactories.newLinkedPoint3DReadOnly(expected::getX, expected::getY, expected::getZ); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextPoint3D(random)); thoroughAssertionsTuple3D(expected, actual); } } } @Test public void testNewLinkedVector3DReadOnly() { Random random = new Random(5416); { // Test newLinkedVector3DReadOnly(DoubleSupplier scaleSupplier, Tuple3DReadOnly originalTuple) double[] scale = new double[1]; Vector3D originalTuple = new Vector3D(); Vector3DReadOnly actual = EuclidCoreFactories.newLinkedVector3DReadOnly(() -> scale[0], originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextVector3D(random)); scale[0] = random.nextDouble(); Vector3D expected = new Vector3D(); expected.setAndScale(scale[0], originalTuple); thoroughAssertionsTuple3D(expected, actual); } } { // Test newLinkedVector3DReadOnly(DoubleSupplier xSupplier, DoubleSupplier ySupplier) Vector3D expected = new Vector3D(); Vector3DReadOnly actual = EuclidCoreFactories.newLinkedVector3DReadOnly(expected::getX, expected::getY, expected::getZ); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextVector3D(random)); thoroughAssertionsTuple3D(expected, actual); } } } @Test public void testNewNegativeLinkedPoint2D() { Random random = new Random(43); { // Test newNegativeLinkedPoint2D(Point2DReadOnly originalPoint) Point2D originalTuple = new Point2D(); Point2DReadOnly actual = EuclidCoreFactories.newNegativeLinkedPoint2D(originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextPoint2D(random)); Point2D expected = new Point2D(); expected.setAndNegate(originalTuple); thoroughAssertionsTuple2D(expected, actual); } } } @Test public void testNewNegativeLinkedVector2D() { Random random = new Random(43); { // Test newNegativeLinkedVector2D(Vector2DReadOnly originalVector) Vector2D originalTuple = new Vector2D(); Vector2DReadOnly actual = EuclidCoreFactories.newNegativeLinkedVector2D(originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextVector2D(random)); Vector2D expected = new Vector2D(); expected.setAndNegate(originalTuple); thoroughAssertionsTuple2D(expected, actual); } } } @Test public void testNewNegativeLinkedPoint3D() { Random random = new Random(43); { // Test newNegativeLinkedPoint3D(Point3DReadOnly originalPoint) Point3D originalTuple = new Point3D(); Point3DReadOnly actual = EuclidCoreFactories.newNegativeLinkedPoint3D(originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextPoint3D(random)); Point3D expected = new Point3D(); expected.setAndNegate(originalTuple); thoroughAssertionsTuple3D(expected, actual); } } } @Test public void testNewNegativeLinkedVector3D() { Random random = new Random(43); { // Test newNegativeLinkedVector3D(Vector3DReadOnly originalVector) Vector3D originalTuple = new Vector3D(); Vector3DReadOnly actual = EuclidCoreFactories.newNegativeLinkedVector3D(originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextVector3D(random)); Vector3D expected = new Vector3D(); expected.setAndNegate(originalTuple); thoroughAssertionsTuple3D(expected, actual); } } } @Test public void testNewNegativeLinkedUnitVector2D() { Random random = new Random(389); { // Test newNegativeLinkedUnitVector2D(UnitVector2DReadOnly originalUnitVector) UnitVector2D originalVector = EuclidCoreRandomTools.nextUnitVector2D(random); UnitVector2DReadOnly actual = EuclidCoreFactories.newNegativeLinkedUnitVector2D(originalVector); for (int i = 0; i < ITERATIONS; i++) { originalVector.set(EuclidCoreRandomTools.nextUnitVector2D(random)); UnitVector2D expected = new UnitVector2D(); expected.setAndNegate(originalVector); thoroughAssertionsTuple2D(expected, actual); assertEquals(expected.getRawX(), actual.getRawX()); assertEquals(expected.getRawY(), actual.getRawY()); assertEquals(originalVector.isDirty(), actual.isDirty()); originalVector.setX(1.0); assertTrue(originalVector.isDirty()); assertTrue(actual.isDirty()); actual.getX(); // Trigger normalization assertFalse(actual.isDirty()); assertFalse(originalVector.isDirty()); } } } @Test public void testNewNegativeLinkedUnitVector3D() { Random random = new Random(389); { // Test newNegativeLinkedUnitVector3D(UnitVector3DReadOnly originalUnitVector) UnitVector3D originalVector = EuclidCoreRandomTools.nextUnitVector3D(random); UnitVector3DReadOnly actual = EuclidCoreFactories.newNegativeLinkedUnitVector3D(originalVector); for (int i = 0; i < ITERATIONS; i++) { originalVector.set(EuclidCoreRandomTools.nextUnitVector3D(random)); UnitVector3D expected = new UnitVector3D(); expected.setAndNegate(originalVector); thoroughAssertionsTuple3D(expected, actual); assertEquals(expected.getRawX(), actual.getRawX()); assertEquals(expected.getRawY(), actual.getRawY()); assertEquals(expected.getRawZ(), actual.getRawZ()); assertEquals(originalVector.isDirty(), actual.isDirty()); originalVector.setX(1.0); assertTrue(originalVector.isDirty()); assertTrue(actual.isDirty()); actual.getX(); // Trigger normalization assertFalse(actual.isDirty()); assertFalse(originalVector.isDirty()); } } } @Test public void testNewConjugateLinkedQuaternion() { Random random = new Random(349653); { // Test newConjugateLinkedQuaternion(QuaternionReadOnly original) Quaternion originalQuaternion = EuclidCoreRandomTools.nextQuaternion(random); QuaternionReadOnly actual = EuclidCoreFactories.newConjugateLinkedQuaternion(originalQuaternion); for (int i = 0; i < ITERATIONS; i++) { originalQuaternion.set(EuclidCoreRandomTools.nextQuaternion(random)); Quaternion expected = new Quaternion(); expected.setAndConjugate(originalQuaternion); thoroughAssertionsTuple4D(expected, actual); } } } @Test public void testNewTransposeLinkedMatrix3DReadOnly() { Random random = new Random(43634677); { // Test newTransposeLinkedMatrix3DReadOnly(Matrix3DBasics original) Matrix3D originalMatrix = new Matrix3D(); Matrix3DReadOnly actual = EuclidCoreFactories.newTransposeLinkedMatrix3DReadOnly(originalMatrix); for (int i = 0; i < ITERATIONS; i++) { originalMatrix.set(EuclidCoreRandomTools.nextMatrix3D(random)); Matrix3D expected = new Matrix3D(); expected.setAndTranspose(originalMatrix); thoroughAssertionsMatrix3D(expected, actual); } } } @Test public void testNewTildeLinkedMatrix3DReadOnly() { Random random = new Random(43634677); { // Test newTildeLinkedMatrix3DReadOnly(Matrix3DBasics original) Tuple3DBasics originalTuple = new Point3D(); Matrix3DReadOnly actual = EuclidCoreFactories.newTildeLinkedMatrix3DReadOnly(originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextPoint3D(random)); Matrix3D expected = new Matrix3D(); expected.setToTildeForm(originalTuple); thoroughAssertionsMatrix3D(expected, actual); } } } @Test public void testNewDiagonalLinkedMatrix3DReadOnly() { Random random = new Random(43634677); { // Test newDiagonalLinkedMatrix3DReadOnly(Matrix3DBasics original) Tuple3DBasics originalTuple = new Point3D(); Matrix3DReadOnly actual = EuclidCoreFactories.newDiagonalLinkedMatrix3DReadOnly(originalTuple); for (int i = 0; i < ITERATIONS; i++) { originalTuple.set(EuclidCoreRandomTools.nextPoint3D(random)); Matrix3D expected = new Matrix3D(); expected.setToDiagonal(originalTuple); thoroughAssertionsMatrix3D(expected, actual); } } } @Test public void testNewObservablePoint2DReadOnly() { Random random = new Random(45); { // Test simple update operation. Point2D expected = EuclidCoreRandomTools.nextPoint2D(random); Point2D source = new Point2D(); Consumer<Axis2D> valueAccessedListener = axis -> source.setElement(axis, expected.getElement(axis)); Point2DReadOnly observable = EuclidCoreFactories.newObservablePoint2DReadOnly(valueAccessedListener, source); EuclidCoreTestTools.assertTuple2DIsSetToZero(source); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); thoroughAssertionsTuple2D(expected, observable); } { // Test transform operation. Point2D expected = EuclidCoreRandomTools.nextPoint2D(random); Point2D source = new Point2D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis2D> valueAccessedListener = axis -> transform.transform(source, false); Point2DReadOnly observable = EuclidCoreFactories.newObservablePoint2DReadOnly(valueAccessedListener, source); transform.transform(expected, false); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected, false); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); } } @Test public void testNewObservableVector2DReadOnly() { Random random = new Random(45); { // Test simple update operation. Vector2D expected = EuclidCoreRandomTools.nextVector2D(random); Vector2D source = new Vector2D(); Consumer<Axis2D> valueAccessedListener = axis -> source.setElement(axis, expected.getElement(axis)); Vector2DReadOnly observable = EuclidCoreFactories.newObservableVector2DReadOnly(valueAccessedListener, source); EuclidCoreTestTools.assertTuple2DIsSetToZero(source); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); thoroughAssertionsTuple2D(expected, observable); } { // Test transform operation. Vector2D expected = EuclidCoreRandomTools.nextVector2D(random); Vector2D source = new Vector2D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis2D> valueAccessedListener = axis -> transform.transform(source, false); Vector2DReadOnly observable = EuclidCoreFactories.newObservableVector2DReadOnly(valueAccessedListener, source); transform.transform(expected, false); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected, false); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); } } @Test public void testNewObservablePoint3DReadOnly() { Random random = new Random(45); { // Test simple update operation. Point3D expected = EuclidCoreRandomTools.nextPoint3D(random); Point3D source = new Point3D(); Consumer<Axis3D> valueAccessedListener = axis -> source.setElement(axis, expected.getElement(axis)); Point3DReadOnly observable = EuclidCoreFactories.newObservablePoint3DReadOnly(valueAccessedListener, source); EuclidCoreTestTools.assertTuple3DIsSetToZero(source); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); thoroughAssertionsTuple3D(expected, observable); } { // Test transform operation. Point3D expected = EuclidCoreRandomTools.nextPoint3D(random); Point3D source = new Point3D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis3D> valueAccessedListener = axis -> transform.transform(source); Point3DReadOnly observable = EuclidCoreFactories.newObservablePoint3DReadOnly(valueAccessedListener, source); transform.transform(expected); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); transform.transform(expected); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); } } @Test public void testNewObservableUnitVector2DReadOnly() { Random random = new Random(45); { // Test simple update operation. UnitVector2D expected = EuclidCoreRandomTools.nextUnitVector2D(random); UnitVector2D source = new UnitVector2D(); Consumer<Axis2D> valueAccessedListener = axis -> source.set(expected); UnitVector2DReadOnly observable = EuclidCoreFactories.newObservableUnitVector2DReadOnly(valueAccessedListener, source); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); thoroughAssertionsTuple2D(expected, observable); } { // Test transform operation. UnitVector2D expected = EuclidCoreRandomTools.nextUnitVector2D(random); UnitVector2D source = new UnitVector2D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis2D> valueAccessedListener = axis -> transform.transform(source, false); UnitVector2DReadOnly observable = EuclidCoreFactories.newObservableUnitVector2DReadOnly(valueAccessedListener, source); transform.transform(expected, false); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected, false); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); } } @Test public void testNewObservableVector3DReadOnly() { Random random = new Random(45); { // Test simple update operation. Vector3D expected = EuclidCoreRandomTools.nextVector3D(random); Vector3D source = new Vector3D(); Consumer<Axis3D> valueAccessedListener = axis -> source.setElement(axis, expected.getElement(axis)); Vector3DReadOnly observable = EuclidCoreFactories.newObservableVector3DReadOnly(valueAccessedListener, source); EuclidCoreTestTools.assertTuple3DIsSetToZero(source); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); thoroughAssertionsTuple3D(expected, observable); } { // Test transform operation. Vector3D expected = EuclidCoreRandomTools.nextVector3D(random); Vector3D source = new Vector3D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis3D> valueAccessedListener = axis -> transform.transform(source); Vector3DReadOnly observable = EuclidCoreFactories.newObservableVector3DReadOnly(valueAccessedListener, source); transform.transform(expected); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); transform.transform(expected); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); } } @Test public void testNewObservableUnitVector3DReadOnly() { Random random = new Random(45); { // Test simple update operation. UnitVector3D expected = EuclidCoreRandomTools.nextUnitVector3D(random); UnitVector3D source = new UnitVector3D(); Consumer<Axis3D> valueAccessedListener = axis -> source.set(expected); UnitVector3DReadOnly observable = EuclidCoreFactories.newObservableUnitVector3DReadOnly(valueAccessedListener, source); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); thoroughAssertionsTuple3D(expected, observable); } { // Test transform operation. UnitVector3D expected = EuclidCoreRandomTools.nextUnitVector3D(random); UnitVector3D source = new UnitVector3D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis3D> valueAccessedListener = axis -> transform.transform(source); UnitVector3DReadOnly observable = EuclidCoreFactories.newObservableUnitVector3DReadOnly(valueAccessedListener, source); transform.transform(expected); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); transform.transform(expected); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); } } @Test public void testNewObservableRotationMatrixReadOnly() { Random random = new Random(45); { // Test simple update operation. RotationMatrix expected = EuclidCoreRandomTools.nextRotationMatrix(random); RotationMatrix source = new RotationMatrix(); BiConsumer<Axis3D, Axis3D> valueAccessedListener = (row, col) -> source.set(expected); RotationMatrixReadOnly observable = EuclidCoreFactories.newObservableRotationMatrixReadOnly(valueAccessedListener, source); assertTrue(source.isIdentity()); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { assertEquals(expected.getElement(row, col), observable.getElement(row, col)); assertEquals(expected.getElement(row, col), source.getElement(row, col)); } } thoroughAssertionsMatrix3D(expected, observable); } { // Test transform operation. RotationMatrix expected = EuclidCoreRandomTools.nextRotationMatrix(random); RotationMatrix source = new RotationMatrix(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); BiConsumer<Axis3D, Axis3D> valueAccessedListener = (row, col) -> transform.transform(source); RotationMatrixReadOnly observable = EuclidCoreFactories.newObservableRotationMatrixReadOnly(valueAccessedListener, source); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { transform.transform(expected); assertEquals(expected.getElement(row, col), observable.getElement(row, col)); assertEquals(expected.getElement(row, col), source.getElement(row, col)); } } } } @Test public void testNewObservableQuaternionReadOnly() { Random random = new Random(45); { // Test simple update operation. Quaternion expected = EuclidCoreRandomTools.nextQuaternion(random); Quaternion source = new Quaternion(); IntConsumer valueAccessedListener = index -> source.set(expected); QuaternionReadOnly observable = EuclidCoreFactories.newObservableQuaternionReadOnly(valueAccessedListener, source); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); thoroughAssertionsTuple4D(expected, observable); } { // Test transform operation. Quaternion expected = EuclidCoreRandomTools.nextQuaternion(random); Quaternion source = new Quaternion(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); IntConsumer valueAccessedListener = index -> transform.transform(source); QuaternionReadOnly observable = EuclidCoreFactories.newObservableQuaternionReadOnly(valueAccessedListener, source); transform.transform(expected); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); transform.transform(expected); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); } } @Test public void testNewObservablePoint2DBasics() { Random random = new Random(4367); { // Test the link property with the source Point2D expected = new Point2D(); Point2DBasics actual = EuclidCoreFactories.newObservablePoint2DBasics(null, null, expected); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextPoint2D(random)); thoroughAssertionsTuple2D(expected, actual); actual.set(EuclidCoreRandomTools.nextPoint2D(random)); thoroughAssertionsTuple2D(expected, actual); } } { // Test with simple notification flags boolean[] changeTrace = {false, false}; boolean[] accessTrace = {false, false}; Point2DBasics source = new Point2D(); Point2DBasics observable = EuclidCoreFactories.newObservablePoint2DBasics((axis, newValue) -> changeTrace[axis.ordinal()] = true, axis -> accessTrace[axis.ordinal()] = true, source); assertAllFalses(changeTrace); assertAllFalses(accessTrace); for (int i = 0; i < 2; i++) { double value = random.nextDouble(); observable.setElement(i, value); assertTrue(changeTrace[i]); changeTrace[i] = false; observable.setElement(i, value); assertFalse(changeTrace[i]); assertAllFalses(changeTrace); assertAllFalses(accessTrace); observable.getElement(i); assertTrue(accessTrace[i]); accessTrace[i] = false; assertAllFalses(changeTrace); assertAllFalses(accessTrace); } } { // Test transform operation. Point2D expected = EuclidCoreRandomTools.nextPoint2D(random); Point2D source = new Point2D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis2D> valueAccessedListener = axis -> transform.transform(source, false); Point2DBasics observable = EuclidCoreFactories.newObservablePoint2DBasics(null, valueAccessedListener, source); transform.transform(expected, false); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected, false); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); } } @Test public void testNewObservableVector2DBasics() { Random random = new Random(4367); { // Test the link property with the source Vector2D expected = new Vector2D(); Vector2DBasics actual = EuclidCoreFactories.newObservableVector2DBasics(null, null, expected); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextVector2D(random)); thoroughAssertionsTuple2D(expected, actual); actual.set(EuclidCoreRandomTools.nextVector2D(random)); thoroughAssertionsTuple2D(expected, actual); } } { // Test with simple notification flags boolean[] changeTrace = {false, false}; boolean[] accessTrace = {false, false}; Vector2DBasics source = new Vector2D(); Vector2DBasics observable = EuclidCoreFactories.newObservableVector2DBasics((axis, newValue) -> changeTrace[axis.ordinal()] = true, axis -> accessTrace[axis.ordinal()] = true, source); assertAllFalses(changeTrace); assertAllFalses(accessTrace); for (int i = 0; i < 2; i++) { double value = random.nextDouble(); observable.setElement(i, value); assertTrue(changeTrace[i]); changeTrace[i] = false; observable.setElement(i, value); assertFalse(changeTrace[i]); assertAllFalses(changeTrace); assertAllFalses(accessTrace); observable.getElement(i); assertTrue(accessTrace[i]); accessTrace[i] = false; assertAllFalses(changeTrace); assertAllFalses(accessTrace); } } { // Test transform operation. Vector2D expected = EuclidCoreRandomTools.nextVector2D(random); Vector2D source = new Vector2D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis2D> valueAccessedListener = axis -> transform.transform(source, false); Vector2DBasics observable = EuclidCoreFactories.newObservableVector2DBasics(null, valueAccessedListener, source); transform.transform(expected, false); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected, false); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); } } @Test public void testNewObservablePoint3DBasics() { Random random = new Random(4367); { // Test the link property with the source Point3D expected = new Point3D(); Point3DBasics actual = EuclidCoreFactories.newObservablePoint3DBasics(null, null, expected); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextPoint3D(random)); thoroughAssertionsTuple3D(expected, actual); actual.set(EuclidCoreRandomTools.nextPoint3D(random)); thoroughAssertionsTuple3D(expected, actual); } } { // Test with simple notification flags boolean[] changeTrace = {false, false, false}; boolean[] accessTrace = {false, false, false}; Point3DBasics source = new Point3D(); Point3DBasics observable = EuclidCoreFactories.newObservablePoint3DBasics((axis, newValue) -> changeTrace[axis.ordinal()] = true, axis -> accessTrace[axis.ordinal()] = true, source); assertAllFalses(changeTrace); assertAllFalses(accessTrace); for (int i = 0; i < 3; i++) { double value = random.nextDouble(); observable.setElement(i, value); assertTrue(changeTrace[i]); changeTrace[i] = false; observable.setElement(i, value); assertFalse(changeTrace[i]); assertAllFalses(changeTrace); assertAllFalses(accessTrace); observable.getElement(i); assertTrue(accessTrace[i]); accessTrace[i] = false; assertAllFalses(changeTrace); assertAllFalses(accessTrace); } } { // Test transform operation. Point3D expected = EuclidCoreRandomTools.nextPoint3D(random); Point3D source = new Point3D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis3D> valueAccessedListener = axis -> transform.transform(source); Point3DBasics observable = EuclidCoreFactories.newObservablePoint3DBasics(null, valueAccessedListener, source); transform.transform(expected); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); transform.transform(expected); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); } } @Test public void testNewObservableVector3DBasics() { Random random = new Random(4367); { // Test the link property with the source Vector3D expected = new Vector3D(); Vector3DBasics actual = EuclidCoreFactories.newObservableVector3DBasics(null, null, expected); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextVector3D(random)); thoroughAssertionsTuple3D(expected, actual); actual.set(EuclidCoreRandomTools.nextVector3D(random)); thoroughAssertionsTuple3D(expected, actual); } } { // Test with simple notification flags boolean[] changeTrace = {false, false, false}; boolean[] accessTrace = {false, false, false}; Vector3DBasics source = new Vector3D(); Vector3DBasics observable = EuclidCoreFactories.newObservableVector3DBasics((axis, newValue) -> changeTrace[axis.ordinal()] = true, axis -> accessTrace[axis.ordinal()] = true, source); assertAllFalses(changeTrace); assertAllFalses(accessTrace); for (int i = 0; i < 3; i++) { double value = random.nextDouble(); observable.setElement(i, value); assertTrue(changeTrace[i]); changeTrace[i] = false; observable.setElement(i, value); assertFalse(changeTrace[i]); assertAllFalses(changeTrace); assertAllFalses(accessTrace); observable.getElement(i); assertTrue(accessTrace[i]); accessTrace[i] = false; assertAllFalses(changeTrace); assertAllFalses(accessTrace); } } { // Test transform operation. Vector3D expected = EuclidCoreRandomTools.nextVector3D(random); Vector3D source = new Vector3D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis3D> valueAccessedListener = axis -> transform.transform(source); Vector3DBasics observable = EuclidCoreFactories.newObservableVector3DBasics(null, valueAccessedListener, source); transform.transform(expected); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); transform.transform(expected); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); } } @Test public void testNewObservableUnitVector2DBasics() { Random random = new Random(4367); { // Test the link property with the source UnitVector2D expected = new UnitVector2D(); UnitVector2DBasics actual = EuclidCoreFactories.newObservableUnitVector2DBasics(null, null, expected); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextUnitVector2D(random)); thoroughAssertionsTuple2D(expected, actual); actual.set(EuclidCoreRandomTools.nextUnitVector2D(random)); thoroughAssertionsTuple2D(expected, actual); } } { // Test with simple notification flags boolean[] changeTrace = {false, false}; boolean[] accessTrace = {false, false}; UnitVector2DBasics source = new UnitVector2D(); UnitVector2DBasics observable = EuclidCoreFactories.newObservableUnitVector2DBasics((axis, newValue) -> changeTrace[axis.ordinal()] = true, axis -> accessTrace[axis.ordinal()] = true, source); assertAllFalses(changeTrace); assertAllFalses(accessTrace); for (int i = 0; i < 2; i++) { double value = random.nextDouble(); observable.setElement(i, value); assertTrue(changeTrace[i]); changeTrace[i] = false; observable.setElement(i, value); assertFalse(changeTrace[i]); assertAllFalses(changeTrace); assertAllFalses(accessTrace); observable.getElement(i); assertTrue(accessTrace[i]); accessTrace[i] = false; assertAllFalses(changeTrace); assertAllFalses(accessTrace); } } { // Test transform operation. UnitVector2D expected = EuclidCoreRandomTools.nextUnitVector2D(random); UnitVector2D source = new UnitVector2D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis2D> valueAccessedListener = axis -> transform.transform(source, false); UnitVector2DBasics observable = EuclidCoreFactories.newObservableUnitVector2DBasics(null, valueAccessedListener, source); transform.transform(expected, false); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected, false); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); } } @Test public void testNewObservableUnitVector3DBasics() { Random random = new Random(4367); { // Test the link property with the source UnitVector3D expected = new UnitVector3D(); UnitVector3DBasics actual = EuclidCoreFactories.newObservableUnitVector3DBasics(null, null, expected); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextUnitVector3D(random)); thoroughAssertionsTuple3D(expected, actual); actual.set(EuclidCoreRandomTools.nextUnitVector3D(random)); thoroughAssertionsTuple3D(expected, actual); } } { // Test with simple notification flags boolean[] changeTrace = {false, false, false}; boolean[] accessTrace = {false, false, false}; UnitVector3DBasics source = new UnitVector3D(); UnitVector3DBasics observable = EuclidCoreFactories.newObservableUnitVector3DBasics((axis, newValue) -> changeTrace[axis.ordinal()] = true, axis -> accessTrace[axis.ordinal()] = true, source); assertAllFalses(changeTrace); assertAllFalses(accessTrace); for (int i = 0; i < 3; i++) { double value = random.nextDouble(); observable.setElement(i, value); assertTrue(changeTrace[i]); changeTrace[i] = false; observable.setElement(i, value); assertFalse(changeTrace[i]); assertAllFalses(changeTrace); assertAllFalses(accessTrace); observable.getElement(i); assertTrue(accessTrace[i]); accessTrace[i] = false; assertAllFalses(changeTrace); assertAllFalses(accessTrace); } } { // Test transform operation. UnitVector3D expected = EuclidCoreRandomTools.nextUnitVector3D(random); UnitVector3D source = new UnitVector3D(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); Consumer<Axis3D> valueAccessedListener = axis -> transform.transform(source); UnitVector3DBasics observable = EuclidCoreFactories.newObservableUnitVector3DBasics(null, valueAccessedListener, source); transform.transform(expected); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); transform.transform(expected); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); } } @Test public void testNewObservableRotationMatrixBasics() { Random random = new Random(4367); { // Test the link property with the source RotationMatrix expected = new RotationMatrix(); RotationMatrixBasics actual = EuclidCoreFactories.newObservableRotationMatrixBasics(null, null, expected); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextRotationMatrix(random)); thoroughAssertionsMatrix3D(expected, actual); actual.set(EuclidCoreRandomTools.nextRotationMatrix(random)); thoroughAssertionsMatrix3D(expected, actual); } } { // Test with simple notification flags boolean[] changeTrace = {false}; boolean[][] accessTrace = {{false, false, false}, {false, false, false}, {false, false, false}}; RotationMatrixBasics source = EuclidCoreRandomTools.nextRotationMatrix(random); RotationMatrixBasics observable = EuclidCoreFactories.newObservableRotationMatrixBasics(() -> changeTrace[0] = true, (row, col) -> accessTrace[row.ordinal()][col.ordinal()] = true, source); assertAllFalses(changeTrace); assertAllFalses(accessTrace); observable.transpose(); assertTrue(changeTrace[0]); assertAllFalses(accessTrace); changeTrace[0] = false; observable.setToNaN(); assertTrue(changeTrace[0]); assertAllFalses(accessTrace); changeTrace[0] = false; observable.setToZero(); assertTrue(changeTrace[0]); assertAllFalses(accessTrace); changeTrace[0] = false; observable.set(EuclidCoreRandomTools.nextRotationMatrix(random)); assertTrue(changeTrace[0]); assertAllFalses(accessTrace); changeTrace[0] = false; for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { observable.getElement(row, col); assertTrue(accessTrace[row][col]); accessTrace[row][col] = false; assertAllFalses(changeTrace); assertAllFalses(accessTrace); } } } { // Test transform operation. RotationMatrix expected = EuclidCoreRandomTools.nextRotationMatrix(random); RotationMatrix source = new RotationMatrix(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); BiConsumer<Axis3D, Axis3D> valueAccessedListener = (row, col) -> transform.transform(source); RotationMatrixBasics observable = EuclidCoreFactories.newObservableRotationMatrixBasics(null, valueAccessedListener, source); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { transform.transform(expected); assertEquals(expected.getElement(row, col), observable.getElement(row, col)); assertEquals(expected.getElement(row, col), source.getElement(row, col)); } } } } @Test public void testNewObservableQuaternionBasics() { Random random = new Random(4367); { // Test the link property with the source Quaternion expected = new Quaternion(); QuaternionBasics actual = EuclidCoreFactories.newObservableQuaternionBasics(null, null, expected); for (int i = 0; i < ITERATIONS; i++) { expected.set(EuclidCoreRandomTools.nextQuaternion(random)); thoroughAssertionsTuple4D(expected, actual); actual.set(EuclidCoreRandomTools.nextQuaternion(random)); thoroughAssertionsTuple4D(expected, actual); } } { // Test with simple notification flags boolean[] changeTrace = {false}; boolean[] accessTrace = {false, false, false, false}; QuaternionBasics source = new Quaternion(); QuaternionBasics observable = EuclidCoreFactories.newObservableQuaternionBasics(() -> changeTrace[0] = true, index -> accessTrace[index] = true, source); assertAllFalses(changeTrace); assertAllFalses(accessTrace); observable.setToZero(); assertTrue(changeTrace[0]); assertAllFalses(accessTrace); changeTrace[0] = false; observable.set(EuclidCoreRandomTools.nextQuaternion(random)); assertTrue(changeTrace[0]); assertAllFalses(accessTrace); changeTrace[0] = false; for (int i = 0; i < 4; i++) { observable.getElement(i); assertTrue(accessTrace[i]); accessTrace[i] = false; assertAllFalses(changeTrace); assertAllFalses(accessTrace); } } { // Test transform operation. Quaternion expected = EuclidCoreRandomTools.nextQuaternion(random); Quaternion source = new Quaternion(expected); RigidBodyTransform transform = EuclidCoreRandomTools.nextRigidBodyTransform(random); IntConsumer valueAccessedListener = index -> transform.transform(source); QuaternionBasics observable = EuclidCoreFactories.newObservableQuaternionBasics(null, valueAccessedListener, source); transform.transform(expected); assertEquals(expected.getX(), observable.getX()); assertEquals(expected.getX(), source.getX()); transform.transform(expected); assertEquals(expected.getY(), observable.getY()); assertEquals(expected.getY(), source.getY()); transform.transform(expected); assertEquals(expected.getZ(), observable.getZ()); assertEquals(expected.getZ(), source.getZ()); transform.transform(expected); assertEquals(expected.getS(), observable.getS()); assertEquals(expected.getS(), source.getS()); } } public static void assertAllFalses(boolean[] array) { for (int i = 0; i < array.length; i++) assertFalse(array[i]); } public static void assertAllFalses(boolean[][] array) { for (int i = 0; i < array.length; i++) assertAllFalses(array[i]); } public static void thoroughAssertionsTuple2D(Tuple2DReadOnly expected, Tuple2DReadOnly actual) { assertObjectMethods(expected, actual); EuclidCoreTestTools.assertTuple2DEquals(expected, actual, EPSILON); EuclidCoreTestTools.assertTuple2DEquals(actual, expected, EPSILON); } public static void thoroughAssertionsTuple3D(Tuple3DReadOnly expected, Tuple3DReadOnly actual) { assertObjectMethods(expected, actual); EuclidCoreTestTools.assertTuple3DEquals(expected, actual, EPSILON); EuclidCoreTestTools.assertTuple3DEquals(actual, expected, EPSILON); } public static void thoroughAssertionsTuple4D(Tuple4DReadOnly expected, Tuple4DReadOnly actual) { assertObjectMethods(expected, actual); EuclidCoreTestTools.assertTuple4DEquals(expected, actual, EPSILON); EuclidCoreTestTools.assertTuple4DEquals(actual, expected, EPSILON); } public static void thoroughAssertionsMatrix3D(Matrix3DReadOnly expected, Matrix3DReadOnly actual) { assertObjectMethods(expected, actual); EuclidCoreTestTools.assertMatrix3DEquals(expected, actual, EPSILON); EuclidCoreTestTools.assertMatrix3DEquals(actual, expected, EPSILON); } public static void assertObjectMethods(Object expected, Object actual) { assertEquals(expected.hashCode(), actual.hashCode()); assertEquals(expected, actual); assertEquals(actual, expected); assertEquals(expected.toString(), actual.toString()); } }
41.117468
160
0.646842
888f233d341775c4b9924291222961a9a865fb87
1,295
package com.hnlens.fingerchat.sso.dborm.model; public class ApplicationEntity { private String appID = ""; private Integer appType = 0; private String appName = ""; private String homeURL = ""; private String logoutURL = ""; private Integer appState = 0; public String getAppID() { return appID; } public void setAppID(String appID) { this.appID = appID == null ? null : appID.trim(); } public Integer getAppType() { return appType; } public void setAppType(Integer appType) { this.appType = appType; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName == null ? null : appName.trim(); } public String getHomeURL() { return homeURL; } public void setHomeURL(String homeURL) { this.homeURL = homeURL == null ? null : homeURL.trim(); } public String getLogoutURL() { return logoutURL; } public void setLogoutURL(String logoutURL) { this.logoutURL = logoutURL == null ? null : logoutURL.trim(); } public Integer getAppState() { return appState; } public void setAppState(Integer appState) { this.appState = appState; } }
28.152174
69
0.613127
e201b1313414665257f5d59edd0e3b81db8b5f63
2,608
package com.kms.katalon.core.webservice.common; import java.net.URI; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.ProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.protocol.HttpContext; import org.apache.http.util.Args; public class DefaultRedirectStrategy extends LaxRedirectStrategy { private static final int SC_PERMANENT_REDIRECT = 308; @Override public boolean isRedirected( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { Args.notNull(request, "HTTP request"); Args.notNull(response, "HTTP response"); final int statusCode = response.getStatusLine().getStatusCode(); final String method = request.getRequestLine().getMethod(); final Header locationHeader = response.getFirstHeader("location"); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: return isRedirectable(method) && locationHeader != null; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_TEMPORARY_REDIRECT: case SC_PERMANENT_REDIRECT: return isRedirectable(method); case HttpStatus.SC_SEE_OTHER: return true; default: return false; } } public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { URI uri = this.getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { int status = response.getStatusLine().getStatusCode(); HttpUriRequest toReturn = null; if(status == HttpStatus.SC_TEMPORARY_REDIRECT || status == SC_PERMANENT_REDIRECT) { toReturn = RequestBuilder.copy(request).setUri(uri).build(); } else { toReturn = new HttpGet(uri); } return toReturn; } } }
38.925373
129
0.673313
6318cfce606528154fb173480f5c3a04a1228992
582
package cn.tomsnail.snail.core.page; import java.io.Serializable; public class OrderBy implements Serializable{ private String orderName; private String orderType; public String getOrderName() { return orderName; } public void setOrderName(String orderName) { this.orderName = orderName; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public OrderBy(String orderName, String orderType) { super(); this.orderName = orderName; this.orderType = orderType; } }
15.72973
53
0.731959
236600dadd70fcc565130e89a01415044c8e2dc9
329
package com.xwc1125.chain5j.jsonrpc; import com.xwc1125.chain5j.protocol.entity.Request; /** * Description: <br> * * @author xwc1125 <br> * @Copyright: Copyright (c) 2019 <br> * @date 2019-01-04 11:38 <br> */ public interface EthMethod { Request<?, EthBalance> getBalance(String address, String blockParameter); }
19.352941
77
0.699088
f0c5ac641d57beb49fea97d06aeb9ca3d90db277
1,513
/* * Copyright 2016 Hippo B.V. (http://www.onehippo.com) * * 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.hippoecm.hst.pagecomposer.jaxrs.util; import java.util.Map; import javax.jcr.Node; import org.junit.Test; import org.onehippo.repository.mock.MockNodeFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class PageComposerUtilTest { @Test public void getAnnotatedDefaultValues() throws Exception { Node node = MockNodeFactory.fromXml("/org/hippoecm/hst/pagecomposer/jaxrs/services/ContainerItemComponentResourceTest-empty-component.xml"); Map<String, String> defaultAnnotated = PageComposerUtil.getAnnotatedDefaultValues(node); assertTrue(defaultAnnotated.containsKey("parameterOne")); assertEquals(defaultAnnotated.get("parameterOne"), ""); assertTrue(defaultAnnotated.containsKey("parameterTwo")); assertEquals(defaultAnnotated.get("parameterTwo"), "test"); } }
36.902439
148
0.752148
560e8c63a106013740dc69d5e6d13f082d537b42
8,270
// Copyright 2017 Yahoo Inc. // Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms. package com.yahoo.bard.webservice.web.security; import static com.yahoo.bard.webservice.web.security.SecurityErrorMessageFormat.DIMENSION_MISSING_MANDATORY_ROLE; import com.yahoo.bard.webservice.application.AbstractBinderFactory; import com.yahoo.bard.webservice.config.SystemConfig; import com.yahoo.bard.webservice.config.SystemConfigProvider; import com.yahoo.bard.webservice.data.config.ResourceDictionaries; import com.yahoo.bard.webservice.data.dimension.Dimension; import com.yahoo.bard.webservice.data.dimension.DimensionField; import com.yahoo.bard.webservice.util.StreamUtils; import com.yahoo.bard.webservice.web.ApiFilter; import com.yahoo.bard.webservice.web.DataApiRequest; import com.yahoo.bard.webservice.web.FilterOperation; import com.yahoo.bard.webservice.web.RequestMapper; import com.yahoo.bard.webservice.web.RequestValidationException; import com.yahoo.bard.webservice.web.filters.ApiFilters; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.Principal; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; /** * A request mapper that ensures that a user has at least one relevant role on a dimension and applies access filters * based on roles for that user. * This mapper is intended to route based on user-category style roles such as routing super-user access to a * different mapping chain. */ public class RoleDimensionApiFilterRequestMapper extends ChainingRequestMapper<DataApiRequest> { private static final SystemConfig SYSTEM_CONFIG = SystemConfigProvider.getInstance(); private static final Logger LOG = LoggerFactory.getLogger(AbstractBinderFactory.class); public static final String SECURITY_SIGNUP_MESSAGE_KEY = "security_signup_message"; public static final String DEFAULT_SECURITY_MESSAGE = "Your security settings do not permit access to this " + "resource. Please contact your user administration for access."; private final static String UNAUTHORIZED_USER_MESSAGE = SYSTEM_CONFIG.getStringProperty( SYSTEM_CONFIG.getPackageVariableName(SECURITY_SIGNUP_MESSAGE_KEY), DEFAULT_SECURITY_MESSAGE ); private final String unauthorizedHttpMessage; private Dimension dimension; private Map<String, Set<ApiFilter>> roleApiFilters; /** * Constructor. * * @param resourceDictionaries The dictionaries to use for request mapping. * @param dimension The dimension whose roles are being matched * @param roleApiFilters ApiFilters by role for a given dimension * @param next The next request mapper to process this ApiRequest */ public RoleDimensionApiFilterRequestMapper( final ResourceDictionaries resourceDictionaries, Dimension dimension, Map<String, Set<ApiFilter>> roleApiFilters, RequestMapper<DataApiRequest> next ) { super(resourceDictionaries, next); this.dimension = dimension; this.roleApiFilters = roleApiFilters; unauthorizedHttpMessage = DIMENSION_MISSING_MANDATORY_ROLE.format(dimension.getApiName()); } @Override protected DataApiRequest internalApply(DataApiRequest request, ContainerRequestContext context) throws RequestValidationException { SecurityContext securityContext = context.getSecurityContext(); Set<ApiFilter> securityFilters = buildSecurityFilters(securityContext); validateSecurityFilters(securityContext.getUserPrincipal(), securityFilters); ApiFilters revisedFilters = mergeSecurityFilters(request.getApiFilters(), securityFilters); return request.withFilters(revisedFilters); } /** * Merge the request filters with the dimension filters for this request. * * @param requestFilters The set of all ApiFilters from a request * @param securityFilters The filters produced by merging role-based filters * * @return A set of request filters supplemented with filters from this request. */ protected ApiFilters mergeSecurityFilters( Map<Dimension, Set<ApiFilter>> requestFilters, Set<ApiFilter> securityFilters ) { ApiFilters revisedFilters = new ApiFilters(requestFilters); Set<ApiFilter> requestDimensionFilters = revisedFilters.getOrDefault( dimension, Collections.emptySet() ); // Merge the request filters (if any) with the security filters for this dimension revisedFilters.put( dimension, unionMergeFilterValues(Stream.concat(requestDimensionFilters.stream(), securityFilters.stream())) ); return revisedFilters; } /** * Verify that, given this user, that at least some of the whitelisted filters have been collected. * Failure to have any whitelisted filters indicate a user has not been authorized for values with this dimension. * * @param userPrincipal The userPrincipal being validated * @param mergedSecurityFilters The combined security filters for this request * * @throws RequestValidationException An http request exception documenting the lack of privileges */ protected void validateSecurityFilters(Principal userPrincipal, Set<ApiFilter> mergedSecurityFilters) throws RequestValidationException { if (mergedSecurityFilters.isEmpty()) { LOG.warn(DIMENSION_MISSING_MANDATORY_ROLE.logFormat(userPrincipal.getName(), dimension.getApiName())); throw new RequestValidationException( Response.Status.FORBIDDEN, unauthorizedHttpMessage, UNAUTHORIZED_USER_MESSAGE ); } } /** * Collect all the whitelist filters generated by roles in this security context. * * @param securityContext The security context of the request. * * @return A set of filters whitelisting access to this dimension. */ protected Set<ApiFilter> buildSecurityFilters(final SecurityContext securityContext) { return unionMergeFilterValues( roleApiFilters.keySet().stream() .filter(securityContext::isUserInRole) .map(roleApiFilters::get) .flatMap(Set::stream) ); } /** * For a set of ApiFilters collect by dimension, field and operation, and union their value sets. * * @param filterStream Stream of ApiFilters whose values are to be unioned * * @return A set of filters with the same operations but values unioned */ protected static Set<ApiFilter> unionMergeFilterValues(Stream<ApiFilter> filterStream) { Function<ApiFilter, Triple<Dimension, DimensionField, FilterOperation>> filterGroupingIdentity = filter -> new ImmutableTriple<>(filter.getDimension(), filter.getDimensionField(), filter.getOperation()); Map<Triple<Dimension, DimensionField, FilterOperation>, Set<String>> filterMap = filterStream.collect(Collectors.groupingBy( filterGroupingIdentity::apply, Collectors.mapping( ApiFilter::getValues, Collectors.reducing(Collections.emptySet(), StreamUtils::setMerge) ) )); return filterMap.entrySet().stream() .map(it -> new ApiFilter( it.getKey().getLeft(), it.getKey().getMiddle(), it.getKey().getRight(), it.getValue() )) .collect(Collectors.toSet()); } }
43.298429
118
0.700846
e5cab6c648470c2e28e83291586fe99460e72108
1,785
package com.hazelcast.client; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.QuickTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientRegressionWithRealNetworkTest extends HazelcastTestSupport { @Test public void testClientPortConnection() { final Config config1 = new Config(); config1.getGroupConfig().setName("foo"); config1.getNetworkConfig().setPort(5701); final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config1); instance1.getMap("map").put("key", "value"); final Config config2 = new Config(); config2.getGroupConfig().setName("bar"); config2.getNetworkConfig().setPort(5702); HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(config2); final ClientConfig clientConfig = new ClientConfig(); clientConfig.getGroupConfig().setName("bar"); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final IMap<Object, Object> map = client.getMap("map"); assertNull(map.put("key", "value")); assertEquals(1, map.size()); client.shutdown(); instance1.getLifecycleService().terminate(); instance2.getLifecycleService().terminate(); } }
37.1875
90
0.741737
72b8f493092a3e29e4b9d6bfe722197cbc9f1e39
188
package com.querydsl.jpa.domain7; import java.util.ArrayList; import java.util.List; public class B { public int id; public List<C> c = new ArrayList<C>(); public A a; }
12.533333
42
0.664894
db45f2bade952f3ac8fda7fb3f092f9dbe0b955f
1,161
package quickcarpet.feature; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.fluid.FluidState; import net.minecraft.fluid.Fluids; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.registry.Registry; import java.util.Random; public class ObsidianBlock extends Block { public ObsidianBlock(Settings settings) { super(settings); } @Override public boolean hasRandomTicks(BlockState state) { return quickcarpet.settings.Settings.renewableLava; } @Override @SuppressWarnings("deprecation") public void scheduledTick(BlockState state, ServerWorld world, BlockPos pos, Random random) { for (Direction dir : Direction.values()) { FluidState neighbor = world.getFluidState(pos.offset(dir)); if (neighbor.getFluid() != Fluids.LAVA || !neighbor.isStill()) return; } if (random.nextInt(10) == 0) { world.setBlockState(pos, Blocks.LAVA.getDefaultState()); } } }
31.378378
97
0.712317
556c7491290458fd204a77305efffc24ea27a3dc
610
package pl.sda.filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpFilter; import java.io.IOException; @WebFilter(urlPatterns = "/*") public class IpAddressFilter extends HttpFilter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { System.out.println("Ip address: " + req.getRemoteAddr()); chain.doFilter(req, res); } }
30.5
123
0.772131