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
61585142f99986f3bc1e3f91357c8d0786b3a952
1,714
package org.apache.helix.ipc; /* * 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 io.netty.buffer.ByteBuf; import org.apache.helix.resolver.HelixAddress; import java.util.UUID; /** * Allows message passing among instances in Helix clusters. * <p> * Messages are sent asynchronously using {@link #send}, and handled by callbacks registered via * {@link #registerCallback} * </p> */ public interface HelixIPCService { static final String IPC_PORT = "IPC_PORT"; /** Starts service (must call before {@link #send}) */ void start() throws Exception; /** Shuts down service and releases any resources */ void shutdown() throws Exception; /** Sends a message to one or more instances that map to a cluster scope. */ void send(HelixAddress destination, int messageType, UUID messageId, ByteBuf message); /** Registers a callback for a given message type */ void registerCallback(int messageType, HelixIPCCallback callback); }
34.28
96
0.742707
fba73f0b7efa74cc7c8ca770c5bc2c8b0aa11052
1,901
package models.service.makeShift; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Workbook; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import models.entity.Employee; import models.request.makeShift.ConditionRequest; import net.sf.jett.transform.ExcelTransformer; /** * シフト作成のServicクラス * @author ohbarye */ public class MakeShiftService { /** シフト表テンプレートのパス */ private static final String templatePath = "resources/shift_template.xlsx"; /** シフト表出力先 */ private static final String outPath = "resources/shift.xlsx"; /** * 帳票作成処理 * @param condition * @return */ public static File makeShift(ConditionRequest condition) { try (FileOutputStream fileOut = new FileOutputStream(outPath); InputStream fileIn = new BufferedInputStream(new FileInputStream(templatePath))) { ExcelTransformer transformer = new ExcelTransformer(); Workbook workbook = transformer.transform(fileIn, createParams(condition)); workbook.write(fileOut); fileOut.close(); } catch (IOException e) { e.printStackTrace(); // TODO } catch (InvalidFormatException e) { e.printStackTrace(); // TODO } return new File(outPath); } /** * 帳票テンプレートに渡すパラメータを作成する * @param condition * @return */ private static Map<String, Object> createParams(ConditionRequest condition) { Map<String, Object> params = Maps.newHashMap(); List<Employee> employees = condition.employees; params.put("employees", employees); params.put("openingTime", condition.openingTime); params.put("closingTime", condition.closingTime); return params; } }
25.013158
92
0.742767
7f9986822e4af3bf56a8da0890d74d3d4cfeb85d
35,742
package com.smartdevicelink.proxy; import java.util.Vector; import android.os.Build; import com.smartdevicelink.proxy.rpc.AddCommand; import com.smartdevicelink.proxy.rpc.AddSubMenu; import com.smartdevicelink.proxy.rpc.Alert; import com.smartdevicelink.proxy.rpc.ChangeRegistration; import com.smartdevicelink.proxy.rpc.Choice; import com.smartdevicelink.proxy.rpc.CreateInteractionChoiceSet; import com.smartdevicelink.proxy.rpc.DeleteCommand; import com.smartdevicelink.proxy.rpc.DeleteFile; import com.smartdevicelink.proxy.rpc.DeleteInteractionChoiceSet; import com.smartdevicelink.proxy.rpc.DeleteSubMenu; import com.smartdevicelink.proxy.rpc.DeviceInfo; import com.smartdevicelink.proxy.rpc.EndAudioPassThru; import com.smartdevicelink.proxy.rpc.GetVehicleData; import com.smartdevicelink.proxy.rpc.Image; import com.smartdevicelink.proxy.rpc.ListFiles; import com.smartdevicelink.proxy.rpc.MenuParams; import com.smartdevicelink.proxy.rpc.PerformAudioPassThru; import com.smartdevicelink.proxy.rpc.PerformInteraction; import com.smartdevicelink.proxy.rpc.PutFile; import com.smartdevicelink.proxy.rpc.RegisterAppInterface; import com.smartdevicelink.proxy.rpc.ScrollableMessage; import com.smartdevicelink.proxy.rpc.SdlMsgVersion; import com.smartdevicelink.proxy.rpc.SetAppIcon; import com.smartdevicelink.proxy.rpc.SetDisplayLayout; import com.smartdevicelink.proxy.rpc.SetGlobalProperties; import com.smartdevicelink.proxy.rpc.SetMediaClockTimer; import com.smartdevicelink.proxy.rpc.Show; import com.smartdevicelink.proxy.rpc.Slider; import com.smartdevicelink.proxy.rpc.SoftButton; import com.smartdevicelink.proxy.rpc.Speak; import com.smartdevicelink.proxy.rpc.StartTime; import com.smartdevicelink.proxy.rpc.SubscribeButton; import com.smartdevicelink.proxy.rpc.SubscribeVehicleData; import com.smartdevicelink.proxy.rpc.SystemRequest; import com.smartdevicelink.proxy.rpc.TTSChunk; import com.smartdevicelink.proxy.rpc.UnregisterAppInterface; import com.smartdevicelink.proxy.rpc.UnsubscribeButton; import com.smartdevicelink.proxy.rpc.UnsubscribeVehicleData; import com.smartdevicelink.proxy.rpc.VrHelpItem; import com.smartdevicelink.proxy.rpc.enums.AppHMIType; import com.smartdevicelink.proxy.rpc.enums.AudioType; import com.smartdevicelink.proxy.rpc.enums.BitsPerSample; import com.smartdevicelink.proxy.rpc.enums.ButtonName; import com.smartdevicelink.proxy.rpc.enums.FileType; import com.smartdevicelink.proxy.rpc.enums.ImageType; import com.smartdevicelink.proxy.rpc.enums.InteractionMode; import com.smartdevicelink.proxy.rpc.enums.Language; import com.smartdevicelink.proxy.rpc.enums.RequestType; import com.smartdevicelink.proxy.rpc.enums.SamplingRate; import com.smartdevicelink.proxy.rpc.enums.TextAlignment; import com.smartdevicelink.proxy.rpc.enums.UpdateMode; /** * @deprecated Use RPC constructors directly instead */ @Deprecated public class RPCRequestFactory { public static final int SDL_MSG_MAJOR_VERSION = 1; public static final int SDL_MSG_MINOR_VERSION = 0; public static SystemRequest buildSystemRequest( String data, Integer correlationID) { if(data == null) return null; SystemRequest msg = new SystemRequest(); msg.setRequestType(RequestType.PROPRIETARY); msg.setCorrelationID(correlationID); msg.setBulkData(data.getBytes()); return msg; } public static SystemRequest buildSystemRequestLegacy( Vector<String> data, Integer correlationID) { if(data == null) return null; SystemRequest msg = new SystemRequest(true); msg.setCorrelationID(correlationID); msg.setLegacyData(data); return msg; } public static AddCommand buildAddCommand(Integer commandID, String menuText, Integer parentID, Integer position, Vector<String> vrCommands, Image cmdIcon, Integer correlationID) { AddCommand msg = new AddCommand(); msg.setCorrelationID(correlationID); msg.setCmdID(commandID); msg.setVrCommands(vrCommands); if (cmdIcon != null) msg.setCmdIcon(cmdIcon); if(menuText != null || parentID != null || position != null) { MenuParams menuParams = new MenuParams(); menuParams.setMenuName(menuText); menuParams.setPosition(position); menuParams.setParentID(parentID); msg.setMenuParams(menuParams); } return msg; } public static AddCommand buildAddCommand(Integer commandID, String menuText, Integer parentID, Integer position, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID) { AddCommand msg = new AddCommand(); msg.setCorrelationID(correlationID); msg.setCmdID(commandID); if (vrCommands != null) msg.setVrCommands(vrCommands); Image cmdIcon = null; if (IconValue != null && IconType != null) { cmdIcon = new Image(); cmdIcon.setValue(IconValue); cmdIcon.setImageType(IconType); } if (cmdIcon != null) msg.setCmdIcon(cmdIcon); if(menuText != null || parentID != null || position != null) { MenuParams menuParams = new MenuParams(); menuParams.setMenuName(menuText); menuParams.setPosition(position); menuParams.setParentID(parentID); msg.setMenuParams(menuParams); } return msg; } public static AddCommand buildAddCommand(Integer commandID, String menuText, Integer parentID, Integer position, Vector<String> vrCommands, Integer correlationID) { AddCommand msg = new AddCommand(); msg.setCorrelationID(correlationID); msg.setCmdID(commandID); msg.setVrCommands(vrCommands); if(menuText != null || parentID != null || position != null) { MenuParams menuParams = new MenuParams(); menuParams.setMenuName(menuText); menuParams.setPosition(position); menuParams.setParentID(parentID); msg.setMenuParams(menuParams); } return msg; } public static AddCommand buildAddCommand(Integer commandID, String menuText, Vector<String> vrCommands, Integer correlationID) { AddCommand msg = buildAddCommand(commandID, menuText, null, null, vrCommands, correlationID); return msg; } public static AddCommand buildAddCommand(Integer commandID, Vector<String> vrCommands, Integer correlationID) { AddCommand msg = new AddCommand(); msg.setCorrelationID(correlationID); msg.setCmdID(commandID); msg.setVrCommands(vrCommands); return msg; } public static AddSubMenu buildAddSubMenu(Integer menuID, String menuName, Integer correlationID) { AddSubMenu msg = buildAddSubMenu(menuID, menuName, null, correlationID); return msg; } public static AddSubMenu buildAddSubMenu(Integer menuID, String menuName, Integer position, Integer correlationID) { AddSubMenu msg = new AddSubMenu(); msg.setCorrelationID(correlationID); msg.setMenuName(menuName); msg.setMenuID(menuID); msg.setPosition(position); return msg; } public static Alert buildAlert(String ttsText, Boolean playTone, Vector<SoftButton> softButtons, Integer correlationID) { Vector<TTSChunk> chunks = TTSChunkFactory .createSimpleTTSChunks(ttsText); Alert msg = buildAlert(chunks, null, null, null, playTone, null, softButtons, correlationID); return msg; } public static Alert buildAlert(String alertText1, String alertText2, String alertText3, Integer duration, Vector<SoftButton> softButtons, Integer correlationID) { Alert msg = buildAlert((Vector<TTSChunk>) null, alertText1, alertText2, alertText3, null, duration, softButtons, correlationID); return msg; } public static Alert buildAlert(String ttsText, String alertText1, String alertText2, String alertText3, Boolean playTone, Integer duration, Vector<SoftButton> softButtons, Integer correlationID) { Vector<TTSChunk> chunks = TTSChunkFactory .createSimpleTTSChunks(ttsText); Alert msg = buildAlert(chunks, alertText1, alertText2, alertText3, playTone, duration, softButtons, correlationID); return msg; } public static Alert buildAlert(Vector<TTSChunk> chunks, Boolean playTone, Vector<SoftButton> softButtons, Integer correlationID) { Alert msg = buildAlert(chunks, null, null, null, playTone, null, softButtons, correlationID); return msg; } public static Alert buildAlert(Vector<TTSChunk> ttsChunks, String alertText1, String alertText2, String alertText3, Boolean playTone, Integer duration, Vector<SoftButton> softButtons, Integer correlationID) { Alert msg = new Alert(); msg.setCorrelationID(correlationID); msg.setAlertText1(alertText1); msg.setAlertText2(alertText2); msg.setAlertText3(alertText3); msg.setDuration(duration); msg.setPlayTone(playTone); msg.setTtsChunks(ttsChunks); msg.setSoftButtons(softButtons); return msg; } public static Alert buildAlert(String ttsText, Boolean playTone, Integer correlationID) { Vector<TTSChunk> chunks = TTSChunkFactory .createSimpleTTSChunks(ttsText); Alert msg = buildAlert(chunks, null, null, playTone, null, correlationID); return msg; } public static Alert buildAlert(String alertText1, String alertText2, Integer duration, Integer correlationID) { Alert msg = buildAlert((Vector<TTSChunk>) null, alertText1, alertText2, null, duration, correlationID); return msg; } public static Alert buildAlert(String ttsText, String alertText1, String alertText2, Boolean playTone, Integer duration, Integer correlationID) { Vector<TTSChunk> chunks = TTSChunkFactory .createSimpleTTSChunks(ttsText); Alert msg = buildAlert(chunks, alertText1, alertText2, playTone, duration, correlationID); return msg; } public static Alert buildAlert(Vector<TTSChunk> chunks, Boolean playTone, Integer correlationID) { Alert msg = buildAlert(chunks, null, null, playTone, null, correlationID); return msg; } public static Alert buildAlert(Vector<TTSChunk> ttsChunks, String alertText1, String alertText2, Boolean playTone, Integer duration, Integer correlationID) { Alert msg = new Alert(); msg.setCorrelationID(correlationID); msg.setAlertText1(alertText1); msg.setAlertText2(alertText2); msg.setDuration(duration); msg.setPlayTone(playTone); msg.setTtsChunks(ttsChunks); return msg; } public static CreateInteractionChoiceSet buildCreateInteractionChoiceSet( Vector<Choice> choiceSet, Integer interactionChoiceSetID, Integer correlationID) { CreateInteractionChoiceSet msg = new CreateInteractionChoiceSet(); msg.setChoiceSet(choiceSet); msg.setInteractionChoiceSetID(interactionChoiceSetID); msg.setCorrelationID(correlationID); return msg; } public static DeleteCommand buildDeleteCommand(Integer commandID, Integer correlationID) { DeleteCommand msg = new DeleteCommand(); msg.setCmdID(commandID); msg.setCorrelationID(correlationID); return msg; } public static DeleteFile buildDeleteFile(String sdlFileName, Integer correlationID) { DeleteFile deleteFile = new DeleteFile(); deleteFile.setCorrelationID(correlationID); deleteFile.setSdlFileName(sdlFileName); return deleteFile; } public static DeleteInteractionChoiceSet buildDeleteInteractionChoiceSet( Integer interactionChoiceSetID, Integer correlationID) { DeleteInteractionChoiceSet msg = new DeleteInteractionChoiceSet(); msg.setInteractionChoiceSetID(interactionChoiceSetID); msg.setCorrelationID(correlationID); return msg; } public static DeleteSubMenu buildDeleteSubMenu(Integer menuID, Integer correlationID) { DeleteSubMenu msg = new DeleteSubMenu(); msg.setCorrelationID(correlationID); msg.setMenuID(menuID); return msg; } public static ListFiles buildListFiles(Integer correlationID) { ListFiles listFiles = new ListFiles(); listFiles.setCorrelationID(correlationID); return listFiles; } public static PerformInteraction buildPerformInteraction( Vector<TTSChunk> initChunks, String displayText, Vector<Integer> interactionChoiceSetIDList, Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp, Integer correlationID) { PerformInteraction msg = new PerformInteraction(); msg.setInitialPrompt(initChunks); msg.setInitialText(displayText); msg.setInteractionChoiceSetIDList(interactionChoiceSetIDList); msg.setInteractionMode(interactionMode); msg.setTimeout(timeout); msg.setHelpPrompt(helpChunks); msg.setTimeoutPrompt(timeoutChunks); msg.setVrHelp(vrHelp); msg.setCorrelationID(correlationID); return msg; } public static PerformInteraction buildPerformInteraction( String initPrompt, String displayText, Vector<Integer> interactionChoiceSetIDList, String helpPrompt, String timeoutPrompt, InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp, Integer correlationID) { Vector<TTSChunk> initChunks = TTSChunkFactory .createSimpleTTSChunks(initPrompt); Vector<TTSChunk> helpChunks = TTSChunkFactory .createSimpleTTSChunks(helpPrompt); Vector<TTSChunk> timeoutChunks = TTSChunkFactory .createSimpleTTSChunks(timeoutPrompt); return buildPerformInteraction(initChunks, displayText, interactionChoiceSetIDList, helpChunks, timeoutChunks, interactionMode, timeout, vrHelp, correlationID); } public static PerformInteraction buildPerformInteraction( String initPrompt, String displayText, Integer interactionChoiceSetID, String helpPrompt, String timeoutPrompt, InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp, Integer correlationID) { Vector<Integer> interactionChoiceSetIDs = new Vector<Integer>(); interactionChoiceSetIDs.add(interactionChoiceSetID); return buildPerformInteraction( initPrompt, displayText, interactionChoiceSetIDs, helpPrompt, timeoutPrompt, interactionMode, timeout, vrHelp, correlationID); } public static PerformInteraction buildPerformInteraction(String initPrompt, String displayText, Integer interactionChoiceSetID, Vector<VrHelpItem> vrHelp, Integer correlationID) { return buildPerformInteraction(initPrompt, displayText, interactionChoiceSetID, null, null, InteractionMode.BOTH, null, vrHelp, correlationID); } public static PerformInteraction buildPerformInteraction( Vector<TTSChunk> initChunks, String displayText, Vector<Integer> interactionChoiceSetIDList, Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, InteractionMode interactionMode, Integer timeout, Integer correlationID) { PerformInteraction msg = new PerformInteraction(); msg.setInitialPrompt(initChunks); msg.setInitialText(displayText); msg.setInteractionChoiceSetIDList(interactionChoiceSetIDList); msg.setInteractionMode(interactionMode); msg.setTimeout(timeout); msg.setHelpPrompt(helpChunks); msg.setTimeoutPrompt(timeoutChunks); msg.setCorrelationID(correlationID); return msg; } public static PerformInteraction buildPerformInteraction( String initPrompt, String displayText, Vector<Integer> interactionChoiceSetIDList, String helpPrompt, String timeoutPrompt, InteractionMode interactionMode, Integer timeout, Integer correlationID) { Vector<TTSChunk> initChunks = TTSChunkFactory .createSimpleTTSChunks(initPrompt); Vector<TTSChunk> helpChunks = TTSChunkFactory .createSimpleTTSChunks(helpPrompt); Vector<TTSChunk> timeoutChunks = TTSChunkFactory .createSimpleTTSChunks(timeoutPrompt); return buildPerformInteraction(initChunks, displayText, interactionChoiceSetIDList, helpChunks, timeoutChunks, interactionMode, timeout, correlationID); } public static PerformInteraction buildPerformInteraction( String initPrompt, String displayText, Integer interactionChoiceSetID, String helpPrompt, String timeoutPrompt, InteractionMode interactionMode, Integer timeout, Integer correlationID) { Vector<Integer> interactionChoiceSetIDs = new Vector<Integer>(); interactionChoiceSetIDs.add(interactionChoiceSetID); return buildPerformInteraction( initPrompt, displayText, interactionChoiceSetIDs, helpPrompt, timeoutPrompt, interactionMode, timeout, correlationID); } public static PerformInteraction buildPerformInteraction(String initPrompt, String displayText, Integer interactionChoiceSetID, Integer correlationID) { return buildPerformInteraction(initPrompt, displayText, interactionChoiceSetID, null, null, InteractionMode.BOTH, null, correlationID); } @Deprecated public static PerformInteraction buildPerformInteraction( Vector<TTSChunk> initChunks, String displayText, Vector<Integer> interactionChoiceSetIDList, Vector<TTSChunk> helpChunks, InteractionMode interactionMode, Integer timeout, Integer correlationID) { PerformInteraction msg = new PerformInteraction(); msg.setInitialPrompt(initChunks); msg.setInitialText(displayText); msg.setInteractionChoiceSetIDList(interactionChoiceSetIDList); msg.setInteractionMode(interactionMode); msg.setTimeout(timeout); msg.setHelpPrompt(helpChunks); msg.setCorrelationID(correlationID); return msg; } @Deprecated public static PerformInteraction buildPerformInteraction(String initPrompt, String displayText, Vector<Integer> interactionChoiceSetIDList, String helpPrompt, InteractionMode interactionMode, Integer timeout, Integer correlationID) { Vector<TTSChunk> initChunks = TTSChunkFactory .createSimpleTTSChunks(initPrompt); Vector<TTSChunk> helpChunks = TTSChunkFactory .createSimpleTTSChunks(helpPrompt); PerformInteraction msg = buildPerformInteraction(initChunks, displayText, interactionChoiceSetIDList, helpChunks, interactionMode, timeout, correlationID); return msg; } public static PutFile buildPutFile(String sdlFileName, FileType fileType, Boolean persistentFile, byte[] fileData, Integer correlationID) { PutFile putFile = new PutFile(); putFile.setCorrelationID(correlationID); putFile.setSdlFileName(sdlFileName); putFile.setFileType(fileType); putFile.setPersistentFile(persistentFile); putFile.setBulkData(fileData); putFile.setCRC(fileData); return putFile; } @Deprecated public static PutFile buildPutFile(String sdlFileName, Integer iOffset, Integer iLength) { PutFile putFile = new PutFile(); putFile.setCorrelationID(10000); putFile.setSdlFileName(sdlFileName); putFile.setFileType(FileType.BINARY); putFile.setSystemFile(true); putFile.setOffset(iOffset); putFile.setLength(iLength); return putFile; } public static PutFile buildPutFile(String sdlFileName, Long iOffset, Long iLength) { PutFile putFile = new PutFile(); putFile.setCorrelationID(10000); putFile.setSdlFileName(sdlFileName); putFile.setFileType(FileType.BINARY); putFile.setSystemFile(true); putFile.setOffset(iOffset); putFile.setLength(iLength); return putFile; } @Deprecated public static PutFile buildPutFile(String syncFileName, Integer iOffset, Integer iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile) { PutFile putFile = new PutFile(); putFile.setCorrelationID(10000); putFile.setSdlFileName(syncFileName); putFile.setFileType(fileType); putFile.setPersistentFile(bPersistentFile); putFile.setSystemFile(bSystemFile); putFile.setOffset(iOffset); putFile.setLength(iLength); return putFile; } public static PutFile buildPutFile(String syncFileName, Long iOffset, Long iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile) { PutFile putFile = new PutFile(); putFile.setCorrelationID(10000); putFile.setSdlFileName(syncFileName); putFile.setFileType(fileType); putFile.setPersistentFile(bPersistentFile); putFile.setSystemFile(bSystemFile); putFile.setOffset(iOffset); putFile.setLength(iLength); return putFile; } @Deprecated public static PutFile buildPutFile(String sdlFileName, Integer iOffset, Integer iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile, Integer iCorrelationID) { PutFile putFile = new PutFile(); putFile.setCorrelationID(iCorrelationID); putFile.setSdlFileName(sdlFileName); putFile.setFileType(fileType); putFile.setPersistentFile(bPersistentFile); putFile.setSystemFile(bSystemFile); putFile.setOffset(iOffset); putFile.setLength(iLength); return putFile; } public static PutFile buildPutFile(String sdlFileName, Long iOffset, Long iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile, Boolean isPayloadProtected, Integer iCorrelationID) { PutFile putFile = new PutFile(); putFile.setCorrelationID(iCorrelationID); putFile.setSdlFileName(sdlFileName); putFile.setFileType(fileType); putFile.setPersistentFile(bPersistentFile); putFile.setSystemFile(bSystemFile); putFile.setOffset(iOffset); putFile.setLength(iLength); putFile.setPayloadProtected(isPayloadProtected); return putFile; } public static RegisterAppInterface buildRegisterAppInterface(String appName, String appID) { return buildRegisterAppInterface(appName, false, appID); } public static RegisterAppInterface buildRegisterAppInterface( String appName, Boolean isMediaApp, String appID) { return buildRegisterAppInterface(null, appName, null, null, null, isMediaApp, null, null, null, appID, null, null); } public static RegisterAppInterface buildRegisterAppInterface( SdlMsgVersion sdlMsgVersion, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, Integer correlationID, DeviceInfo deviceInfo) { RegisterAppInterface msg = new RegisterAppInterface(); if (correlationID == null) { correlationID = 1; } msg.setCorrelationID(correlationID); if (sdlMsgVersion == null) { sdlMsgVersion = new SdlMsgVersion(); sdlMsgVersion.setMajorVersion(Integer.valueOf(SDL_MSG_MAJOR_VERSION)); sdlMsgVersion.setMinorVersion(Integer.valueOf(SDL_MSG_MINOR_VERSION)); } msg.setSdlMsgVersion(sdlMsgVersion); msg.setDeviceInfo(deviceInfo); msg.setAppName(appName); msg.setTtsName(ttsName); if (ngnMediaScreenAppName == null) { ngnMediaScreenAppName = appName; } msg.setNgnMediaScreenAppName(ngnMediaScreenAppName); if (vrSynonyms == null) { vrSynonyms = new Vector<String>(); vrSynonyms.add(appName); } msg.setVrSynonyms(vrSynonyms); msg.setIsMediaApplication(isMediaApp); if (languageDesired == null) { languageDesired = Language.EN_US; } msg.setLanguageDesired(languageDesired); if (hmiDisplayLanguageDesired == null) { hmiDisplayLanguageDesired = Language.EN_US; } msg.setHmiDisplayLanguageDesired(hmiDisplayLanguageDesired); msg.setAppHMIType(appType); msg.setAppID(appID); return msg; } public static SetAppIcon buildSetAppIcon(String sdlFileName, Integer correlationID) { SetAppIcon setAppIcon = new SetAppIcon(); setAppIcon.setCorrelationID(correlationID); setAppIcon.setSdlFileName(sdlFileName); return setAppIcon; } public static SetGlobalProperties buildSetGlobalProperties( String helpPrompt, String timeoutPrompt, Integer correlationID) { return buildSetGlobalProperties(TTSChunkFactory .createSimpleTTSChunks(helpPrompt), TTSChunkFactory .createSimpleTTSChunks(timeoutPrompt), correlationID); } public static SetGlobalProperties buildSetGlobalProperties( Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, Integer correlationID) { SetGlobalProperties req = new SetGlobalProperties(); req.setCorrelationID(correlationID); req.setHelpPrompt(helpChunks); req.setTimeoutPrompt(timeoutChunks); return req; } public static SetGlobalProperties buildSetGlobalProperties( String helpPrompt, String timeoutPrompt, String vrHelpTitle, Vector<VrHelpItem> vrHelp, Integer correlationID) { return buildSetGlobalProperties(TTSChunkFactory .createSimpleTTSChunks(helpPrompt), TTSChunkFactory .createSimpleTTSChunks(timeoutPrompt), vrHelpTitle, vrHelp, correlationID); } public static SetGlobalProperties buildSetGlobalProperties( Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, String vrHelpTitle, Vector<VrHelpItem> vrHelp, Integer correlationID) { SetGlobalProperties req = new SetGlobalProperties(); req.setCorrelationID(correlationID); req.setHelpPrompt(helpChunks); req.setTimeoutPrompt(timeoutChunks); req.setVrHelpTitle(vrHelpTitle); req.setVrHelp(vrHelp); return req; } public static SetMediaClockTimer buildSetMediaClockTimer(Integer hours, Integer minutes, Integer seconds, UpdateMode updateMode, Integer correlationID) { SetMediaClockTimer msg = new SetMediaClockTimer(); if (hours != null || minutes != null || seconds != null) { StartTime startTime = new StartTime(); msg.setStartTime(startTime); startTime.setHours(hours); startTime.setMinutes(minutes); startTime.setSeconds(seconds); } msg.setUpdateMode(updateMode); msg.setCorrelationID(correlationID); return msg; } @Deprecated public static SetMediaClockTimer buildSetMediaClockTimer( UpdateMode updateMode, Integer correlationID) { Integer hours = null; Integer minutes = null; Integer seconds = null; SetMediaClockTimer msg = buildSetMediaClockTimer(hours, minutes, seconds, updateMode, correlationID); return msg; } @SuppressWarnings("deprecation") public static Show buildShow(String mainText1, String mainText2, String mainText3, String mainText4, String statusBar, String mediaClock, String mediaTrack, Image graphic, Vector<SoftButton> softButtons, Vector <String> customPresets, TextAlignment alignment, Integer correlationID) { Show msg = new Show(); msg.setCorrelationID(correlationID); msg.setMainField1(mainText1); msg.setMainField2(mainText2); msg.setStatusBar(statusBar); msg.setMediaClock(mediaClock); msg.setMediaTrack(mediaTrack); msg.setAlignment(alignment); msg.setMainField3(mainText3); msg.setMainField4(mainText4); msg.setGraphic(graphic); msg.setSoftButtons(softButtons); msg.setCustomPresets(customPresets); return msg; } public static Show buildShow(String mainText1, String mainText2, String mainText3, String mainText4, TextAlignment alignment, Integer correlationID) { Show msg = buildShow(mainText1, mainText2, mainText3, mainText4, null, null, null, null, null, null, alignment, correlationID); return msg; } @SuppressWarnings("deprecation") public static Show buildShow(String mainText1, String mainText2, String statusBar, String mediaClock, String mediaTrack, TextAlignment alignment, Integer correlationID) { Show msg = new Show(); msg.setCorrelationID(correlationID); msg.setMainField1(mainText1); msg.setMainField2(mainText2); msg.setStatusBar(statusBar); msg.setMediaClock(mediaClock); msg.setMediaTrack(mediaTrack); msg.setAlignment(alignment); return msg; } public static Show buildShow(String mainText1, String mainText2, TextAlignment alignment, Integer correlationID) { Show msg = buildShow(mainText1, mainText2, null, null, null, alignment, correlationID); return msg; } public static Speak buildSpeak(String ttsText, Integer correlationID) { Speak msg = buildSpeak(TTSChunkFactory.createSimpleTTSChunks(ttsText), correlationID); return msg; } public static Speak buildSpeak(Vector<TTSChunk> ttsChunks, Integer correlationID) { Speak msg = new Speak(); msg.setCorrelationID(correlationID); msg.setTtsChunks(ttsChunks); return msg; } public static SubscribeButton buildSubscribeButton(ButtonName buttonName, Integer correlationID) { SubscribeButton msg = new SubscribeButton(); msg.setCorrelationID(correlationID); msg.setButtonName(buttonName); return msg; } public static UnregisterAppInterface buildUnregisterAppInterface( Integer correlationID) { UnregisterAppInterface msg = new UnregisterAppInterface(); msg.setCorrelationID(correlationID); return msg; } public static UnsubscribeButton buildUnsubscribeButton( ButtonName buttonName, Integer correlationID) { UnsubscribeButton msg = new UnsubscribeButton(); msg.setCorrelationID(correlationID); msg.setButtonName(buttonName); return msg; } @SuppressWarnings("deprecation") public static SubscribeVehicleData BuildSubscribeVehicleData(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) { SubscribeVehicleData msg = new SubscribeVehicleData(); msg.setGps(gps); msg.setSpeed(speed); msg.setRpm(rpm); msg.setFuelLevel(fuelLevel); msg.setFuelLevel_State(fuelLevel_State); msg.setInstantFuelConsumption(instantFuelConsumption); msg.setExternalTemperature(externalTemperature); msg.setPrndl(prndl); msg.setTirePressure(tirePressure); msg.setOdometer(odometer); msg.setBeltStatus(beltStatus); msg.setBodyInformation(bodyInformation); msg.setDeviceStatus(deviceStatus); msg.setDriverBraking(driverBraking); msg.setCorrelationID(correlationID); return msg; } @SuppressWarnings("deprecation") public static UnsubscribeVehicleData BuildUnsubscribeVehicleData(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) { UnsubscribeVehicleData msg = new UnsubscribeVehicleData(); msg.setGps(gps); msg.setSpeed(speed); msg.setRpm(rpm); msg.setFuelLevel(fuelLevel); msg.setFuelLevel_State(fuelLevel_State); msg.setInstantFuelConsumption(instantFuelConsumption); msg.setExternalTemperature(externalTemperature); msg.setPrndl(prndl); msg.setTirePressure(tirePressure); msg.setOdometer(odometer); msg.setBeltStatus(beltStatus); msg.setBodyInformation(bodyInformation); msg.setDeviceStatus(deviceStatus); msg.setDriverBraking(driverBraking); msg.setCorrelationID(correlationID); return msg; } @SuppressWarnings("deprecation") public static GetVehicleData BuildGetVehicleData(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean vin, boolean prndl, boolean tirePressure, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) { GetVehicleData msg = new GetVehicleData(); msg.setGps(gps); msg.setSpeed(speed); msg.setRpm(rpm); msg.setFuelLevel(fuelLevel); msg.setFuelLevel_State(fuelLevel_State); msg.setInstantFuelConsumption(instantFuelConsumption); msg.setExternalTemperature(externalTemperature); msg.setVin(vin); msg.setPrndl(prndl); msg.setTirePressure(tirePressure); msg.setOdometer(odometer); msg.setBeltStatus(beltStatus); msg.setBodyInformation(bodyInformation); msg.setDeviceStatus(deviceStatus); msg.setDriverBraking(driverBraking); msg.setCorrelationID(correlationID); return msg; } public static ScrollableMessage BuildScrollableMessage(String scrollableMessageBody, Integer timeout, Vector<SoftButton> softButtons, Integer correlationID) { ScrollableMessage msg = new ScrollableMessage(); msg.setCorrelationID(correlationID); msg.setScrollableMessageBody(scrollableMessageBody); msg.setTimeout(timeout); msg.setSoftButtons(softButtons); return msg; } public static Slider BuildSlider(Integer numTicks, Integer position, String sliderHeader, Vector<String> sliderFooter, Integer timeout, Integer correlationID) { Slider msg = new Slider(); msg.setCorrelationID(correlationID); msg.setNumTicks(numTicks); msg.setPosition(position); msg.setSliderHeader(sliderHeader); msg.setSliderFooter(sliderFooter); msg.setTimeout(timeout); return msg; } public static ChangeRegistration BuildChangeRegistration(Language language, Language hmiDisplayLanguage, Integer correlationID) { ChangeRegistration msg = new ChangeRegistration(); msg.setCorrelationID(correlationID); msg.setLanguage(language); msg.setHmiDisplayLanguage(hmiDisplayLanguage); return msg; } public static SetDisplayLayout BuildSetDisplayLayout(String displayLayout, Integer correlationID) { SetDisplayLayout msg = new SetDisplayLayout(); msg.setCorrelationID(correlationID); msg.setDisplayLayout(displayLayout); return msg; } public static PerformAudioPassThru BuildPerformAudioPassThru(String ttsText, String audioPassThruDisplayText1, String audioPassThruDisplayText2, SamplingRate samplingRate, Integer maxDuration, BitsPerSample bitsPerSample, AudioType audioType, Boolean muteAudio, Integer correlationID) { Vector<TTSChunk> chunks = TTSChunkFactory .createSimpleTTSChunks(ttsText); PerformAudioPassThru msg = BuildPerformAudioPassThru(chunks, audioPassThruDisplayText1, audioPassThruDisplayText2, samplingRate, maxDuration, bitsPerSample,audioType, muteAudio, correlationID); return msg; } public static PerformAudioPassThru BuildPerformAudioPassThru(Vector<TTSChunk> initialPrompt, String audioPassThruDisplayText1, String audioPassThruDisplayText2, SamplingRate samplingRate, Integer maxDuration, BitsPerSample bitsPerSample, AudioType audioType, Boolean muteAudio, Integer correlationID) { PerformAudioPassThru msg = new PerformAudioPassThru(); msg.setCorrelationID(correlationID); msg.setInitialPrompt(initialPrompt); msg.setAudioPassThruDisplayText1(audioPassThruDisplayText1); msg.setAudioPassThruDisplayText2(audioPassThruDisplayText2); msg.setSamplingRate(samplingRate); msg.setMaxDuration(maxDuration); msg.setBitsPerSample(bitsPerSample); msg.setAudioType(audioType); msg.setMuteAudio(muteAudio); return msg; } public static EndAudioPassThru BuildEndAudioPassThru(Integer correlationID) { EndAudioPassThru msg = new EndAudioPassThru(); msg.setCorrelationID(correlationID); return msg; } public static DeviceInfo BuildDeviceInfo(String carrierName) { DeviceInfo msg = new DeviceInfo(); msg.setHardware(android.os.Build.MODEL); msg.setOs(DeviceInfo.DEVICE_OS); msg.setOsVersion(Build.VERSION.RELEASE); msg.setCarrier(carrierName); return msg; } }
35.742
203
0.762436
c7dced52081169bf3011d832101aa1d8d43b9aa7
488
package net.avicus.atlas.core; /** * Along the way, I got lazy and used generic strings to represent the name and URL of the network, * even though it is stored in the config for some plugins, and should be localized. If you ever * decide to use this code, it would probably be wise to actually fix places that use these * references. - Austin */ public class NetworkIdentification { public static String NAME = "The Avicus Network"; public static String URL = "avicus.net"; }
34.857143
99
0.741803
0eb43acc9790e63fe28a44714cb7e0d74197b2ff
3,238
package igentuman.bfr.client.gui.element; import mekanism.api.text.ILangEntry; import mekanism.client.SpecialColors; import mekanism.client.gui.IGuiWrapper; import mekanism.client.gui.element.tab.GuiTabElementType; import mekanism.client.gui.element.tab.TabType; import mekanism.client.render.lib.ColorAtlas.ColorRegistryObject; import mekanism.common.util.MekanismUtils; import mekanism.common.util.MekanismUtils.ResourceType; import igentuman.bfr.client.BfrSpecialColors; import igentuman.bfr.client.gui.element.GuiFusionReactorTab.FusionReactorTab; import igentuman.bfr.common.BfrLang; import igentuman.bfr.common.BetterFusionReactor; import igentuman.bfr.common.network.to_server.PacketBfrGuiButtonPress; import igentuman.bfr.common.network.to_server.PacketBfrGuiButtonPress.ClickedGeneratorsTileButton; import igentuman.bfr.common.tile.fusion.TileEntityFusionReactorController; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; public class GuiFusionReactorTab extends GuiTabElementType<TileEntityFusionReactorController, FusionReactorTab> { public GuiFusionReactorTab(IGuiWrapper gui, TileEntityFusionReactorController tile, FusionReactorTab type) { super(gui, tile, type); } public enum FusionReactorTab implements TabType<TileEntityFusionReactorController> { HEAT(MekanismUtils.getResource(ResourceType.GUI, "heat.png"), BfrLang.HEAT_TAB, 6, ClickedGeneratorsTileButton.TAB_HEAT, BfrSpecialColors.TAB_MULTIBLOCK_HEAT), FUEL(BetterFusionReactor.rl(ResourceType.GUI.getPrefix() + "fuel.png"), BfrLang.FUEL_TAB, 34, ClickedGeneratorsTileButton.TAB_FUEL, BfrSpecialColors.TAB_MULTIBLOCK_FUEL), STAT(MekanismUtils.getResource(ResourceType.GUI, "stats.png"), BfrLang.STATS_TAB, 62, ClickedGeneratorsTileButton.TAB_STATS, SpecialColors.TAB_MULTIBLOCK_STATS), EFFICIENCY(MekanismUtils.getResource(ResourceType.GUI, "visuals.png"), BfrLang.EFFICIENCY_TAB, 90, ClickedGeneratorsTileButton.TAB_EFFICIENCY, SpecialColors.TAB_MULTIBLOCK_STATS); private final ClickedGeneratorsTileButton button; private final ColorRegistryObject colorRO; private final ILangEntry description; private final ResourceLocation path; private final int yPos; FusionReactorTab(ResourceLocation path, ILangEntry description, int y, ClickedGeneratorsTileButton button, ColorRegistryObject colorRO) { this.path = path; this.description = description; this.yPos = y; this.button = button; this.colorRO = colorRO; } @Override public ResourceLocation getResource() { return path; } @Override public void onClick(TileEntityFusionReactorController tile) { BetterFusionReactor.packetHandler().sendToServer(new PacketBfrGuiButtonPress(button, tile.getBlockPos())); } @Override public Component getDescription() { return description.translate(); } @Override public int getYPos() { return yPos; } @Override public ColorRegistryObject getTabColor() { return colorRO; } } }
44.972222
187
0.75386
e4e30044c96dab873c0a8c6824b48ecac229431a
1,673
package mekanism.client.render.armor; import javax.annotation.Nonnull; import mekanism.client.model.ModelScubaTank; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; public class ScubaTankArmor extends CustomArmor { public static final ScubaTankArmor SCUBA_TANK = new ScubaTankArmor(0.5F); private static final ModelScubaTank model = new ModelScubaTank(); private ScubaTankArmor(float size) { super(size); } @Override public void render(@Nonnull MatrixStack matrix, @Nonnull VertexConsumerProvider renderer, int light, int overlayLight, boolean hasEffect, LivingEntity entity, ItemStack stack) { if (!torso.visible) { //If the body model shouldn't show don't bother displaying it return; } if (child) { matrix.push(); float f1 = 1.0F / invertedChildBodyScale; matrix.scale(f1, f1, f1); matrix.translate(0.0D, childBodyYOffset / 16.0F, 0.0D); renderTank(matrix, renderer, light, overlayLight, hasEffect); matrix.pop(); } else { renderTank(matrix, renderer, light, overlayLight, hasEffect); } } private void renderTank(@Nonnull MatrixStack matrix, @Nonnull VertexConsumerProvider renderer, int light, int overlayLight, boolean hasEffect) { matrix.push(); torso.rotate(matrix); matrix.translate(0, 0, 0.06); model.render(matrix, renderer, light, overlayLight, hasEffect); matrix.pop(); } }
37.177778
162
0.675433
c6b531ccd32d20aa52dce09c6fcadd4cc1a42d15
9,192
package sqlancer.cockroachdb.oracle.tlp; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.postgresql.util.PSQLException; import sqlancer.ComparatorHelper; import sqlancer.IgnoreMeException; import sqlancer.QueryAdapter; import sqlancer.Randomly; import sqlancer.TestOracle; import sqlancer.cockroachdb.CockroachDBCommon; import sqlancer.cockroachdb.CockroachDBErrors; import sqlancer.cockroachdb.CockroachDBProvider.CockroachDBGlobalState; import sqlancer.cockroachdb.CockroachDBSchema; import sqlancer.cockroachdb.CockroachDBSchema.CockroachDBDataType; import sqlancer.cockroachdb.CockroachDBSchema.CockroachDBTables; import sqlancer.cockroachdb.CockroachDBVisitor; import sqlancer.cockroachdb.ast.CockroachDBAggregate; import sqlancer.cockroachdb.ast.CockroachDBAggregate.CockroachDBAggregateFunction; import sqlancer.cockroachdb.ast.CockroachDBAlias; import sqlancer.cockroachdb.ast.CockroachDBCast; import sqlancer.cockroachdb.ast.CockroachDBExpression; import sqlancer.cockroachdb.ast.CockroachDBNotOperation; import sqlancer.cockroachdb.ast.CockroachDBSelect; import sqlancer.cockroachdb.ast.CockroachDBTableReference; import sqlancer.cockroachdb.ast.CockroachDBUnaryPostfixOperation; import sqlancer.cockroachdb.ast.CockroachDBUnaryPostfixOperation.CockroachDBUnaryPostfixOperator; import sqlancer.cockroachdb.gen.CockroachDBExpressionGenerator; import sqlancer.cockroachdb.oracle.CockroachDBNoRECOracle; public class CockroachDBTLPAggregateOracle implements TestOracle { private final CockroachDBGlobalState state; private final Set<String> errors = new HashSet<>(); private CockroachDBExpressionGenerator gen; private String firstResult; private String secondResult; private String originalQuery; private String metamorphicQuery; public CockroachDBTLPAggregateOracle(CockroachDBGlobalState state) { this.state = state; CockroachDBErrors.addExpressionErrors(errors); errors.add("interface conversion: coldata.column"); errors.add("float out of range"); } @Override public void check() throws SQLException { CockroachDBSchema s = state.getSchema(); CockroachDBTables targetTables = s.getRandomTableNonEmptyTables(); gen = new CockroachDBExpressionGenerator(state).setColumns(targetTables.getColumns()); CockroachDBSelect select = new CockroachDBSelect(); CockroachDBAggregateFunction windowFunction = Randomly .fromOptions(CockroachDBAggregate.CockroachDBAggregateFunction.getRandomMetamorphicOracle()); CockroachDBAggregate aggregate = gen.generateArgsForAggregate(windowFunction.getRandomReturnType().get(), windowFunction); List<CockroachDBExpression> fetchColumns = new ArrayList<>(); fetchColumns.add(aggregate); while (Randomly.getBooleanWithRatherLowProbability()) { fetchColumns.add(gen.generateAggregate()); } select.setFetchColumns(Arrays.asList(aggregate)); List<CockroachDBTableReference> tableList = targetTables.getTables().stream() .map(t -> new CockroachDBTableReference(t)).collect(Collectors.toList()); List<CockroachDBExpression> from = CockroachDBCommon.getTableReferences(tableList); if (Randomly.getBooleanWithRatherLowProbability()) { select.setJoinList(CockroachDBNoRECOracle.getJoins(from, state)); } select.setFromList(from); if (Randomly.getBooleanWithRatherLowProbability()) { select.setOrderByExpressions(gen.getOrderingTerms()); } originalQuery = CockroachDBVisitor.asString(select); firstResult = getAggregateResult(originalQuery); metamorphicQuery = createMetamorphicUnionQuery(select, aggregate, from); secondResult = getAggregateResult(metamorphicQuery); state.getState().queryString = "--" + originalQuery + ";\n--" + metamorphicQuery + "\n-- " + firstResult + "\n-- " + secondResult; if (firstResult == null && secondResult != null || firstResult != null && (!firstResult.contentEquals(secondResult) && !ComparatorHelper.isEqualDouble(firstResult, secondResult))) { if (secondResult.contains("Inf")) { throw new IgnoreMeException(); // FIXME: average computation } throw new AssertionError(); } } private String createMetamorphicUnionQuery(CockroachDBSelect select, CockroachDBAggregate aggregate, List<CockroachDBExpression> from) { String metamorphicQuery; CockroachDBExpression whereClause = gen.generateExpression(CockroachDBDataType.BOOL.get()); CockroachDBNotOperation negatedClause = new CockroachDBNotOperation(whereClause); CockroachDBUnaryPostfixOperation notNullClause = new CockroachDBUnaryPostfixOperation(whereClause, CockroachDBUnaryPostfixOperator.IS_NULL); List<CockroachDBExpression> mappedAggregate = mapped(aggregate); CockroachDBSelect leftSelect = getSelect(mappedAggregate, from, whereClause, select.getJoinList()); CockroachDBSelect middleSelect = getSelect(mappedAggregate, from, negatedClause, select.getJoinList()); CockroachDBSelect rightSelect = getSelect(mappedAggregate, from, notNullClause, select.getJoinList()); metamorphicQuery = "SELECT " + getOuterAggregateFunction(aggregate).toString() + " FROM ("; metamorphicQuery += CockroachDBVisitor.asString(leftSelect) + " UNION ALL " + CockroachDBVisitor.asString(middleSelect) + " UNION ALL " + CockroachDBVisitor.asString(rightSelect); metamorphicQuery += ")"; return metamorphicQuery; } private String getAggregateResult(String queryString) throws SQLException { String resultString; QueryAdapter q = new QueryAdapter(queryString, errors); try (ResultSet result = q.executeAndGet(state)) { if (result == null) { throw new IgnoreMeException(); } if (!result.next()) { resultString = null; } else { resultString = result.getString(1); } } catch (PSQLException e) { throw new AssertionError(queryString, e); } return resultString; } private List<CockroachDBExpression> mapped(CockroachDBAggregate aggregate) { switch (aggregate.getFunc()) { case SUM: case COUNT: case COUNT_ROWS: case BIT_AND: case BIT_OR: case XOR_AGG: case SUM_INT: case BOOL_AND: case BOOL_OR: case MAX: case MIN: return aliasArgs(Arrays.asList(aggregate)); case AVG: // List<CockroachDBExpression> arg = Arrays.asList(new CockroachDBCast(aggregate.getExpr().get(0), // CockroachDBDataType.DECIMAL.get())); CockroachDBAggregate sum = new CockroachDBAggregate(CockroachDBAggregateFunction.SUM, aggregate.getExpr()); CockroachDBCast count = new CockroachDBCast( new CockroachDBAggregate(CockroachDBAggregateFunction.COUNT, aggregate.getExpr()), CockroachDBDataType.DECIMAL.get()); // CockroachDBBinaryArithmeticOperation avg = new CockroachDBBinaryArithmeticOperation(sum, count, // CockroachDBBinaryArithmeticOperator.DIV); return aliasArgs(Arrays.asList(sum, count)); default: throw new AssertionError(aggregate.getFunc()); } } private List<CockroachDBExpression> aliasArgs(List<CockroachDBExpression> originalAggregateArgs) { List<CockroachDBExpression> args = new ArrayList<>(); int i = 0; for (CockroachDBExpression expr : originalAggregateArgs) { args.add(new CockroachDBAlias(expr, "agg" + i++)); } return args; } private String getOuterAggregateFunction(CockroachDBAggregate aggregate) { switch (aggregate.getFunc()) { case AVG: return "SUM(agg0::DECIMAL)/SUM(agg1)::DECIMAL"; case COUNT: case COUNT_ROWS: return CockroachDBAggregateFunction.SUM.toString() + "(agg0)"; default: return aggregate.getFunc().toString() + "(agg0)"; } } private CockroachDBSelect getSelect(List<CockroachDBExpression> aggregates, List<CockroachDBExpression> from, CockroachDBExpression whereClause, List<CockroachDBExpression> joinList) { CockroachDBSelect leftSelect = new CockroachDBSelect(); leftSelect.setFetchColumns(aggregates); leftSelect.setFromList(from); leftSelect.setWhereClause(whereClause); leftSelect.setJoinList(joinList); if (Randomly.getBooleanWithSmallProbability()) { leftSelect.setGroupByExpressions(gen.generateExpressions(Randomly.smallNumber() + 1)); } return leftSelect; } }
45.96
119
0.706919
65be2916e2e75f6d6ee8d354c8dda7b3b5ea14d7
547
package org.jboss.as.quickstarts.kitchensink.interceptor; import javax.interceptor.InterceptorBinding; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; @InterceptorBinding @Retention(RetentionPolicy.RUNTIME) @Target({TYPE, METHOD, FIELD}) @Qualifier public @interface Log { }
26.047619
57
0.828154
1eec099703172b4c2c22650249f635f0fc7f68c4
4,277
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.xsom.impl; import com.sun.xml.internal.xsom.XSElementDecl; import com.sun.xml.internal.xsom.XSModelGroup; import com.sun.xml.internal.xsom.XSModelGroupDecl; import com.sun.xml.internal.xsom.XSParticle; import com.sun.xml.internal.xsom.XSTerm; import com.sun.xml.internal.xsom.XSWildcard; import com.sun.xml.internal.xsom.impl.parser.SchemaDocumentImpl; import com.sun.xml.internal.xsom.visitor.XSFunction; import com.sun.xml.internal.xsom.visitor.XSTermFunction; import com.sun.xml.internal.xsom.visitor.XSTermFunctionWithParam; import com.sun.xml.internal.xsom.visitor.XSTermVisitor; import com.sun.xml.internal.xsom.visitor.XSVisitor; import org.xml.sax.Locator; import java.util.Arrays; import java.util.Iterator; public class ModelGroupImpl extends ComponentImpl implements XSModelGroup, Ref.Term { public ModelGroupImpl( SchemaDocumentImpl owner, AnnotationImpl _annon, Locator _loc, ForeignAttributesImpl _fa, Compositor _compositor, ParticleImpl[] _children ) { super(owner,_annon,_loc,_fa); this.compositor = _compositor; this.children = _children; if(compositor==null) throw new IllegalArgumentException(); for( int i=children.length-1; i>=0; i-- ) if(children[i]==null) throw new IllegalArgumentException(); } private final ParticleImpl[] children; public ParticleImpl getChild( int idx ) { return children[idx]; } public int getSize() { return children.length; } public ParticleImpl[] getChildren() { return children; } private final Compositor compositor; public Compositor getCompositor() { return compositor; } public void redefine(ModelGroupDeclImpl oldMG) { for (ParticleImpl p : children) p.redefine(oldMG); } public Iterator<XSParticle> iterator() { return Arrays.asList((XSParticle[])children).iterator(); } public boolean isWildcard() { return false; } public boolean isModelGroupDecl() { return false; } public boolean isModelGroup() { return true; } public boolean isElementDecl() { return false; } public XSWildcard asWildcard() { return null; } public XSModelGroupDecl asModelGroupDecl() { return null; } public XSModelGroup asModelGroup() { return this; } public XSElementDecl asElementDecl() { return null; } public void visit( XSVisitor visitor ) { visitor.modelGroup(this); } public void visit( XSTermVisitor visitor ) { visitor.modelGroup(this); } public Object apply( XSTermFunction function ) { return function.modelGroup(this); } public <T,P> T apply(XSTermFunctionWithParam<T, P> function, P param) { return function.modelGroup(this,param); } public Object apply( XSFunction function ) { return function.modelGroup(this); } // Ref.Term implementation public XSTerm getTerm() { return this; } }
37.191304
116
0.7047
720faac67ee0a672ace0bbca76e9c6b8444fd1f6
3,524
package com.wzqCode.service; import com.wzqCode.cache.PlayerCache; import com.wzqCode.config.gameConfig.GlobalConfig; import com.wzqCode.config.gameConfig.HeroConfig; import com.wzqCode.exception.gameException.tavern.TavernFormatErrorException; import com.wzqCode.exception.gameException.tavern.TavernFreeLotteryTimeErrorException; import com.wzqCode.obj.cache.PlayerInfo; import com.wzqCode.obj.db.Player; import com.wzqCode.obj.msg.server.SReturnMsg; import com.wzqCode.obj.msg.server.tavern.SFreeLotteryMsg; import com.wzqCode.obj.msg.server.tavern.SGetTavernInfoMsg; import com.wzqCode.utils.DataUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.Date; @Service @Slf4j public class TavernService { @Autowired PlayerCache playerCache; @Autowired GlobalConfig globalConfig; @Autowired HeroConfig heroConfig; @Autowired HeroService heroService; // 获取酒馆信息 public SReturnMsg getTavernInfo(Integer playerId) { Integer lastFreeTime = getLastFreeTime(playerId); if(lastFreeTime < 0) lastFreeTime = 0; // TODO: 查询卷轴道具数量,需要道具系统,先设置为0 SGetTavernInfoMsg sGetTavernInfoMsg = new SGetTavernInfoMsg(); sGetTavernInfoMsg.setLastFreeTime(lastFreeTime); sGetTavernInfoMsg.setItemNum(0); return SReturnMsg.success(sGetTavernInfoMsg); } // 用户免费抽取英雄 public SReturnMsg freeLottery(Integer playerId){ Integer lastFreeTime = getLastFreeTime(playerId); // 还未到免费时间 if(lastFreeTime > 0) throw new TavernFreeLotteryTimeErrorException(); PlayerInfo playerInfo = playerCache.getPlayerInfo(playerId); Player baseProp = playerInfo.getBaseProp(); // 设置免费抽奖时间为当前时间 SimpleDateFormat df = new SimpleDateFormat(DataUtil.YYYY_MM_DD_HH_MM_SS); String currentTime = df.format(new Date()); baseProp.setLastFreeLotteryTime(currentTime); // 根据权重配置计算 随机获取type_id Integer heroTypeId = heroConfig.randHeroTypeId(); // 创建英雄 heroService.createHero(playerId, heroTypeId); // 返回消息,消息内容为英雄type_id SFreeLotteryMsg sFreeLotteryMsg = new SFreeLotteryMsg(); sFreeLotteryMsg.setHeroTypeId(heroTypeId); return SReturnMsg.success(sFreeLotteryMsg); } // 用户剩余的免费抽奖时间 private Integer getLastFreeTime(Integer playerId){ PlayerInfo playerInfo = playerCache.getPlayerInfo(playerId); // 获取免费抽奖的间隔时间 Integer freeDistLotteryTime = globalConfig.getIntegerValue(GlobalConfig.FREE_LOTTERY_TIME); // 获取用户最后一次免费抽奖的时间 String lastFreeLotteryTime = playerInfo.getBaseProp().getLastFreeLotteryTime(); // 时间格式转换时间戳 SimpleDateFormat df = new SimpleDateFormat(DataUtil.YYYY_MM_DD_HH_MM_SS); long lastFreeLotteryUnixTime = 0; try { lastFreeLotteryUnixTime = df.parse(lastFreeLotteryTime).getTime()/1000; }catch (Exception e) { log.error("getTavernInfo error: playerId="+playerId + " lastFreeLotteryTime=" + lastFreeLotteryTime); throw new TavernFormatErrorException(); } // 当前时间 Date date = new Date(); long currentTime = date.getTime()/1000; // 用户剩余的免费抽奖时间倒计时 long lastFreeTime = lastFreeLotteryUnixTime + freeDistLotteryTime - currentTime; return (int)lastFreeTime; } }
33.245283
113
0.717367
bf21caef90d6bab8c3cde0a228c2974e04334c53
7,107
/** * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br> * This file is part of FI-WARE project. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. * </p> * <p> * You may obtain a copy of the License at:<br> * <br> * http://www.apache.org/licenses/LICENSE-2.0 * </p> * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * </p> * <p> * See the License for the specific language governing permissions and limitations under the License. * </p> * <p> * For those usages not covered by the Apache version 2.0 License please contact with opensource@tid.es * </p> */ package com.telefonica.euro_iaas.sdc.installator.impl; import static java.text.MessageFormat.format; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.telefonica.euro_iaas.sdc.exception.InstallatorException; import com.telefonica.euro_iaas.sdc.exception.InvalidInstallProductRequestException; import com.telefonica.euro_iaas.sdc.exception.NodeExecutionException; import com.telefonica.euro_iaas.sdc.exception.OpenStackException; import com.telefonica.euro_iaas.sdc.exception.SdcRuntimeException; import com.telefonica.euro_iaas.sdc.installator.Installator; import com.telefonica.euro_iaas.sdc.keystoneutils.OpenStackRegion; import com.telefonica.euro_iaas.sdc.model.Attribute; import com.telefonica.euro_iaas.sdc.model.ProductInstance; import com.telefonica.euro_iaas.sdc.model.ProductRelease; import com.telefonica.euro_iaas.sdc.model.dto.NodeDto; import com.telefonica.euro_iaas.sdc.model.dto.VM; public class InstallatorPuppetImpl implements Installator { private static Logger log = LoggerFactory.getLogger(InstallatorPuppetImpl.class); private HttpClient client; private OpenStackRegion openStackRegion; public void callService(VM vm, String vdc, ProductRelease product, String action, String token) throws InstallatorException { String puppetUrl = null; try { puppetUrl = openStackRegion.getPuppetWrapperEndPoint(token); } catch (OpenStackException e) { throw new SdcRuntimeException(e); } HttpPost postInstall = new HttpPost(puppetUrl + "v2/node/"+ vm.getHostname() + "/" + action); postInstall.addHeader("Content-Type", "application/json"); NodeDto nodeDto = new NodeDto(vdc,product.getProduct().getName(),product.getVersion()); ObjectMapper mapper = new ObjectMapper(); StringEntity input; try { input = new StringEntity(mapper.writeValueAsString(nodeDto)); } catch (JsonGenerationException e2) { throw new SdcRuntimeException(e2); } catch (JsonMappingException e2) { throw new SdcRuntimeException(e2); } catch (UnsupportedEncodingException e2) { throw new SdcRuntimeException(e2); } catch (IOException e2) { throw new SdcRuntimeException(e2); } input.setContentType("application/json"); postInstall.setEntity(input); // System.out.println("puppetURL: " + puppetUrl + "v2/node/"+ vm.getHostname() + "/" // + action); HttpResponse response; log.info("Calling puppetWrapper install"); log.debug("connecting to puppetURL: "+"puppetURL: " + puppetUrl + "v2/node/"+ vm.getHostname() + "/" + action); try { response = client.execute(postInstall); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); if (statusCode != 200) { String msg=format("[puppet install] response code was: {0}", statusCode); log.warn(msg); throw new InstallatorException(format(msg)); } log.debug("statusCode:"+ statusCode); log.info("Calling puppetWrapper generate"); log.debug(puppetUrl + "v2/node/"+vm.getHostname()+"/generate"); // generate files in puppet master HttpGet getGenerate = new HttpGet(puppetUrl + "v2/node/"+vm.getHostname()+"/generate"); getGenerate.addHeader("Content-Type", "application/json"); response = client.execute(getGenerate); statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); EntityUtils.consume(entity); if (statusCode != 200) { String msg=format("generate files response code was: {0}", statusCode); log.warn(msg); throw new InstallatorException(format(msg, statusCode)); } log.debug("statusCode:"+ statusCode); } catch (IOException e) { log.error(e.getMessage()); throw new InstallatorException(e); } catch (IllegalStateException e1) { log.error(e1.getMessage()); throw new InstallatorException(e1); } } public void setClient(HttpClient client) { this.client = client; } @Override public void callService(ProductInstance productInstance, VM vm, List<Attribute> attributes, String action, String token) throws InstallatorException, NodeExecutionException { // TODO Auto-generated method stub } @Override public void upgrade(ProductInstance productInstance, VM vm, String token) throws InstallatorException { // TODO Auto-generated method stub } @Override public void callService(ProductInstance productInstance, String action, String token) throws InstallatorException, NodeExecutionException { // TODO Auto-generated method stub } @Override public void validateInstalatorData(VM vm, String token) throws InvalidInstallProductRequestException { if (!vm.canWorkWithInstallatorServer()) { String message = "The VM does not include the node hostname required to Install " + "software"; throw new InvalidInstallProductRequestException(message); } } public void setOpenStackRegion(OpenStackRegion openStackRegion) { this.openStackRegion = openStackRegion; } }
37.603175
118
0.676938
1bec936cb5cfbd0312d6859a0af2ca9d2711ee1b
749
package nl.weeaboo.lua2.luajava; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.List; final class JavaConstructor { private final Constructor<?> constr; private List<Class<?>> params; public JavaConstructor(Constructor<?> c) { constr = c; } public Object newInstance(Object... args) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { return constr.newInstance(args); } public List<Class<?>> getParamTypes() { if (params == null) { params = Arrays.asList(constr.getParameterTypes()); } return params; } }
25.827586
120
0.682243
6c301e31a98e6cd263040824acd6b7294ccdc4d1
2,529
package me.reflexlabs.randomspawn.utils; import java.util.Random; import me.reflexlabs.randomspawn.RandomSpawn; import org.bukkit.Sound; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import org.bukkit.ChatColor; public class Functions { public static String formatMessage(final String msg) { return ChatColor.translateAlternateColorCodes('&', "&f" + msg); } public static List<String> formatMessage(final List<String> msg) { final List<String> message = new ArrayList<String>(); for (final String line : msg) { message.add(ChatColor.translateAlternateColorCodes('&', "&f" + line)); } return message; } public static void print(String msg) { RandomSpawn.getInstance().getLogger().info(msg); } public static void playSound(final Player player, final int type) { String soundType = null; if (RandomSpawn.getInstance().getRandomManager().getDataManager().enableSound) { switch (type) { case 1: { soundType = RandomSpawn.getInstance().getRandomManager().getDataManager().uiSound; break; } case 2: { soundType = RandomSpawn.getInstance().getRandomManager().getDataManager().spawnSound; break; } default: { soundType = RandomSpawn.getInstance().getRandomManager().getDataManager().uiSound; break; } } try { player.playSound(player.getLocation(), soundType, 1.0f, 1.0f); } catch (Exception e) { player.playSound(player.getLocation(), Sound.valueOf(soundType), 1.0f, 1.0f); } } } public static boolean isNumeric(final String s) { try { Double.parseDouble(s); } catch (NumberFormatException nfe) { try { Integer.parseInt(s); } catch (NumberFormatException nfee) { return false; } } return true; } public static boolean isNegative(final double d) { return Double.compare(d, 0.0) < 0; } public static String getRandomNumberString() { final Random rnd = new Random(); final int number = rnd.nextInt(999999); return String.format("%06d", number); } }
30.841463
105
0.561487
90b9ff00c26334e1a0e16d07bee18e390447ba44
2,225
/* * Copyright (c) 2014-2018, Bitnine Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bitnine.agensgraph.ds; import net.bitnine.agensgraph.util.DriverInfo; import org.postgresql.PGProperty; import org.postgresql.ds.PGConnectionPoolDataSource; import java.util.Properties; public class AGConnectionPoolDataSource extends PGConnectionPoolDataSource { @Override public String getDescription() { return "ConnectionPoolDataSource from " + DriverInfo.DRIVER_FULL_NAME; } @Override public String getUrl() { StringBuilder url = new StringBuilder(100); url.append("jdbc:agensgraph://"); url.append(super.getServerName()); if (getPortNumber() != 0) { url.append(":").append(super.getPortNumber()); } url.append("/").append(super.getDatabaseName()); StringBuilder query = new StringBuilder(100); Properties properties = new Properties(); for (PGProperty property : PGProperty.values()) { String value = super.getProperty(property); if (value != null) { properties.setProperty(property.getName(), value); } } for (PGProperty property : PGProperty.values()) { if (property.isPresent(properties)) { if (query.length() != 0) { query.append("&"); } query.append(property.getName()); query.append("="); query.append(property.get(properties)); } } if(query.length() > 0) { url.append("?"); url.append(query); } return url.toString(); } }
32.720588
78
0.620225
c49c5da973e89c63202520ba5558471001596add
400
package com.ibeetl.java8.optional; public class Man { private Godness godness; public Man() { super(); } public Man(Godness godness) { super(); this.godness = godness; } public Godness getGodness() { return godness; } public void setGodness(Godness godness) { this.godness = godness; } @Override public String toString() { return "Man [godness=" + godness + "]"; } }
13.333333
42
0.6575
6b887fafe2b715074542228a183a9cbebd942d18
842
package com.xu.atchat.cache; import org.springframework.stereotype.Component; import java.util.concurrent.ConcurrentHashMap; /** * @author xucl * @version 1.0 * @date 2020/5/23 18:23 * @description 线程共享缓存 */ @Component public class CacheFactory <K,V> implements Cache <K,V>{ private volatile ConcurrentHashMap<K, V> commons = new ConcurrentHashMap<K,V>(); @SuppressWarnings("unchecked") @Override public V getCache(K k) { // TODO Auto-generated method stub return (V) commons.get(k); } @Override public void addCache(K k,V v) { // TODO Auto-generated method stub commons.put(k, v); } @Override public void putIfAbsentCache(K k,V v) { // TODO Auto-generated method stub commons.putIfAbsent(k, v); } @Override public void remove(K k) { // TODO Auto-generated method stub commons.remove(k); } }
19.581395
82
0.698337
d01cd0d9b6e17ea035ecc4afa2e58e36d7c34a20
6,526
package com.github.mirs.banxiaoxiao.framework.core.license; import com.github.mirs.banxiaoxiao.framework.common.shell.ShellUtils; import com.github.mirs.banxiaoxiao.framework.common.util.MultiTypeValMap; import com.github.mirs.banxiaoxiao.framework.core.log.TComLogs; import org.slf4j.helpers.MessageFormatter; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author zcy 2019年5月31日 */ public final class License extends MultiTypeValMap { /** * */ private static final long serialVersionUID = -5520061786135596348L; private static License INSTANCE = new License(); private LicenseDataLoader loader; /** * 服务器id */ private List<String> uuids; private License() { } public static License get() { return INSTANCE; } public static License create() { return new License(); } public void setLicenseDataLoader(LicenseDataLoader loader) { this.loader = loader; } public void put(String key, Object val) { throw new UnsupportedOperationException(); } public void putAll(Map<String, Object> vals) { throw new UnsupportedOperationException(); } /** * */ public void init() { try { if (this.uuids != null) { this.uuids.clear(); } getVals().clear(); byte[] licenseData = this.loader.load(); byte[] decryptData = decrypt(licenseData); if (decryptData == null || decryptData.length == 0) { throw new LicenseException("init License data fail, not found data"); } Properties properties = new Properties(); properties.load(new ByteArrayInputStream(decryptData)); properties.forEach((k, v) -> { super.put(k.toString(), v); }); try { this.uuids = new ArrayList<String>(); String systemuid = BlackBox.decodesystemid(licenseData); if (systemuid != null) { //支持license逗号和换行符切割 for (String uid : systemuid.split("[\n,]")) { this.uuids.add(uid); } } } catch (Throwable e) { TComLogs.error("decode systemid fail", e); } } catch (LicenseException e) { throw e; } catch (IOException e) { throw new LicenseException("init License data fail", e); } } public String getLocalUid() { List<String> result = ShellUtils.exec("dmidecode -s system-uuid"); return result == null || result.size() == 0 ? "" : result.get(0); } public List<String> getUuids() { return uuids; } public void setUuids(List<String> uuids) { this.uuids = uuids; } public void checkContains(String key, String val) throws LicenseException { String licenseData = getString(key); if (licenseData == null) { throwLicenseAuthException(key); } else { for (String licenseItem : licenseData.split(",")) { if (!licenseItem.equals(val)) { throwLicenseAuthException(key); } } } } public void checkEquals(String key, String val) throws LicenseException { String licenseData = getString(key); if (licenseData == null || !licenseData.equals(val)) { throwLicenseAuthException(key); } } public <T extends Number> void checkEquals(String key, T val) throws LicenseException { Long licenseData = getLong(key, null); if (licenseData == null || licenseData != val.longValue()) { throwLicenseAuthException(key); } } /** * 验证是否在授权数值是否在范围内 */ public <T extends Number> void checkRange(String key, T val1, T val2) throws LicenseException { Long licenseData = getLong(key, null); if (licenseData == null || val1 == null || val2 == null) { throwLicenseAuthException(key); } if (licenseData < val1.longValue() || licenseData > val2.longValue()) { throwLicenseAuthException("{} out of auth range", key); } } /** * 验证授权数值是否>val */ public <T extends Number> void checkGreater(String key, T val) throws LicenseException { Long licenseData = getLong(key, null); if (licenseData == null || val == null) { throwLicenseAuthException(key); } if (licenseData <= val.longValue()) { throwLicenseAuthException(key); } } /** * 验证授权数值是否>=val */ public <T extends Number> void checkGreaterAndEqu(String key, T val) throws LicenseException { Long licenseData = getLong(key, null); if (licenseData == null || val == null) { throwLicenseAuthException(key); } if (licenseData < val.longValue()) { throwLicenseAuthException(key); } } /** * 验证授权数值是否<val */ public <T extends Number> void checkLess(String key, T val) throws LicenseException { Long licenseData = getLong(key, null); if (licenseData == null || val == null) { throwLicenseAuthException(key); } if (licenseData >= val.longValue()) { throwLicenseAuthException(key); } } /** * 验证授权数值是否<=val */ public <T extends Number> void checkLessAndEqu(String key, T val) throws LicenseException { Long licenseData = getLong(key, null); if (licenseData == null || val == null) { throwLicenseAuthException(key); } if (licenseData > val.longValue()) { throwLicenseAuthException(key); } } private void throwLicenseAuthException(String key) { throwLicenseAuthException("{} unauthorized", key); } private void throwLicenseAuthException(String formatMsg, Object... propertys) { String msg = MessageFormatter.arrayFormat(formatMsg, propertys).getMessage(); throw new LicenseException(msg); } /** * 解密数据 */ public byte[] decrypt(byte[] data) { if (data == null) { return null; } byte[] resultData = BlackBox.decrypt(data); return resultData; } }
29.663636
99
0.576004
103b50c8d9442121b940dd0bc4f62a2efedcbbe8
1,663
package br.odravison.sogo.minicoursesinfrasctructure.repositories.hibernate; import br.odravison.sogo.minicoursesinfrasctructure.entities.UserMapped; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserMappedRepository extends CrudRepository<UserMapped, Long> { /** * Login the user. */ @Query(value = "select * from user_account " + "where upper(email) = upper(?1) " + "and password = ?2 " + "and deleted = false;", nativeQuery = true) UserMapped login(String email, String encryptedPassword); /** * Checks if exists an user with the same email. */ boolean existsByEmailAndDeleted(String email, boolean deleted); /** * Finds the user by email. */ UserMapped findByEmailAndDeleted(String email, boolean deleted); /** * Checks if the password of the user is correct. */ @Query(value = "SELECT EXISTS(" + "SELECT * FROM user_account " + "WHERE id = ?1 " + "AND password = ?2 " + "AND deleted = false" + ");", nativeQuery = true) Boolean isPasswordCorrect(Long id, String password); @Modifying @Query(value = "UPDATE user_account " + "SET last_login_time = ?2 " + "WHERE id = ?1", nativeQuery = true) void updateLastLoginTimeByUserId(Long id, Long lastLoginTime); boolean existsByEmailIgnoreCaseAndDeletedFalse(String email); }
32.607843
80
0.656645
8d7e9506c7b9a94822ece7336995b1a646522563
885
package org.fastnate.data.files; import java.io.IOException; import java.io.InputStream; import java.net.URL; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Represents a data file from an URL. * * @author Tobias Liefke */ @RequiredArgsConstructor public class UrlDataFile implements DataFile { /** The parent folder, if any. */ @Getter private final DataFolder folder; /** The represented file as URL. */ @Getter private final URL url; /** * Creates a new file from an URL without information about the parent folder. * * @param url * the URL of the file we represent */ public UrlDataFile(final URL url) { this(null, url); } @Override public String getName() { return this.url.getPath().replaceFirst("^.*\\/", ""); } @Override public InputStream open() throws IOException { return this.url.openStream(); } }
18.829787
79
0.694915
0c9b5ad794232316aa79d43f7e3de9d7d600c241
6,326
/* * Copyright 2020 Open LVC Project. * * This file is part of Open LVC Disco. * * 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.openlvc.disco.connection.rpr.types.enumerated; import org.openlvc.disco.DiscoException; import hla.rti1516e.encoding.ByteWrapper; import hla.rti1516e.encoding.DataElement; import hla.rti1516e.encoding.DecoderException; import hla.rti1516e.encoding.EncoderException; /** * <p>This class represents the parent type for all HLA enumerated data types. Due to the way that * the encoding helpers are specified, it is not simple to implement them as a Java enum. We must * be able to call the DataElement method decode() on them, which has the potential to change their * value, effectively losing the immutable nature of Java enumerations.</p> * * <p>To get around this, we have implemented various protective measures into this base type. * These include: * <ul> * <li>Each <code>HLAenum</code> has an <code>isConstant</code> property. This should be declared * as true for all instances that are defined as statics in subclasses to represent the * enumerated values. (should be done via a private constructor in that type).</li> * <li>When decode() is called on an instant that is constant, an exception is thrown.</li> * <li>Child classes do not expose the constructor that sets the isConstant property, meaning * only the defining type can call it. Public constructors for child types should always set * isConstant to false.</li> * <li>A copy() method must be defined by all child types, allowing new enum instances that can * have decode() called on them to be created from the static types.</li> * </p> * * <p>Child classes should follow these rules.</p> * * @param <T> The underlying datatype that forms the value for the enumerated named. */ public abstract class HLAenum<T extends DataElement> implements DataElement { //---------------------------------------------------------- // STATIC VARIABLES //---------------------------------------------------------- //---------------------------------------------------------- // INSTANCE VARIABLES //---------------------------------------------------------- protected T value; private boolean isConstant; //---------------------------------------------------------- // CONSTRUCTORS //---------------------------------------------------------- protected HLAenum( T value, boolean isConstant ) { this.value = value; this.isConstant = isConstant; } //---------------------------------------------------------- // INSTANCE METHODS //---------------------------------------------------------- /** * @return This method will clone the data element that is used to store the enum value. * This allows us to safely replace a value on decode rather than edit the original, * which in turn prevents us modifying the value of the enumerated types. */ protected abstract T copyValue(); /** * Create a copy of this enum and return it. This allows us to copy a constant value of * the enum type without maintaining a reference to the original (and avoiding us accidentally * using {@link #decode(byte[])} to erase its known value. * * @param <X> The subclass of {@link HLAenum} that the type we are copying is. Should be the * type of the class that this method is implemented in. * @return A copy of the value this is called on that can be freely changed. */ public abstract <X extends HLAenum<T>> X copy(); //////////////////////////////////////////////////////////////////////////////////////////// /// Accessor and Mutator Methods ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// public T getHlaValue() { return this.value; } public void setHlaValue( T value ) throws DiscoException { if( isConstant ) { throw new DiscoException( "Cannot change the value of a constant. "+ "Create a copy of constant using copy() first" ); } else { this.value = value; } } //////////////////////////////////////////////////////////////////////////////////////////// /// Data Element Methods ///////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// @Override public int getOctetBoundary() { return value.getOctetBoundary(); } @Override public void encode( ByteWrapper byteWrapper ) throws EncoderException { value.encode( byteWrapper ); } @Override public int getEncodedLength() { return value.getEncodedLength(); } @Override public byte[] toByteArray() throws EncoderException { return value.toByteArray(); } @Override public final void decode( ByteWrapper byteWrapper ) throws DecoderException { if( isConstant ) { throw new DecoderException( "Cannot change the value of a constant. "+ "Create a copy of constant using copy() first" ); } T newValue = copyValue(); newValue.decode( byteWrapper ); this.value = newValue; } @Override public final void decode( byte[] bytes ) throws DecoderException { if( isConstant ) { throw new DecoderException( "Cannot change the value of a constant. "+ "Create a copy of constant using copy() first" ); } T newValue = copyValue(); newValue.decode( bytes ); this.value = newValue; } //---------------------------------------------------------- // STATIC METHODS //---------------------------------------------------------- }
35.539326
99
0.566077
80ec3d29e1ad90a88d17685ee98568bc9a022b2c
7,306
package com.github.skjolber.nfc.service; import java.io.ByteArrayOutputStream; // http://stackoverflow.com/questions/14117025/des-send-and-receive-modes-for-desfire-authentication // http://nfc-tools.googlecode.com/svn/branches/libfreefare-desfire/libfreefare/mifare_desfire.c // https://code.google.com/p/java-card-desfire-emulation/ // https://code.google.com/p/java-card-desfire-emulation/source/browse/trunk/java-card-desfire-emulation/DESfire%20Android%20App/src/des/Android/engine/DESfireApi.java // http://stackoverflow.com/questions/20055122/making-host-card-emulation-work-for-payment // http://stackoverflow.com/questions/14117025/des-send-and-receive-modes-for-desfire-authentication // http://stackoverflow.com/questions/15610329/change-cipher-encryption-decryption-mode-while-retaining-iv // http://noobstah.blogspot.de/2013/04/mifare-desfire-ev1-and-android.html // http://stackoverflow.com/questions/19296595/android-nfc-isodep-read-file-content // tja: // https://code.google.com/p/guard-application-desfire/source/browse/trunk/src/com/example/guardingapp/Utility.java // https://code.google.com/p/write-ndef-to-desfire/source/browse/trunk/src/CardReader/CardReader.java // https://code.google.com/p/nfcard/source/browse/src/com/sinpo/xnfc/tech/Iso7816.java // http://stackoverflow.com/questions/15610329/change-cipher-encryption-decryption-mode-while-retaining-iv // http://www.nxp.com/documents/other/mf_passwordrequest200902.pdf public class DesfireProtocol { private static final String TAG = DesfireProtocol.class .getName(); /* Commands */ static final byte GET_VERSION_INFO = (byte) 0x60; static final byte GET_APPLICATION_DIRECTORY = (byte) 0x6A; static final byte GET_ADDITIONAL_FRAME = (byte) 0xAF; static final byte SELECT_APPLICATION = (byte) 0x5A; static final byte READ_DATA = (byte) 0xBD; static final byte READ_RECORD = (byte) 0xBB; static final byte GET_FILES = (byte) 0x6F; static final byte GET_FILE_SETTINGS = (byte) 0xF5; static final byte INIT_AUTH = (byte) 0x0a; static final byte FINISH_AUTH = (byte) 0xAF; static final byte GET_KEY_VERSION = (byte) 0x64; static final byte WRITE_DATA = (byte) 0x3D; static final byte CREATE_APPLICATION = (byte) 0xCA; // {6 bytes: cmd, , , , uint8 settings, uint8 keyNo} static final byte DELETE_APPLICATION = (byte) 0xDA; // {4 bytes: } /* Status codes */ public static final byte OPERATION_OK = (byte) 0x00; public static final byte NO_CHANGES = (byte) 0x0C; public static final byte OUT_OF_EEPROM_ERROR = (byte) 0x0E; public static final byte ILLEGAL_COMMAND_CODE = (byte) 0x1C; public static final byte INTEGRITY_ERROR = (byte) 0x1E; public static final byte NO_SUCH_KEY = (byte) 0x40; public static final byte LENGTH_ERROR = (byte) 0x7E; public static final byte PERMISSION_ERROR = (byte) 0x9D; public static final byte PARAMETER_ERROR = (byte) 0x9E; public static final byte APPLICATION_NOT_FOUND = (byte) 0xA0; public static final byte APPL_INTEGRITY_ERROR = (byte) 0xA1; public static final byte AUTHENTICATION_ERROR = (byte) 0xAE; public static final byte ADDITIONAL_FRAME = (byte) 0xAF; public static final byte BOUNDARY_ERROR = (byte) 0xBE; public static final byte PICC_INTEGRITY_ERROR = (byte) 0xC1; public static final byte COMMAND_ABORTED = (byte) 0xCA; public static final byte PICC_DISABLED_ERROR = (byte) 0xCD; public static final byte COUNT_ERROR = (byte) 0xCE; public static final byte DUPLICATE_ERROR = (byte) 0xDE; public static final byte EEPROM_ERROR = (byte) 0xEE; public static final byte FILE_NOT_FOUND = (byte) 0xF0; public static final byte FILE_INTEGRITY_ERROR = (byte) 0xF1; static final byte APPLICATION_CRYPTO_DES = (byte) 0x00; static final byte APPLICATION_CRYPTO_3K3DES = (byte) 0x40; static final byte APPLICATION_CRYPTO_AES = (byte) 0x80; private IsoDepWrapper mTagTech; public DesfireProtocol(IsoDepWrapper tagTech) { mTagTech = tagTech; } public void selectApp(int appId) throws Exception { byte[] appIdBuff = new byte[3]; appIdBuff[0] = (byte) ((appId & 0xFF0000) >> 16); appIdBuff[1] = (byte) ((appId & 0xFF00) >> 8); appIdBuff[2] = (byte) (appId & 0xFF); sendRequest(SELECT_APPLICATION, appIdBuff); } public int[] getFileList() throws Exception { byte[] buf = sendRequest(GET_FILES); int[] fileIds = new int[buf.length]; for (int x = 0; x < buf.length; x++) { fileIds[x] = (int) buf[x]; } return fileIds; } public byte[] readFile(int fileNo) throws Exception { return sendRequest(READ_DATA, new byte[]{ (byte) fileNo, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0 }); } public byte[] readRecord(int fileNum) throws Exception { return sendRequest(READ_RECORD, new byte[]{ (byte) fileNum, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0 }); } private byte[] sendRequest(byte command) throws Exception { return sendRequest(command, null); } public VersionInfo getVersionInfo() throws Exception { byte[] bytes = sendRequest(GET_VERSION_INFO); // Log.d(TAG, "Version info " + ACRCommands.toHexString(bytes)); return new VersionInfo(bytes); } private byte[] sendRequest(byte command, byte[] parameters) throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] recvBuffer = mTagTech.transceive(wrapMessage(command, parameters)); while (true) { if (recvBuffer[recvBuffer.length - 2] != (byte) 0x91) throw new Exception("Invalid response"); output.write(recvBuffer, 0, recvBuffer.length - 2); byte status = recvBuffer[recvBuffer.length - 1]; if (status == OPERATION_OK) { break; } else if (status == ADDITIONAL_FRAME) { recvBuffer = mTagTech.transceive(wrapMessage(GET_ADDITIONAL_FRAME, null)); } else if (status == PERMISSION_ERROR) { throw new Exception("Permission denied"); } else { throw new Exception("Unknown status code: " + Integer.toHexString(status & 0xFF)); } } return output.toByteArray(); } private byte[] wrapMessage(byte command, byte[] parameters) throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.write((byte) 0x90); stream.write(command); stream.write((byte) 0x00); stream.write((byte) 0x00); if (parameters != null) { stream.write((byte) parameters.length); stream.write(parameters); } stream.write((byte) 0x00); return stream.toByteArray(); } public boolean createApplication(byte[] aid, byte keyNumber) { //sendCommand(Utils.hexStringToByteArray("90 CA 00 00 05 " + Utils.addSpaces(AID)+ " 01 "+Utils.hexDump(keyNumber)+" 00"));//Create App throw new RuntimeException(); } }
41.276836
167
0.671503
b9c87b7e67e7a8ff5df01df2a618e8a4fdf21793
6,270
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template unit_test.java // Do not modify package org.projectfloodlight.openflow.protocol.ver13; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import static org.junit.Assert.*; import org.junit.Test; import org.junit.Before; import java.util.Set; import com.google.common.collect.ImmutableSet; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.hamcrest.CoreMatchers; public class OFBsnVirtualPortCreateRequestVer13L2GreTest { OFFactory factory; final static byte[] BSN_VIRTUAL_PORT_CREATE_REQUEST_SERIALIZED = new byte[] { 0x4, 0x4, 0x0, 0x50, 0x1, 0x2, 0x3, 0x4, 0x0, 0x5c, 0x16, (byte) 0xc7, 0x0, 0x0, 0x0, 0xf, 0x0, 0x1, 0x0, 0x40, 0x0, 0x0, 0x0, 0x1b, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, (byte) 0xc0, 0x0, 0x0, 0x2, (byte) 0xc0, 0x0, 0x10, 0x2, 0x1, 0x40, 0x0, 0x0, 0x0, 0x0, (byte) 0xbe, (byte) 0xef, 0x0, 0x0, 0x4, 0x0, 0x66, 0x6f, 0x6f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }; @Before public void setup() { factory = OFFactoryVer13.INSTANCE; } @Test public void testWrite() { OFBsnVirtualPortCreateRequest.Builder builder = factory.buildBsnVirtualPortCreateRequest(); builder.setXid(0x01020304) .setVport( factory.buildBsnVportL2Gre() .setFlags( ImmutableSet.<OFBsnVportL2GreFlags>of( OFBsnVportL2GreFlags.BSN_VPORT_L2GRE_LOCAL_MAC_IS_VALID, OFBsnVportL2GreFlags.BSN_VPORT_L2GRE_DSCP_ASSIGN, OFBsnVportL2GreFlags.BSN_VPORT_L2GRE_LOOPBACK_IS_VALID, OFBsnVportL2GreFlags.BSN_VPORT_L2GRE_RATE_LIMIT_IS_VALID ) ) .setPortNo(OFPort.of(1)) .setLoopbackPortNo(OFPort.of(2)) .setLocalMac(MacAddress.of("0a:0b:0c:0d:0e:0f")) .setNhMac(MacAddress.of("01:02:03:04:05:06")) .setSrcIp(IPv4Address.of("192.0.0.2")) .setDstIp(IPv4Address.of("192.0.16.2")) .setDscp((short)1) .setTtl((short)64) .setVpn(0xbeef) .setRateLimit(0x400) .setIfName("foo") .build() );; OFBsnVirtualPortCreateRequest bsnVirtualPortCreateRequest = builder.build(); ByteBuf bb = Unpooled.buffer(); bsnVirtualPortCreateRequest.writeTo(bb); byte[] written = new byte[bb.readableBytes()]; bb.readBytes(written); assertThat(written, CoreMatchers.equalTo(BSN_VIRTUAL_PORT_CREATE_REQUEST_SERIALIZED)); } @Test public void testRead() throws Exception { OFBsnVirtualPortCreateRequest.Builder builder = factory.buildBsnVirtualPortCreateRequest(); builder.setXid(0x01020304) .setVport( factory.buildBsnVportL2Gre() .setFlags( ImmutableSet.<OFBsnVportL2GreFlags>of( OFBsnVportL2GreFlags.BSN_VPORT_L2GRE_LOCAL_MAC_IS_VALID, OFBsnVportL2GreFlags.BSN_VPORT_L2GRE_DSCP_ASSIGN, OFBsnVportL2GreFlags.BSN_VPORT_L2GRE_LOOPBACK_IS_VALID, OFBsnVportL2GreFlags.BSN_VPORT_L2GRE_RATE_LIMIT_IS_VALID ) ) .setPortNo(OFPort.of(1)) .setLoopbackPortNo(OFPort.of(2)) .setLocalMac(MacAddress.of("0a:0b:0c:0d:0e:0f")) .setNhMac(MacAddress.of("01:02:03:04:05:06")) .setSrcIp(IPv4Address.of("192.0.0.2")) .setDstIp(IPv4Address.of("192.0.16.2")) .setDscp((short)1) .setTtl((short)64) .setVpn(0xbeef) .setRateLimit(0x400) .setIfName("foo") .build() );; OFBsnVirtualPortCreateRequest bsnVirtualPortCreateRequestBuilt = builder.build(); ByteBuf input = Unpooled.copiedBuffer(BSN_VIRTUAL_PORT_CREATE_REQUEST_SERIALIZED); // FIXME should invoke the overall reader once implemented OFBsnVirtualPortCreateRequest bsnVirtualPortCreateRequestRead = OFBsnVirtualPortCreateRequestVer13.READER.readFrom(input); assertEquals(BSN_VIRTUAL_PORT_CREATE_REQUEST_SERIALIZED.length, input.readerIndex()); assertEquals(bsnVirtualPortCreateRequestBuilt, bsnVirtualPortCreateRequestRead); } @Test public void testReadWrite() throws Exception { ByteBuf input = Unpooled.copiedBuffer(BSN_VIRTUAL_PORT_CREATE_REQUEST_SERIALIZED); // FIXME should invoke the overall reader once implemented OFBsnVirtualPortCreateRequest bsnVirtualPortCreateRequest = OFBsnVirtualPortCreateRequestVer13.READER.readFrom(input); assertEquals(BSN_VIRTUAL_PORT_CREATE_REQUEST_SERIALIZED.length, input.readerIndex()); // write message again ByteBuf bb = Unpooled.buffer(); bsnVirtualPortCreateRequest.writeTo(bb); byte[] written = new byte[bb.readableBytes()]; bb.readBytes(written); assertThat(written, CoreMatchers.equalTo(BSN_VIRTUAL_PORT_CREATE_REQUEST_SERIALIZED)); } }
44.15493
472
0.69681
7def5d9f6f88953c6024d471aa2c00b0711d7d01
2,339
package com.danielflower.apprunner.runners; import com.danielflower.apprunner.Config; import org.apache.commons.lang3.StringUtils; import org.apache.maven.shared.invoker.DefaultInvocationRequest; import org.apache.maven.shared.invoker.InvocationRequest; import java.io.File; import java.util.Collections; import java.util.Optional; import static com.danielflower.apprunner.runners.MavenRunner.CLEAN_AND_PACKAGE; public class MavenRunnerFactory implements AppRunnerFactory { private final HomeProvider javaHomeProvider; private final String versionInfo; public MavenRunnerFactory(HomeProvider javaHomeProvider, String versionInfo) { this.javaHomeProvider = javaHomeProvider; this.versionInfo = versionInfo; } @Override public String id() { return "maven"; } @Override public String sampleProjectName() { return "maven.zip"; } @Override public String description() { return "Java uber jars built with maven"; } @Override public String[] startCommands() { return MavenRunner.startCommands; } @Override public AppRunner appRunner(File folder) { return new MavenRunner(folder, javaHomeProvider, CLEAN_AND_PACKAGE); } @Override public String versionInfo() { return versionInfo; } @Override public boolean canRun(File appDirectory) { return new File(appDirectory, "pom.xml").isFile(); } public static Optional<MavenRunnerFactory> createIfAvailable(Config config) { HomeProvider homeProvider = config.javaHomeProvider(); StringBuffer out = new StringBuffer(); InvocationRequest request = new DefaultInvocationRequest() .setOutputHandler((str) -> out.append(str).append(" - ")) .setErrorHandler((str) -> out.append(str).append(" - ")) .setShowVersion(true) .setGoals(Collections.singletonList("--version")) .setBaseDirectory(new File(".")); try { MavenRunner.runRequest(request, homeProvider); String versionInfo = StringUtils.removeEndIgnoreCase(out.toString(), " - "); return Optional.of(new MavenRunnerFactory(homeProvider, versionInfo)); } catch (Exception e) { return Optional.empty(); } } }
29.987179
88
0.67935
2c2dd19617a2715ac183b151bc21a96613c25791
433
package lesson5_aop.lesson2; /** * @author Sergey Zhernovoy * create on 18.09.2017. */ public class Magician implements MindReader { private String thougths; @Override public void interceptThougths(String thougths) { System.out.println("Intercepting volunteer's thougths"); this.thougths = thougths; } @Override public String getThougths() { return this.thougths; } }
18.041667
64
0.660508
3d314ef9e43a8a53a2cc03698114936de63fd878
1,473
/* * Copyright (C) 2004-2016 L2J DataPack * * This file is part of L2J DataPack. * * L2J DataPack is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * L2J DataPack is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package hellbound.AI; import ai.npc.AbstractNpcAI; import com.l2jserver.gameserver.model.actor.L2Npc; import com.l2jserver.gameserver.model.actor.instance.L2MonsterInstance; import com.l2jserver.gameserver.model.actor.instance.L2PcInstance; /** * Naia Lock AI.<br> * Removes minions after master's death. * @author GKR */ public final class NaiaLock extends AbstractNpcAI { // NPCs private static final int LOCK = 18491; public NaiaLock() { super(NaiaLock.class.getSimpleName(), "hellbound/AI"); addKillId(LOCK); } @Override public String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon) { ((L2MonsterInstance) npc).getMinionList().onMasterDie(true); return super.onKill(npc, killer, isSummon); } }
30.061224
71
0.74406
c8b84caba88fb98234396c6ab5d65e7d8ea6ccbb
228
package com.noobug.nooblog.repository; import com.noobug.nooblog.domain.Authority; import org.springframework.data.jpa.repository.JpaRepository; public interface AuthorityRepository extends JpaRepository<Authority, Long> { }
25.333333
77
0.837719
1176c627b94fee0048d06f835b5aad14af161140
6,051
/* * Copyright 2019 The caver-java Authors * * Licensed under the Apache License, Version 2.0 (the “License”); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an “AS IS” BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.klaytn.caver.tx.account; import com.fasterxml.jackson.annotation.JsonProperty; import com.klaytn.caver.utils.AccountKeyPublicUtils; import com.klaytn.caver.utils.BytesUtils; import org.web3j.rlp.*; import org.web3j.utils.Numeric; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * AccountKeyWeightedMultiSig is an account key type containing a threshold and WeightedPublicKeys. * WeightedPublicKeys contains a slice of {weight and key}. To be a valid tx for an account associated * with AccountKeyWeightedMultiSig, the weighted sum of signed public keys should be larger than the threshold. */ public class AccountKeyWeightedMultiSig implements AccountKey { /** * Validation threshold. To be a valid transaction, the weight sum of signatures should be larger than * or equal to the threshold. */ private BigInteger threshold; /** * A slice of weighted public keys. A weighted public key contains a weight and a public key. */ private List<WeightedPublicKey> weightedPublicKeys = new ArrayList<>(); public static AccountKeyWeightedMultiSig create(BigInteger threshold, List<WeightedPublicKey> weightedPublicKeys) { return new AccountKeyWeightedMultiSig(threshold, weightedPublicKeys); } public AccountKeyWeightedMultiSig() { } public AccountKeyWeightedMultiSig(BigInteger threshold, List<WeightedPublicKey> weightedPublicKeys) { this.threshold = threshold; this.weightedPublicKeys.addAll(weightedPublicKeys); } public BigInteger getThreshold() { return threshold; } @JsonProperty("keys") public List<WeightedPublicKey> getWeightedPublicKeys() { return weightedPublicKeys; } @Override public byte[] toRlp() { List<RlpType> rlpTypeList = new ArrayList<>(); rlpTypeList.add(RlpString.create(threshold)); List<RlpType> rlpWeightedPublicKeys = new ArrayList<>(); for (WeightedPublicKey item : this.weightedPublicKeys) { List<RlpType> rlpWeightedPublicKey = new ArrayList<>(); rlpWeightedPublicKey.addAll(Arrays.asList( RlpString.create(item.weight), RlpString.create(Numeric.hexStringToByteArray(item.key.toCompressedPublicKey())))); rlpWeightedPublicKeys.add(new RlpList(rlpWeightedPublicKey)); } rlpTypeList.add(new RlpList(rlpWeightedPublicKeys)); byte[] encodedTransaction = RlpEncoder.encode(new RlpList(rlpTypeList)); byte[] type = {getType().getValue()}; return BytesUtils.concat(type, encodedTransaction); } public static AccountKeyWeightedMultiSig decodeFromRlp(byte[] rawTransaction) { byte[] transaction = AccountKeyDecoder.getRawTransactionNoType(rawTransaction); RlpList rlpList = RlpDecoder.decode(transaction); RlpList values = (RlpList) rlpList.getValues().get(0); BigInteger threshold = ((RlpString) values.getValues().get(0)).asPositiveBigInteger(); List<WeightedPublicKey> weightedPublicKeys = new ArrayList<>(); RlpList rlpWeightedPublicKeys = (RlpList) values.getValues().get(1); for (RlpType item : rlpWeightedPublicKeys.getValues()) { RlpList rlpWeightedPublicKey = (RlpList) item; BigInteger weight = ((RlpString) rlpWeightedPublicKey.getValues().get(0)).asPositiveBigInteger(); String compressedPublicKey = ((RlpString) rlpWeightedPublicKey.getValues().get(1)).asString(); weightedPublicKeys.add(new WeightedPublicKey(weight, AccountKeyPublicUtils.decompressKey(compressedPublicKey))); } return new AccountKeyWeightedMultiSig(threshold, weightedPublicKeys); } public static AccountKeyWeightedMultiSig decodeFromRlp(String hexString) { return decodeFromRlp(Numeric.hexStringToByteArray(hexString)); } @Override public Type getType() { return Type.MULTISIG; } public static class WeightedPublicKey { private BigInteger weight; private AccountKeyPublic key; public WeightedPublicKey() { } protected WeightedPublicKey(BigInteger weight, AccountKeyPublic key) { this.weight = weight; this.key = key; } public static WeightedPublicKey create(BigInteger weight, AccountKeyPublic accountKeyPublic) { return new WeightedPublicKey(weight, accountKeyPublic); } public BigInteger getWeight() { return weight; } public AccountKeyPublic getKey() { return key; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AccountKeyWeightedMultiSig that = (AccountKeyWeightedMultiSig) o; return Arrays.equals(toRlp(), that.toRlp()); } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("AccountKeyWeightedMultiSig : {\n"); for (WeightedPublicKey weightedPublicKey : weightedPublicKeys) { result.append("{Weight : " + weightedPublicKey.weight + " / "); result.append("PublicKey : " + weightedPublicKey.key.toString() + "}\n "); } result.append("}"); return result.toString(); } }
36.672727
124
0.691291
e10e652006e53e0a4876e2b2ce02e965adf03715
1,493
package com.ververica.cdc.connectors.tdsql.source.split; import org.apache.flink.connector.base.source.reader.RecordsWithSplitIds; import com.ververica.cdc.connectors.tdsql.bases.set.TdSqlSet; import org.apache.kafka.connect.source.SourceRecord; import javax.annotation.Nullable; import java.util.Set; import java.util.stream.Collectors; /** * An implementation of {@link RecordsWithSplitIds} which contains the records of one table split. */ public class TdSqlRecords implements RecordsWithSplitIds<SourceRecord> { private final RecordsWithSplitIds<SourceRecord> mySqlRecords; private final TdSqlSet set; public TdSqlRecords(RecordsWithSplitIds<SourceRecord> mySqlRecords, TdSqlSet set) { this.mySqlRecords = mySqlRecords; this.set = set; } @Nullable @Override public String nextSplit() { String mysqlSplitId = mySqlRecords.nextSplit(); if (mysqlSplitId == null) { return null; } return tdSqlSplitId(mysqlSplitId); } @Nullable @Override public SourceRecord nextRecordFromSplit() { return mySqlRecords.nextRecordFromSplit(); } @Override public Set<String> finishedSplits() { Set<String> finishedSplits = mySqlRecords.finishedSplits(); return finishedSplits.stream().map(this::tdSqlSplitId).collect(Collectors.toSet()); } private String tdSqlSplitId(String mysqlSplitId) { return set.getSetKey() + ":" + mysqlSplitId; } }
29.27451
98
0.713999
2617c5e953b306c41bd3da4b803e1cdb3703ed8f
1,176
package com.diamondq.reactions.engine.definitions; import com.diamondq.reactions.api.JobParamsBuilder; import com.diamondq.reactions.api.impl.ParamBuilderImpl; import com.diamondq.reactions.api.impl.StateCriteria; import java.util.Set; import java.util.function.Function; import org.checkerframework.checker.nullness.qual.Nullable; public class ParamDefinition<T> extends DependentDefinition<T> { public final @Nullable String valueByVariable; public final @Nullable Function<JobParamsBuilder, ?> valueByInput; public final boolean valueByTrigger; ParamDefinition(ParamBuilderImpl<T> pBuilder) { this(pBuilder.getParamClass(), pBuilder.getRequiredStates(), pBuilder.getName(), pBuilder.getValueByVariable(), pBuilder.getValueByInput(), pBuilder.isValueByTrigger()); } public ParamDefinition(Class<T> pClazz, Set<StateCriteria> pRequiredStates, @Nullable String pName, @Nullable String pValueByVariable, @Nullable Function<JobParamsBuilder, ?> pValueByInput, boolean pValueByTrigger) { super(pClazz, pRequiredStates, pName); valueByVariable = pValueByVariable; valueByInput = pValueByInput; valueByTrigger = pValueByTrigger; } }
33.6
113
0.797619
b3078a8091c89f3617ba057092a559effd84271f
2,465
package de.rnd7.miele.api; import org.apache.client.sse.ApacheHttpSseClient; import org.apache.client.sse.Event; import org.apache.client.sse.SseRequest; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class SSEClient { private static final Logger LOGGER = LoggerFactory.getLogger(SSEClient.class); private final ExecutorService executor = Executors.newFixedThreadPool(1); private CloseableHttpAsyncClient asyncClient; BlockingQueue<Event> subscribe(final MieleAPI api) throws Exception { LOGGER.debug("Subscribe SSE"); final String token = api.getToken().getAccessToken(); asyncClient = HttpAsyncClients.createDefault(); asyncClient.start(); final SseRequest request = new SseRequest("https://api.mcs3.miele.com/v1/devices/all/events"); request.setHeader("Accept-Language", "en-GB"); request.setHeader("Authorization", "Bearer " + token); return new ApacheHttpSseClient(asyncClient, executor) .execute(request) .get(10, TimeUnit.SECONDS) .getEntity() .getEvents(); } void shutdown() { closeClient(); executor.shutdown(); } void closeClient() { if (asyncClient != null) { try { asyncClient.close(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } } boolean isRunning() { return asyncClient.isRunning(); } public void start(final MieleAPI api, final MieleEventListener listener) { while (true) { // NOSONAR try { final BlockingQueue<Event> events = subscribe(api); listener.state(MieleAPIState.connected); new SSEClientHandler(events, asyncClient, listener::accept).run(); } catch (Exception e) { listener.state(MieleAPIState.disconnected); LOGGER.error(e.getMessage(), e); if (!api.waitReconnect()) { shutdown(); return; } } } } }
32.012987
102
0.627586
6947331e6a789132a5aa0de2219671932eb78255
2,264
package talk.ramlbpmn.api.model; import java.util.HashMap; import java.util.Map; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * The links of an Artist * */ @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "self", "songs" }) public class ArtistLinks { /** * A HAL link * */ @JsonProperty("self") private HalLink self; /** * A HAL link * */ @JsonProperty("songs") private HalLink songs; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * A HAL link * * @return * The self */ @JsonProperty("self") public HalLink getSelf() { return self; } /** * A HAL link * * @param self * The self */ @JsonProperty("self") public void setSelf(HalLink self) { this.self = self; } public ArtistLinks withSelf(HalLink self) { this.self = self; return this; } /** * A HAL link * * @return * The songs */ @JsonProperty("songs") public HalLink getSongs() { return songs; } /** * A HAL link * * @param songs * The songs */ @JsonProperty("songs") public void setSongs(HalLink songs) { this.songs = songs; } public ArtistLinks withSongs(HalLink songs) { this.songs = songs; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public ArtistLinks withAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); return this; } }
20.214286
85
0.613958
575ac84dfc3e015b1b79b17de23f4b1cc4c52a96
541
package net.ssehub.easy.instantiation.core.model.vilTypes.configuration; /** * A no filter, i.e., a filter which includes everything. * * @author Holger Eichelberger */ class NoFilter implements IConfigurationFilter { /** * The singleton instance of this filter. */ public static final IConfigurationFilter INSTANCE = new NoFilter(); /** * Prevents external creation. */ private NoFilter() { } @Override public boolean include(IvmlElement element) { return true; } }
20.037037
72
0.654344
1f9b4016a13c7598c193c7ce08c7c518f9461062
20,215
/* * Copyright 2015 Karlsruhe Institute of Technology. * * 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 edu.kit.dama.util.release; import edu.kit.dama.util.release.config.ReleaseConfiguration; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.collections.Predicate; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.maven.model.Dependency; import org.apache.maven.model.Developer; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.Profile; import org.apache.maven.model.Repository; import org.apache.maven.model.Scm; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** * * @author mf6319 */ public class GenerateSourceRelease { final static String MAVEN_REPOSITORY = "/Users/jejkal/.m2/repository"; private enum RELEASE_TYPE { KITDM, GENERIC_CLIENT, BARE_DEMO } //For KIT DM Source Release //private final static String[] sourceFolders = new String[]{"Authorization", "Commons", "Core", "DataOrganization", "DataWorkflow", "Documentation", "MetaDataManagement", "RestInterfaces", "Scheduler", "Staging", "UserInterface", "Utils"}; //For BaReDemo Source Release //private final static String[] sourceFolders = new String[]{"src"}; //Common for all // private final static String[] foldersToIgnore = new String[]{"target", "srcRelease"}; // private final static String[] filesToIgnore = new String[]{"nbactions*.xml", "nb-configuration.xml", "dependency-reduced-pom.xml", "filter.ipejejkal2.properties"}; public static void generateSourceRelease(ReleaseConfiguration config) throws IOException, XmlPullParserException { File source = new File(config.getSourceDirectory()); File destination = new File(config.getDestinationDirectory(), "srcRelease"); destination.mkdirs(); copySources(source, destination, config); checkLicenseHeaders(destination); updatePom(destination, config); } public static void copySources(File source, File destination, final ReleaseConfiguration config) throws IOException { for (String folder : config.getInputDirectories()) { File input = new File(source, folder); if (!input.exists()) { //warn continue; } new File(destination, folder).mkdirs(); FileUtils.copyDirectory(input, new File(destination, folder), new FileFilter() { @Override public boolean accept(File pathname) { //check folders to ignore for (String folder : config.getDirectoriesToIgnore()) { if (pathname.isDirectory() && folder.equals(pathname.getName())) { return false; } } //check files to ignore for (String file : config.getFilesToIgnore()) { if (pathname.isFile() && new WildcardFileFilter(file).accept(pathname)) { return false; } } return true; } }); } for (String file : config.getFilesToRemove()) { FileUtils.deleteQuietly(new File(destination, file)); } for (String file : config.getInputFiles()) { File input = new File(source, file); if (input.exists()) { FileUtils.copyFile(new File(source, file), new File(destination, file)); } else { //warn } } } public static void checkLicenseHeaders(File destination) throws IOException { //check license headers Collection<File> files = FileUtils.listFiles(destination, new String[]{"java", "xml"}, true); for (File f : files) { boolean haveLicense = false; try (BufferedReader bf = new BufferedReader(new FileReader(f))) { String line; while ((line = bf.readLine()) != null) { if (line.contains("Licensed under the Apache License")) { haveLicense = true; break; } } } if (!haveLicense) { System.out.println("File " + f + " seems to have no/an invalid license header."); } } } public static void updatePom(File destination, ReleaseConfiguration config) throws IOException, XmlPullParserException { File pomfile = new File(destination, "pom.xml"); FileUtils.copyFile(pomfile, new File(destination, "pom.original.xml")); MavenXpp3Reader mavenreader = new MavenXpp3Reader(); FileReader reader = new FileReader(pomfile); Model model = mavenreader.read(reader); model.setPomFile(pomfile); if (config.isRemoveDevelopers()) { model.setDevelopers(new ArrayList<Developer>()); } if (config.isRemoveDistributionManagement()) { model.setDistributionManagement(null); } if (config.isRemoveCiManagement()) { model.setCiManagement(null); } if (config.getScmConnection() != null || config.getScmUrl() != null) { Scm scm = new Scm(); scm.setConnection(config.getScmConnection()); scm.setUrl(config.getScmUrl()); model.setScm(scm); } for (final String profile : config.getProfilesToRemove()) { Profile toRemove = (Profile) org.apache.commons.collections.CollectionUtils.find(model.getProfiles(), new Predicate() { @Override public boolean evaluate(Object o) { return profile.equals(((Profile) o).getId()); } }); if (toRemove != null) { model.getProfiles().remove(toRemove); } } for (final String plugin : config.getPluginsToRemove()) { Plugin toRemove = (Plugin) org.apache.commons.collections.CollectionUtils.find(model.getBuild().getPlugins(), new Predicate() { @Override public boolean evaluate(Object o) { return plugin.equals(((Plugin) o).getArtifactId()); } }); if (toRemove != null) { model.getBuild().getPlugins().remove(toRemove); } } for (final String module : config.getModulesToRemove()) { String toRemove = (String) org.apache.commons.collections.CollectionUtils.find(model.getModules(), new Predicate() { @Override public boolean evaluate(Object o) { return module.equals((String) o); } }); if (toRemove != null) { model.getModules().remove(toRemove); } } for (String property : config.getPropertiesToRemove()) { model.getProperties().remove(property); } Set<Entry<String, String>> entries = config.getPropertiesToSet().entrySet(); for (Entry<String, String> entry : entries) { model.getProperties().put(entry.getKey(), entry.getValue()); } if (config.getLocalDependencies().length != 0) { //add local dependencies for (Dependency dependency : config.getLocalDependencies()) { String groupId = dependency.getGroupId(); String artifactId = dependency.getArtifactId(); String version = dependency.getVersion(); String dependencyPath = groupId.replaceAll("\\.", File.separator) + File.separator + artifactId + File.separator + version; String mavenRepoPath = MAVEN_REPOSITORY + File.separator + dependencyPath; String localRepoPath = config.getDestinationDirectory() + File.separator + "srcRelease" + File.separator + "libs" + File.separator + dependencyPath; if (!new File(localRepoPath).mkdirs() && !new File(localRepoPath).exists()) { throw new IOException("Failed to create local repository path at " + localRepoPath); } String artifactFileName = artifactId + "-" + version + ".jar"; String pomFileName = artifactId + "-" + version + ".pom"; File artifact = new File(mavenRepoPath, artifactFileName); File pom = new File(mavenRepoPath, pomFileName); if (artifact.exists() && pom.exists()) { FileUtils.copyFile(artifact, new File(localRepoPath, artifactFileName)); FileUtils.copyFile(pom, new File(localRepoPath, pomFileName)); } else { throw new IOException("Dependency " + groupId + ":" + artifactId + ":" + version + " not found at " + mavenRepoPath); } } //check local repo boolean haveLocalRepo = false; for (Repository repository : model.getRepositories()) { String repoUrl = repository.getUrl(); URL u = new URL(repoUrl); if ("file".equals(u.getProtocol())) { haveLocalRepo = true; break; /** * <repository> * <id>localRepository</id> * <url>file://${basedir}/${root.relative.path}/libs</url> * </repository> */ } } if (!haveLocalRepo) { //add local repo Repository localRepository = new Repository(); localRepository.setId("localRepository"); localRepository.setUrl("file://${basedir}/lib/"); localRepository.setName("Local file repository"); model.getRepositories().add(0, localRepository); } } // MavenProject project = new MavenProject(model); //check parent (fail if exists) // MavenXpp3Writer mavenwriter = new MavenXpp3Writer(); mavenwriter.write(new FileOutputStream(new File(destination, "pom.xml")), model); } public static ReleaseConfiguration getGenericRepoClientSourceReleaseConfig(String source, String destination) { ReleaseConfiguration config = new ReleaseConfiguration(); config.setConfigurationName("GenericClient"); config.setSourceDirectory("/Users/jejkal/NetBeansProjects/KITDM_EXT/tags/GenericRepoClient-1.4"); config.setDestinationDirectory("/Users/jejkal/NetBeansProjects/KITDM_EXT/trunk/GenericRestClient"); //config.setScmConnection("https://github.com/kit-data-manager/genericRepoClient"); config.setScmUrl("https://github.com/kit-data-manager/genericRepoClient"); config.setInputDirectories(new String[]{"src", "lib"}); config.setInputFiles(new String[]{"pom.xml"}); config.setFilesToIgnore(new String[]{"nbactions*.xml", "nb-configuration.xml", "dependency-reduced-pom.xml", "filter.ipejejkal2.properties", "filter.bess.properties", "filter.nsc.properties", "filter.anka.properties", "filter.vm.properties"}); config.setDirectoriesToIgnore(new String[]{"target", "srcRelease"}); config.setRemoveDevelopers(true); config.setRemoveDistributionManagement(true); Dependency d1 = new Dependency(); d1.setGroupId("edu.kit.cmdline"); d1.setArtifactId("CommandlineTools"); d1.setVersion("1.1"); Dependency d2 = new Dependency(); d2.setGroupId("edu.kit"); d2.setArtifactId("ADALAPI"); d2.setVersion("2.3"); Dependency d3 = new Dependency(); d3.setGroupId("au.edu.apsr"); d3.setArtifactId("mtk"); d3.setVersion("1.1"); config.setLocalDependencies(new Dependency[]{d1, d2}); config.addProperty("group", "release"); return config; } public static Dependency factoryDependency(String groupId, String artifactId, String version) { Dependency d = new Dependency(); d.setGroupId(groupId); d.setArtifactId(artifactId); d.setVersion(version); return d; } public static ReleaseConfiguration getKITDMSourceReleaseConfig(String source, String destination) { ReleaseConfiguration config = new ReleaseConfiguration(); config.setConfigurationName("KIT Data Manager"); config.setSourceDirectory(source); config.setDestinationDirectory(destination); config.setScmUrl("https://github.com/kit-data-manager/base"); config.setScmConnection("https://github.com/kit-data-manager/base"); config.setInputDirectories(new String[]{"Authorization", "Commons", "Core", "DataOrganization", "DataOrganization_Neo4j", "DataWorkflow", "Documentation", "MetaDataManagement", "RestInterfaces", "Samples", "Scheduler", "Staging", "src/test", "UserInterface", "Utils"}); config.setInputFiles(new String[]{"pom.xml"}); config.setFilesToIgnore(new String[]{"nbactions*.xml", "nb-configuration.xml", "dependency-reduced-pom.xml", "filter.ipejejkal2.properties", "filter.bess.properties", "filter.nsc.properties", "filter.anka.properties", "filter.vm.properties", "migrationObject.xml"}); config.setFilesToRemove(new String[]{"Samples/src/main/resources/META-INF/persistence.xml", "Samples/src/main/resources/logback.xml", "Utils/src/main/resources/logback.xml", "Utils/src/main/resources/META-INF/persistence.xml"}); config.setDirectoriesToIgnore(new String[]{"target", "srcRelease", "metadata", ".settings"}); config.setModulesToRemove(new String[]{"FunctionalTests"}); config.setPropertiesToRemove(new String[]{"firstName", "lastName", "nameId"}); config.setRemoveDevelopers(true); config.setRemoveDistributionManagement(true); Dependency commandlineTools = factoryDependency("edu.kit.cmdline", "CommandlineTools", "1.1"); Dependency adalapi = factoryDependency("edu.kit", "ADALAPI", "2.3"); Dependency mail = factoryDependency("org.fzk.globus", "mail", "4.0.8"); Dependency soton = factoryDependency("org.fzk.globus", "soton-hicog", "4.0.2"); Dependency gridutil = factoryDependency("org.fzk.ipe", "grid-util", "2.1"); Dependency tools = factoryDependency("org.fzk.ipe", "Tools", "1.6"); Dependency mtk = factoryDependency("au.edu.apsr", "mtk", "1.1"); config.setLocalDependencies(new Dependency[]{commandlineTools, adalapi, mail, soton, gridutil, tools, mtk}); return config; } public static ReleaseConfiguration getBaReDemoSourceReleaseConfig(String source, String destination) { ReleaseConfiguration config = new ReleaseConfiguration(); config.setConfigurationName("Basic Repository Demonstrator"); config.setSourceDirectory(source); config.setDestinationDirectory(destination); config.setScmUrl("https://github.com/kit-data-manager/basic-repository-demonstrator"); config.setScmConnection("https://github.com/kit-data-manager/basic-repository-demonstrator"); config.setInputDirectories(new String[]{"Docker", "libs", "src"}); config.setInputFiles(new String[]{"pom.xml", "makeDist.sh",}); config.setFilesToIgnore(new String[]{"nbactions*.xml", "nb-configuration.xml", "dependency-reduced-pom.xml", "filter.ipejejkal.properties"}); config.setDirectoriesToIgnore(new String[]{"target", "srcRelease", ".settings"}); config.setPropertiesToRemove(new String[]{"firstName", "lastName", "nameId"}); config.setPluginsToRemove(new String[]{"maven-release-plugin", "maven-surefire-plugin"}); config.setRemoveDevelopers(true); config.setRemoveDistributionManagement(true); Dependency adminui = factoryDependency("edu.kit.dama", "AdminUI", "1.3"); config.setLocalDependencies(new Dependency[]{adminui}); return config; } public static void main(String[] args) throws Exception { if (args.length != 3) { System.err.println("Usage: GenerateSourceRelease TYPE SOURCE DESTINATION"); System.err.println(""); System.err.println("TYPE\tThe release type. Must be one of KITDM, GENERIC_CLIENT or BARE_DEMO"); System.err.println("SOURCE\tThe source folder containing all sources for the selected release type."); System.err.println("DESTINATION\tThe destination folder where all sources of the release are placed."); System.exit(1); } String releaseType = args[0]; RELEASE_TYPE type = RELEASE_TYPE.KITDM; try { type = RELEASE_TYPE.valueOf(releaseType); } catch (IllegalArgumentException ex) { System.err.println("Invalid release type. Valid relase types arguments are KITDM, GENERIC_CLIENT or BARE_DEMO"); System.exit(1); } String source = args[1]; String destination = args[2]; File sourceFile = new File(source); File destinationFile = new File(destination); if ((sourceFile.exists() && !sourceFile.isDirectory()) || (destinationFile.exists() && !destinationFile.isDirectory())) { System.err.println("Either source or destination are no directories."); System.exit(1); } if (!sourceFile.exists() || !sourceFile.canRead()) { System.err.println("Source either does not exist or is not readable."); System.exit(1); } if ((destinationFile.exists() && !sourceFile.canWrite()) || (!destinationFile.exists() && !destinationFile.mkdirs())) { System.err.println("Destination is either not writable or cannot be created."); System.exit(1); } ReleaseConfiguration config = null; switch (type) { case KITDM: config = getKITDMSourceReleaseConfig(source, destination); break; case GENERIC_CLIENT: config = getGenericRepoClientSourceReleaseConfig(source, destination); break; case BARE_DEMO: config = getBaReDemoSourceReleaseConfig(source, destination); break; } generateSourceRelease(config); System.out.println("Generating Release finished."); System.out.println("Please manually check pom.xml:"); System.out.println(" - Remove profiles"); System.out.println(" - Update links to SCM, ciManagement and internal repositories"); } }
46.471264
278
0.608558
722f9cb6a317b4162b588de4ac42b6f243bc7e01
2,039
package ifcconverter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class ObjThread extends Thread { ProcessBuilder ifcconvert_builder; Process ifcconvert_p; BufferedWriter ifcconvert_p_stdin; int fifcstart; int fifcend; File[] ifcs; ObjThread(File ifcs[], int start, int end){ this.ifcs = ifcs; this.fifcstart = start; this.fifcend = end; // init shell ifcconvert_builder = new ProcessBuilder( "cmd.exe" ); ifcconvert_p=null; try { ifcconvert_p = ifcconvert_builder.start(); ifcconvert_p_stdin = new BufferedWriter(new OutputStreamWriter(ifcconvert_p.getOutputStream())); ifcconvert_p_stdin.write("cd " + Main.OBJS_PATH); ifcconvert_p_stdin.newLine(); ifcconvert_p_stdin.flush(); } catch (IOException e) { e.printStackTrace(); } } public void run() { try { for (int i=fifcstart; i<fifcend;i++) { if (!((new File (Main.OBJS_PATH + ifcs[i].getName().split(".ifc")[0] + ".obj")).exists())) { ifcconvert_p_stdin.write("IfcConvert \"../IFCs/" + ifcs[i].getName() + "\" \"./" + ifcs[i].getName().split(".ifc")[0] + ".obj\""); ifcconvert_p_stdin.newLine(); ifcconvert_p_stdin.flush(); } } // finally close the shell by execution exit command ifcconvert_p_stdin.write("exit"); ifcconvert_p_stdin.newLine(); ifcconvert_p_stdin.flush(); // Write the output to the console (essential or the rest would not work for some reason) BufferedReader ifcconvert_br = new BufferedReader(new InputStreamReader(ifcconvert_p.getInputStream())); String ifcconvert_thisLine = null; while ((ifcconvert_thisLine = ifcconvert_br.readLine()) != null) { System.out.println(ifcconvert_thisLine); } } catch (IOException e) { e.printStackTrace(); } } }
30.893939
135
0.653261
b5d190a552062e877f3030bc1519288e94c688fa
1,752
/* * Copyright 2020-2021 Sweden Connect * * 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 se.swedenconnect.security.credential.factory; import java.security.cert.X509Certificate; import org.junit.Assert; import org.junit.Test; import org.springframework.core.io.ClassPathResource; /** * Test cases for X509CertificateFactoryBean. * * @author Martin Lindström (martin@idsec.se) * @author Stefan Santesson (stefan@idsec.se) */ public class X509CertificateFactoryBeanTest { @Test public void testFactory() throws Exception { X509CertificateFactoryBean factory = new X509CertificateFactoryBean(); factory.setResource(new ClassPathResource("rsa1.crt")); factory.afterPropertiesSet(); Assert.assertNotNull(factory.getObject()); Assert.assertEquals(X509Certificate.class, factory.getObjectType()); factory = new X509CertificateFactoryBean(new ClassPathResource("rsa1.crt")); factory.afterPropertiesSet(); Assert.assertNotNull(factory.getObject()); } @Test(expected = IllegalArgumentException.class) public void testMissingResource() throws Exception { X509CertificateFactoryBean factory = new X509CertificateFactoryBean(); factory.afterPropertiesSet(); } }
32.444444
80
0.754566
c7168c7a490b9c029364e33625db19f5ff9c2f77
291
package org.hzero.oauth.security.service; import io.choerodon.core.oauth.CustomUserDetails; /** * 加载 UserDetails 后的业务处理 * * @author bojiangzhou 2019/02/27 */ public interface UserDetailsWrapper { void warp(CustomUserDetails details, Long userId, Long tenantId, boolean login); }
19.4
84
0.75945
cbcb26ea65724a5b6e1f81e64a442496c56ccd31
7,510
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.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.opensingular.form.wicket.mapper.attachment; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.wicket.Component; import org.apache.wicket.IResourceListener; import org.apache.wicket.Session; import org.apache.wicket.SharedResources; import org.apache.wicket.ajax.json.JSONObject; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.model.IModel; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.ContentDisposition; import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.request.resource.ResourceReference; import org.apache.wicket.request.resource.SharedResourceReference; import org.apache.wicket.util.string.StringValue; import org.opensingular.form.SInstance; import org.opensingular.form.document.SDocument; import org.opensingular.form.type.core.attachment.IAttachmentPersistenceHandler; import org.opensingular.form.type.core.attachment.IAttachmentRef; import org.opensingular.lib.commons.util.Loggable; import static org.apache.wicket.markup.head.JavaScriptHeaderItem.forReference; /** * Behavior a ser adicionado ao componente de upload/download para permitir download dos arquivos * Busca o arquivo por meio do hash e do nome e retorna uma url com um link temporário para download * o link retornado funciona apenas uma vez. * <p> * A busca é feita primeiro no armazenamento temporárioe em seguida no permanente. * * @author vinicius */ public class DownloadSupportedBehavior extends Behavior implements IResourceListener, Loggable { private Component component; private IModel<? extends SInstance> model; private ContentDisposition contentDisposition; public DownloadSupportedBehavior(IModel<? extends SInstance> model, ContentDisposition contentDisposition) { this.model = model; this.contentDisposition = contentDisposition; } public DownloadSupportedBehavior(IModel<? extends SInstance> model) { this(model, ContentDisposition.INLINE); } @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); response.render(forReference(new PackageResourceReference(getClass(), "DownloadSupportedBehavior.js"))); } @Override public void bind(Component component) { this.component = component; } @Override public void onResourceRequested() { try { handleRequest(); } catch (IOException e) { getLogger().debug(null, e); throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } private void handleRequest() throws IOException { WebRequest request = (WebRequest) RequestCycle.get().getRequest(); IRequestParameters parameters = request.getRequestParameters(); StringValue id = parameters.getParameterValue("fileId"); StringValue name = parameters.getParameterValue("fileName"); writeResponse(getDownloadURL(id.toString(), name.toString())); } private void writeResponse(String url) throws IOException { JSONObject jsonFile = new JSONObject(); jsonFile.put("url", url); WebResponse response = (WebResponse) RequestCycle.get().getResponse(); response.setContentType("application/json"); response.setHeader("Cache-Control", "no-store, no-cache"); response.getOutputStream().write(jsonFile.toString().getBytes(StandardCharsets.UTF_8)); response.flush(); } public String getUrl() { return component.urlFor(this, IResourceListener.INTERFACE, new PageParameters()).toString(); } private AttachmentResource addAttachmentSharedResourceToCurrentSession() { String sessionKey = getSessionKey(); getWebApplication().mountResource(AttachmentResource.getMountPath(sessionKey), new SharedResourceReference(sessionKey)); AttachmentResource attachmentResource = new AttachmentResource(sessionKey); getSharedResources().add(sessionKey, attachmentResource); return attachmentResource; } private String getSessionKey() { return Session.get().getId(); } protected WebApplication getWebApplication() { return WebApplication.get(); } public AttachmentResource lookupAttachmentSharedResourceOnCurrentSession() { ResourceReference resourceReference = getSharedResources().get(Session.get().getId()); if (resourceReference == null) { return addAttachmentSharedResourceToCurrentSession(); } else { return (AttachmentResource) resourceReference.getResource(); } } protected SharedResources getSharedResources() { return getWebApplication().getSharedResources(); } /** * Registra um recurso compartilhado do wicket para permitir o download * sem bloquear a fila de ajax do wicket. * O recurso compartilhado é removido tão logo o download é executado * Esse procedimento visa garantir que somente quem tem acesso à página pode fazer * download dos arquivos. * * @param filename * @return */ String getDownloadURL(String attachmentKey, String filename) { AttachmentResource attachmentResource = lookupAttachmentSharedResourceOnCurrentSession(); return attachmentResource.addAttachment(filename, contentDisposition, findAttachmentRef(attachmentKey)); } public IAttachmentRef findAttachmentRef(String attachmentKey) { IAttachmentRef ref = null; for (IAttachmentPersistenceHandler<?> service : getHandlers()) { ref = service.getAttachment(attachmentKey); if (ref != null) { break; } } return ref; } private List<IAttachmentPersistenceHandler<?>> getHandlers() { List<IAttachmentPersistenceHandler<?>> services = new ArrayList<>(); SDocument sDocument = model.getObject().getDocument(); if (sDocument.isAttachmentPersistenceTemporaryHandlerSupported()) { services.add(sDocument.getAttachmentPersistenceTemporaryHandler()); } sDocument.getAttachmentPersistencePermanentHandler().ifPresent(services::add); return services; } }
40.594595
128
0.737017
d2673ecf84cb10b821be3b027074fa4cc58d3d13
1,835
package org.pentaho.di.core.compress.zip; import java.io.IOException; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.pentaho.di.core.Const; import org.pentaho.di.core.compress.CompressionOutputStream; import org.pentaho.di.core.compress.CompressionProvider; public class ZIPCompressionOutputStream extends CompressionOutputStream { public ZIPCompressionOutputStream( OutputStream out, CompressionProvider provider ) { super( getDelegate( out ), provider ); } protected static ZipOutputStream getDelegate( OutputStream out ) { ZipOutputStream delegate; if ( out instanceof ZipOutputStream ) { delegate = (ZipOutputStream) out; } else { delegate = new ZipOutputStream( out ); } return delegate; } @Override public void close() throws IOException { ZipOutputStream zos = (ZipOutputStream) delegate; zos.flush(); zos.closeEntry(); zos.finish(); zos.close(); } @Override public void addEntry( String filename, String extension ) throws IOException { // remove folder hierarchy int index = filename.lastIndexOf( Const.FILE_SEPARATOR ); String entryPath; if ( index != -1 ) { entryPath = filename.substring( index + 1 ); } else { entryPath = filename; } // remove ZIP extension index = entryPath.toLowerCase().lastIndexOf( ".zip" ); if ( index != -1 ) { entryPath = entryPath.substring( 0, index ) + entryPath.substring( index + ".zip".length() ); } // add real extension if needed if ( !Const.isEmpty( extension ) ) { entryPath += "." + extension; } ZipEntry zipentry = new ZipEntry( entryPath ); zipentry.setComment( "Compressed by Kettle" ); ( (ZipOutputStream) delegate ).putNextEntry( zipentry ); } }
28.671875
99
0.687193
f80c8c9fd2f5d396336381c29913c5f0b0690c86
5,349
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.pipeline.stage.origin.omniture; import com.streamsets.pipeline.api.ConfigDef; import com.streamsets.pipeline.api.ConfigDefBean; import com.streamsets.pipeline.api.ConfigGroups; import com.streamsets.pipeline.api.ExecutionMode; import com.streamsets.pipeline.api.GenerateResourceBundle; import com.streamsets.pipeline.api.Source; import com.streamsets.pipeline.api.StageDef; import com.streamsets.pipeline.api.ValueChooserModel; import com.streamsets.pipeline.api.base.configurablestage.DSource; import com.streamsets.pipeline.api.credential.CredentialValue; @StageDef( version = 2, label = "Omniture", description = "Retrieves Omniture reports via the REST API.", icon="omniture_icon.png", execution = ExecutionMode.STANDALONE, recordsByRef = true, upgrader = OmnitureSourceUpgrader.class, upgraderDef = "upgrader/OmnitureDSource.yaml", onlineHelpRefUrl ="index.html?contextID=task_of4_wpw_1s" ) @ConfigGroups(Groups.class) @GenerateResourceBundle public class OmnitureDSource extends DSource { @ConfigDefBean(groups = "PROXY") public HttpProxyConfigBean proxySettings = new HttpProxyConfigBean(); @ConfigDef( required = true, type = ConfigDef.Type.STRING, label = "Omniture REST URL", defaultValue = "https://api2.omniture.com/admin/1.4/rest/", description = "Specify the Omniture REST endpoint", displayPosition = 10, group = "OMNITURE" ) public String resourceUrl; @ConfigDef( required = true, type = ConfigDef.Type.TEXT, label = "Omniture Report Description", description = "Report description to queue", displayPosition = 15, mode = ConfigDef.Mode.JSON, dependsOn = "httpMode", lines = 5, triggeredByValue = "POLLING", group = "REPORT" ) public String reportDescription; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, label = "Request Timeout", defaultValue = "3000", description = "HTTP request timeout in milliseconds.", displayPosition = 20, group = "OMNITURE" ) public long requestTimeoutMillis; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, label = "Mode", defaultValue = "POLLING", displayPosition = 25, group = "OMNITURE" ) @ValueChooserModel(HttpClientModeChooserValues.class) public HttpClientMode httpMode; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, label = "Report Request Interval (ms)", defaultValue = "5000", displayPosition = 30, group = "OMNITURE", dependsOn = "httpMode", triggeredByValue = "POLLING" ) public long pollingInterval; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, label = "Max Batch Size (reports)", defaultValue = "1", description = "Maximum number of response entities to queue (e.g. JSON objects).", displayPosition = 35, group = "OMNITURE" ) public int batchSize; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, label = "Batch Wait Time (ms)", defaultValue = "5000", description = "Maximum amount of time to wait to fill a batch before sending it", displayPosition = 40, group = "OMNITURE" ) public long maxBatchWaitTime; @ConfigDef( required = true, type = ConfigDef.Type.CREDENTIAL, label = "Username", description = "Omniture Username", displayPosition = 45, group = "OMNITURE" ) public CredentialValue username; @ConfigDef( required = true, type = ConfigDef.Type.CREDENTIAL, label = "Shared Secret", description = "Omniture Shared Secret", displayPosition = 50, group = "OMNITURE" ) public CredentialValue sharedSecret; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, label = "Use Proxy", description = "Whether or not HTTP proxy should be used for connection", defaultValue = "false", displayPosition = 60, group = "OMNITURE" ) public boolean useProxy; @Override protected Source createSource() { OmnitureConfig config = new OmnitureConfig(); config.setPollingInterval(pollingInterval); config.setMaxBatchWaitTime(maxBatchWaitTime); config.setBatchSize(batchSize); config.setHttpMode(httpMode); config.setReportDescription(reportDescription); config.setRequestTimeoutMillis(requestTimeoutMillis); config.setResourceUrl(resourceUrl); config.setSharedSecret(sharedSecret); config.setUsername(username); if (useProxy) { config.setProxySettings(proxySettings); } return new OmnitureSource(config); } }
29.882682
88
0.690036
36dca0abf2da72d0fca78666d60f36e6260f095b
1,991
package com.lahzouz.graphql.service; import com.lahzouz.graphql.client.universe.FindEventQuery; import com.lahzouz.graphql.util.ApolloClientUtils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.apollographql.apollo.ApolloClient; import com.apollographql.apollo.ApolloQueryCall; import com.apollographql.apollo.api.Response; import com.apollographql.apollo.api.cache.http.HttpCachePolicy; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Mono; import java.util.concurrent.CompletableFuture; @Slf4j @Component public class UniverseApolloService { private final ApolloClient apolloClient; public UniverseApolloService(@Qualifier("universeApolloClient") final ApolloClient apolloClient) { this.apolloClient = apolloClient; } public Response<FindEventQuery.Data> findEvent(final String id) { final ApolloQueryCall<FindEventQuery.Data> findEventCall = apolloClient .query(new FindEventQuery(id)) .toBuilder() .httpCachePolicy(HttpCachePolicy.NETWORK_ONLY).build(); return ApolloClientUtils.toCompletableFuture(findEventCall).join(); } public CompletableFuture<Response<FindEventQuery.Data>> findEventCf(final String id) { final ApolloQueryCall<FindEventQuery.Data> findEventCall = apolloClient .query(new FindEventQuery(id)) .toBuilder() .httpCachePolicy(HttpCachePolicy.NETWORK_ONLY).build(); return ApolloClientUtils.toCompletableFuture(findEventCall); } public Mono<Response<FindEventQuery.Data>> findEventMono(final String id) { final ApolloQueryCall<FindEventQuery.Data> findEventCall = apolloClient .query(new FindEventQuery(id)) .toBuilder() .httpCachePolicy(HttpCachePolicy.NETWORK_ONLY).build(); return ApolloClientUtils.toMono(findEventCall); } }
36.2
102
0.73782
272a6d5ff397a061f857ffc89ebf06e8d641032b
5,174
package net.nekomura.utils.jixiv; import net.nekomura.utils.jixiv.exception.PixivException; import net.nekomura.utils.jixiv.settings.Language; import okhttp3.*; import org.json.JSONObject; import java.io.IOException; public class Settings { private static String getSubmit() throws IOException { String url = "https://www.pixiv.net/setting_user.php"; OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder rb = new Request.Builder().url(url); rb.addHeader("Referer", "https://www.pixiv.net"); rb.addHeader("cookie", "PHPSESSID=" + Jixiv.PHPSESSID); rb.addHeader("user-agent", Jixiv.userAgent()); rb.method("GET", null); Response res = okHttpClient.newCall(rb.build()).execute(); String html = res.body().string(); if (html.contains("<input name=\"submit\" type=\"submit\" class=\"btn_type01\" value=\"")) { int index1 = html.indexOf("<input name=\"submit\" type=\"submit\" class=\"btn_type01\" value=\""); int length = "<input name=\"submit\" type=\"submit\" class=\"btn_type01\" value=\"".length(); String sub = html.substring(index1 + length); int index2 = sub.indexOf("\""); return html.substring(index1 + length, index1 + length + index2); }else { throw new PixivException("Cannot get pixiv submit string"); } } private static String getLanguage() throws IOException { String url = "https://www.pixiv.net/setting_user.php"; OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder rb = new Request.Builder().url(url); rb.addHeader("Referer", "https://www.pixiv.net"); rb.addHeader("cookie", "PHPSESSID=" + Jixiv.PHPSESSID); rb.addHeader("user-agent", Jixiv.userAgent()); rb.method("GET", null); Response res = okHttpClient.newCall(rb.build()).execute(); String html = res.body().string(); if (html.contains(",lang: \"")) { int index1 = html.indexOf(",lang: \""); int length = ",lang: \"".length(); String sub = html.substring(index1 + length); int index2 = sub.indexOf("\""); return html.substring(index1 + length, index1 + length + index2); }else { throw new PixivException("Cannot get user language"); } } /** * 設定作品瀏覽限制 * @param r18Restriction 是否可瀏覽R18作品 * @param r18gRestriction 是否可瀏覽R18-G作品 * @return HTTP 狀態碼 * @throws IOException 讀取網路資料失敗或修改失敗 */ public static int setViewRestriction(boolean r18Restriction, boolean r18gRestriction) throws IOException { String url = "https://www.pixiv.net/setting_user.php"; OkHttpClient okHttpClient = new OkHttpClient(); String r18; if (r18Restriction) { r18 = "show"; }else { r18 = "hide"; } String r18g; if (r18gRestriction) { r18g = "2"; }else { r18g = "1"; } RequestBody body = new FormBody.Builder() .add("mode", "mod") .add("tt", Pixiv.getToken()) .add("r18", r18) .add("r18g", r18g) .add("user_language", getLanguage()) .addEncoded("submit", getSubmit()).build(); Request.Builder rb = new Request.Builder().url(url); MediaType mediaType = MediaType.parse("application/json; charset=utf-8"); rb.method("POST", body); rb.addHeader("referer", "https://www.pixiv.net"); rb.addHeader("cookie", "PHPSESSID=" + Jixiv.PHPSESSID); rb.addHeader("user-agent", Jixiv.userAgent()); Request request = rb.build(); Response response = okHttpClient.newCall(request).execute(); return response.code(); } /** * 設定語言 * @param language 語言 * @return 返回訊息 * @throws IOException 讀取網路資料失敗或修改失敗 */ public static String setLanguage(Language language) throws IOException { String url = "https://www.pixiv.net/ajax/user/language"; JSONObject postData = new JSONObject(); postData.put("code", language.getLanguageCode()); OkHttpClient okHttpClient = new OkHttpClient(); RequestBody body = RequestBody.create(postData.toString(), MediaType.parse("application/json; charset=utf-8")); Request.Builder rb = new Request.Builder(); rb.url(url); rb.post(body); rb.addHeader("referer", "https://www.pixiv.net"); rb.addHeader("cookie", "PHPSESSID=" + Jixiv.PHPSESSID); rb.addHeader("user-agent", Jixiv.userAgent()); rb.addHeader("x-csrf-token", Pixiv.getToken()); Request request = rb.build(); Response response = okHttpClient.newCall(request).execute(); JSONObject json = new JSONObject(response.body().string()); return json.getString("message"); } }
35.197279
119
0.572284
dcf22976db0a2b0454d262d139dd59bab41e5317
379
package mod.society.common.modules; import net.minecraft.item.Item; import net.minecraftforge.fml.common.registry.GameRegistry; /** * @author Martin "Garth" Zander <garth@new-crusader.de> */ public class ItemSmelting extends AbstractItem { public ItemSmelting(String name) { super(name); GameRegistry.findRegistry(Item.class).register(this); } }
21.055556
61
0.720317
deef2ea4c693dd19a9ee47067bf3bf3a92a93f18
1,741
package com.easytoolsoft.commons.lang.util; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; /** * String 工具类 * * @author zhiwei.deng * @date 2017-03-28 **/ public class StringUtil { private static final Pattern IP_PATTERN = Pattern.compile( "(((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|" + "(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|" + "([1-9]\\d)|(\\d))"); private static final Pattern EMAIL_PATTERN = Pattern.compile( "^([a-zA-Z0-9_\\-\\.\\+]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))" + "([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"); private static final Pattern MOBILE_PATTERN = Pattern.compile( "^((176)|(13[0-9])|(14[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$"); /** * ip校验 * * @param s * @return 格式是否正确 */ public static boolean isIpAddress(String s) { Matcher m = IP_PATTERN.matcher(s); return m.matches(); } /** * email校验 * * @param email * @return 格式是否正确 */ public static boolean isEmail(String email) { if (StringUtils.isEmpty(email)) { return false; } Matcher m = EMAIL_PATTERN.matcher(email); return m.matches(); } /** * 手机号校验 * * @param mobiles * @return 格式是否正确 */ public static boolean isMobile(String mobiles) { if (StringUtils.isEmpty(mobiles)) { return false; } Matcher m = MOBILE_PATTERN.matcher(mobiles); return m.matches(); } }
25.985075
115
0.493969
4f9938510cbb3a67c0cf0212644d1e07f0a80297
4,606
package com.xxf.baking.ui.fragment; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.xxf.baking.Constants; import com.xxf.baking.R; import com.xxf.baking.adapter.DividerItemDecoration; import com.xxf.baking.adapter.RecipeIngredientAdapter; import com.xxf.baking.utils.NetworkUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by dell on 2018/2/27. */ public class RecipeIngredientsFragment extends Fragment { @BindView(R.id.recyclerview_recipe_ingredients) RecyclerView mRecyclerView; public static final int UPDATA_DATA = 1; private List<String> ingredients = new ArrayList<>(); private RecipeIngredientAdapter mRecipeIngredientAdapter; private URL url; private String jsonResponse; private int position = new RecipeDetailFragment().getPosition(); private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATA_DATA: mRecipeIngredientAdapter.setData(ingredients); } } }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_recipe_ingredients,container,false); ButterKnife.bind(this, view); fetchData(Constants.API.RECIPE_JSON); initRecyclerView(); return view; } private void initRecyclerView(){ mRecipeIngredientAdapter = new RecipeIngredientAdapter(getContext(),ingredients); mRecyclerView.setAdapter(mRecipeIngredientAdapter); mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL_LIST)); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); } private void fetchData(final String httpUrl) { if (isOnline()){ try { url = new URL(httpUrl); } catch (MalformedURLException e) { e.printStackTrace(); } new Thread(new Runnable() { @Override public void run() { try { jsonResponse = NetworkUtils.getResponseFromHttpUrl(url); if (ingredients != null) { ingredients.clear(); } parseJson(jsonResponse); Message message = new Message(); message.what = UPDATA_DATA; mHandler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } } }).start(); }else { mRecyclerView.setVisibility(View.GONE); } } private void parseJson(String json) throws JSONException { JSONArray recipes = new JSONArray(json); JSONObject recipe = recipes.getJSONObject(position); Log.d("position", String.valueOf(position)); JSONArray ingredientJsonArray = recipe.getJSONArray("ingredients"); for (int i = 0; i < ingredientJsonArray.length(); i++) { JSONObject ingredient = ingredientJsonArray.getJSONObject(i); int quantity = ingredient.getInt("quantity"); String measure = ingredient.getString("measure"); String food = ingredient.getString("ingredient"); String s = food +" "+ quantity+" " + measure; Log.d("s",s); ingredients.add(s); } } public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnected(); } }
30.912752
123
0.642206
8ecae61e1fd730c5a24ea53444d5b2bce23e30fe
393
package dp.behaviour.mediator; /** * 具体同事类B * * @author YZhi * @since 1.0 */ public class ConcreteColleagueB extends Colleague { public ConcreteColleagueB(Mediator mediator) { super(mediator); } public void selfMehtod() { System.out.println("selfMehtod in ConcreteColleagueB"); } public void depMethod() { super.mediator.mehtodB(); } }
17.086957
63
0.641221
f9cedb704bae166a5491d784377eadfdfd5f503a
1,471
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.bitran.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; /** * * @author Willian */ @Configuration @EnableWebMvc public class Config extends WebMvcConfigurerAdapter{ @Bean public UrlBasedViewResolver setupViewResolver(){ UrlBasedViewResolver ubvr = new UrlBasedViewResolver(); ubvr.setPrefix("/WEB-INF/jsp/"); ubvr.setSuffix(".jsp"); ubvr.setViewClass(JstlView.class); return ubvr; } @Bean public ThreadPoolTaskExecutor taskExecutor(){ ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(10); taskExecutor.setMaxPoolSize(1000); taskExecutor.setQueueCapacity(10000); taskExecutor.setWaitForTasksToCompleteOnShutdown(true); return taskExecutor; } }
34.209302
82
0.736234
ef15259a468f7f9eaa66d098e1fd33ea32ad39ec
1,431
package laurent.fitness.controller.postman; import java.util.ArrayList; import javax.validation.Valid; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import laurent.fitness.model.Command; import laurent.fitness.model.Seance; import laurent.fitness.services.CommandService; import laurent.fitness.services.SeanceService; @RestController @RequestMapping("/postman/seancectrl") public class SeanceControllerPostman { private SeanceService seanceService; private CommandService commandService; public SeanceControllerPostman(SeanceService seanceService, CommandService commandService) { this.seanceService = seanceService; this.commandService = commandService; } //Initialise une seance pour une commande donnée d'un utilisateur connecté (customer ou staff-seller) @PostMapping("/addseance") public ResponseEntity<?> addSeance(@Valid int idCommand, @Valid String username) { try { Seance newSeance = this.seanceService.createSeance(idCommand, username, 0f); return ResponseEntity.status(HttpStatus.OK).body(newSeance); } catch(Exception e) { System.out.println(e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } } }
31.108696
102
0.802935
f7403ac082fbe8987fb1a8b48703bfdf15c824a5
226
package com.home.commonData.message.game.request.func.item; import com.home.commonData.message.game.request.func.base.FuncSMO; /** 移动装备消息 */ public class FuncSendMoveEquipMO extends FuncSMO { int fromSlot; int toSlot; }
18.833333
66
0.778761
b02fc3fc3c15246b3c786d7cd33fbc33a66fd37e
1,128
package foodtruck.google; import java.io.IOException; import java.util.Properties; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.name.Named; import foodtruck.annotations.GoogleJavascriptApiKey; import foodtruck.annotations.GoogleServerAPIKey; import foodtruck.server.security.PropertyStore; public class GoogleModule extends AbstractModule { private static final String GOOGLE_PROPERTIES = "google.properties"; @Singleton @Provides @Named(GOOGLE_PROPERTIES) public Properties providesProperties(PropertyStore propertyStore) throws IOException { return propertyStore.findProperties("google"); } @Provides @GoogleJavascriptApiKey public String providesGoogleJavascriptKey(@Named(GOOGLE_PROPERTIES) Properties properties) { return properties.getProperty("foodtrucklocator.google.javascript.api.key"); } @Provides @GoogleServerAPIKey public String providesGoogleServerKey(@Named(GOOGLE_PROPERTIES) Properties properties) { return properties.getProperty("foodtrucklocator.google.api.key"); } }
29.684211
94
0.812943
312708b8f47165fcb8dbbb89f348eed5184ce068
1,462
package io.github.wuzhihao7.dp; import java.util.HashMap; import java.util.Map; public class Fibonacci { public static void main(String[] args) { int n = 4; System.out.println(fibonacci1(n)); Map<Integer, Integer> map = new HashMap<>(); System.out.println(fibonacci2(n, map)); System.out.println(fibonacci3(n, map)); System.out.println(fibonacci4(n)); } private static int fibonacci4(int n) { if(n == 0 || n == 1){ return 1; } int previous = 1, current = 1; for(int i = 2; i <= n; i++){ int sum = previous + current; previous = current; current = sum; } return current; } private static int fibonacci3(int n, Map<Integer, Integer> map) { map.put(0,1); map.put(1,1); for(int i = 2; i <= n; i++){ map.put(i,map.get(i-1) + map.get(i-2)); } return map.get(n); } private static int fibonacci2(int n, Map<Integer, Integer> cache) { if(n ==0 || n == 1){ return 1; } if(cache.containsKey(n)){ return cache.get(n); } cache.put(n, fibonacci2(n-1, cache) + fibonacci2(n-2, cache)); return cache.get(n); } private static int fibonacci1(int n) { if(n ==0 || n == 1){ return 1; } return fibonacci1(n-1) + fibonacci1(n-2); } }
26.107143
71
0.505472
fe5c64fed66c30d3ab84e6202e05bce76c13bc7c
11,234
/** * personium.io * Copyright 2014 FUJITSU LIMITED * * 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.fujitsu.dc.test.utils; import static org.junit.Assert.assertEquals; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.MediaType; import org.apache.http.HttpStatus; import com.fujitsu.dc.test.jersey.AbstractCase; import com.fujitsu.dc.test.unit.core.UrlUtils; /** * Httpリクエストドキュメントを利用するユーティリティ. */ public class AccountUtils { private AccountUtils() { } /** * AccountのGETを行うユーティリティ. * @param token 認証トークン * @param code レスポンスコード * @param cellName セル * @param userName ユーザ名 * @return レスポンス */ public static TResponse get(String token, int code, String cellName, String userName) { TResponse response = Http.request("account-retrieve.txt") .with("token", token) .with("cellPath", cellName) .with("username", userName) .returns() .statusCode(code) .contentType("application/json"); return response; } /** * アカウントを作成するユーティリティ. * @param token トークン * @param cellName セル名 * @param userName ユーザ名 * @param pass パスワード * @param code ステータスコード * @return レスポンス */ public static TResponse create(final String token, final String cellName, final String userName, final String pass, int code) { // AccountのC TResponse tresponse = Http.request("account-create.txt") .with("token", token) .with("cellPath", cellName) .with("username", userName) .with("password", pass) .returns() .statusCode(code); return tresponse; } /** * アカウントを作成するユーティリティ. * @param token トークン * @param cellName セル名 * @param userName ユーザ名 * @param pass パスワード * @param lastAuthenticated 最終ログイン時刻(Edm.DateTime) * @param code ステータスコード * @return レスポンス */ public static TResponse create(final String token, final String cellName, final String userName, final String pass, final String lastAuthenticated, int code) { // AccountのC TResponse tresponse = Http.request("account-create-lastauthenticated.txt") .with("token", token) .with("cellPath", cellName) .with("username", userName) .with("password", pass) .with("lastauthenticated", lastAuthenticated) .returns() .statusCode(code); return tresponse; } /** * X-Dc-Credentialヘッダー無しでアカウントを作成するユーティリティ. * @param token トークン * @param cellName セル名 * @param userName ユーザ名 * @param code ステータスコード * @return レスポンス */ public static TResponse createNonCredential(final String token, final String cellName, final String userName, int code) { // AccountのC TResponse tresponse = Http.request("account-create-Non-Credential.txt") .with("token", token) .with("cellPath", cellName) .with("username", userName) .returns() .statusCode(code); return tresponse; } /** * AccountとRoleの$links登録. * @param token トークン * @param cellName セル名 * @param boxName ボックス名 * @param userName ユーザ名 * @param roleName ロール名 * @param code ステータスコード * @return レスポンス */ public static TResponse createLinkWithRole(final String token, final String cellName, final String boxName, final String userName, final String roleName, int code) { // アカウント・ロールの$link return Http.request("link-account-role.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName) .with("username", userName) .with("roleUrl", UrlUtils.roleUrl(cellName, boxName, roleName)) .returns() .statusCode(code) .debug(); } /** * NP経由でAccountを作成するユーティリティ. * @param cellName Cell名 * @param token 認証トークン(Bearerなし) * @param srcEntityName NP経由元のエンティティ名 * @param srcEntityKeyString NP経由元のID * @param body リクエストボディ * @param code 期待するレスポンスコード * @return レスポンス */ public static TResponse createViaNPNonCredential( final String cellName, final String token, final String srcEntityName, final String srcEntityKeyString, final String body, final int code) { return Http.request("cell/createNP.txt") .with("method", HttpMethod.POST) .with("token", token) .with("cell", cellName) .with("entityType", srcEntityName) .with("id", srcEntityKeyString) .with("navPropName", "_Account") .with("accept", MediaType.APPLICATION_JSON) .with("contentType", MediaType.APPLICATION_JSON) .with("body", body) .returns() .statusCode(code); } /** * アカウント更新. * @param token 認証トークン * @param cellName セル名 * @param userName 旧ユーザ名 * @param newUsername アカウント名 * @param newPassword パスワード * @param sc ステータスコード * @return レスポンス */ public static TResponse update(String token, String cellName, String userName, String newUsername, String newPassword, int sc) { TResponse res = Http.request("account-update.txt") .with("token", token) .with("cellPath", cellName) .with("username", userName) .with("password", newPassword) .with("newUsername", newUsername) .returns().debug(); res.statusCode(sc); return res; } /** * アカウント更新(LastAuthenticated指定あり). * @param token 認証トークン * @param cellName セル名 * @param userName 旧ユーザ名 * @param newUsername アカウント名 * @param newPassword パスワード * @param newLastAuthenticated 最終ログイン時刻 * @param sc ステータスコード * @return レスポンス */ public static TResponse update(String token, String cellName, String userName, String newUsername, String newPassword, String newLastAuthenticated, int sc) { if (null != newLastAuthenticated) { // nullでない場合は文字列であるため、ダブルクォーテーションで囲う newLastAuthenticated = "\"" + newLastAuthenticated + "\""; } else { newLastAuthenticated = "null"; } TResponse res = Http.request("account-update-lastauthenticated.txt") .with("token", token) .with("cellPath", cellName) .with("username", userName) .with("password", newPassword) .with("newUsername", newUsername) .with("newLastAuthenticated", newLastAuthenticated) .returns().debug(); res.statusCode(sc); return res; } /** * アカウントを削除するユーティリティー. * @param cellName セル名 * @param token トークン * @param userName ユーザ名 * @param code レスポンスコード */ public static void delete(final String cellName, final String token, final String userName, final int code) { // アカウント削除 TResponse res = Http.request("account-delete.txt") .with("token", token) .with("cellPath", cellName) .with("username", userName) .returns(); if (code != -1) { assertEquals(code, res.getStatusCode()); } } /** * AccountとRoleの$links削除. * @param cellName セル名 * @param boxName ボックス名 * @param token トークン * @param userName ユーザ名 * @param roleName ロール名 * @param code レスポンスコード */ public static void deleteLinksWithRole(final String cellName, final String boxName, final String token, final String userName, final String roleName, final int code) { String roleKey; if (boxName == null) { roleKey = "Name='" + roleName + "',_Box.Name=null"; } else { roleKey = "Name='" + roleName + "',_Box.Name='" + boxName + "'"; } // Account-Role1登録$links削除 Http.request("cell/link-delete-account-role.txt") .with("cellPath", cellName) .with("accountKey", userName) .with("roleKey", roleKey) .with("contentType", MediaType.APPLICATION_JSON) .with("token", token) .with("ifMatch", "*") .returns() .statusCode(code); } /** * アカウントリスト取得ユーティリティ(クエリ有). * @param token 認証トークン * @param cellName セル名 * @param query クエリ * @param sc ステータスコード * @return レスポンス */ public static TResponse list(String token, String cellName, String query, int sc) { TResponse res = Http.request("account-list-with-query.txt") .with("token", token) .with("cellPath", cellName) .with("query", query) .returns() .statusCode(sc); return res; } /** * アカウントNP経由一覧取得ユーティリティ. * @param cellName セル名 * @param token トークン * @param sourceEntityType ソース側エンティティタイプ名 * @param sourceEntityKeyString ソース側エンティティキー文字列(例:"Name='xxx'") * @param query クエリ("?$"から指定すること) * @return レスポンス */ public static TResponse listViaNP( final String cellName, final String token, final String sourceEntityType, final String sourceEntityKeyString, final String query) { String navPropName = "_Account"; if (null != query) { navPropName += query; } return Http.request("cell/listViaNP.txt") .with("token", "Bearer " + token) .with("cell", cellName) .with("entityType", sourceEntityType) .with("id", sourceEntityKeyString) .with("navPropName", navPropName) .with("accept", MediaType.APPLICATION_JSON) .returns() .statusCode(HttpStatus.SC_OK); } }
34.042424
114
0.55154
c24e4da9afde0228f4a52957c9f4242580c40c30
5,213
package io.nosqlbench.engine.api.templating; import io.nosqlbench.engine.api.activityconfig.yaml.OpTemplate; import io.nosqlbench.engine.api.activityconfig.yaml.StmtDef; import io.nosqlbench.engine.api.activityimpl.motor.ParamsParser; import io.nosqlbench.virtdata.core.bindings.BindingsTemplate; import io.nosqlbench.virtdata.core.templates.ParsedTemplate; import io.nosqlbench.virtdata.core.templates.StringBindings; import io.nosqlbench.virtdata.core.templates.StringBindingsTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.function.Function; /** * Use the {@link StmtDef} template form as a property template for parameterized commands. This is a general purpose * template which uses a map of named parameters. The {@code command} property designates the verb component of the * command. * <p> * To be valid for use with this template type, the template specifier (the stmt String) must either start with command= * or have a single word at the start. In either case, the command will be parsed as if it started with a command=... * <p> * The semantics of command are meant to be generalized. For example, with HTTP, command might mean the HTTP method like * GET or PUT that is used. For web driver, it may be a webdriver command as known by the SIDE file format. */ public class CommandTemplate { private final static Logger logger = LoggerFactory.getLogger(CommandTemplate.class); private final String name; private final Map<String, String> statics = new HashMap<>(); private final Map<String, StringBindings> dynamics = new HashMap<>(); public CommandTemplate(OpTemplate stmt) { this(stmt.getName(), stmt.getStmt(), stmt.getParamsAsValueType(String.class), stmt.getBindings(), List.of()); } public CommandTemplate(OpTemplate stmt, List<Function<String, Map<String, String>>> parsers) { this(stmt.getName(), stmt.getStmt(), stmt.getParamsAsValueType(String.class), stmt.getBindings(), parsers); } /** * Create a command template from a set of optional properties. * * @param name The name of the command template * @param oneline A oneline version of the parameters. Passed as 'stmt' in the yaml format. * @param params A set of named parameters and values in name:value form. * @param bindings A set of named bindings in name:recipe form. */ public CommandTemplate(String name, String oneline, Map<String, String> params, Map<String, String> bindings, List<Function<String, Map<String, String>>> optionalParsers) { this.name = name; Map<String, String> cmd = new HashMap<>(); // Only parse and inject the oneline form if it is defined. // The first parser to match and return a map will be the last one tried. // If none of the suppliemental parsers work, the default params parser is used if (oneline != null) { List<Function<String,Map<String,String>>> parserlist = new ArrayList<>(optionalParsers); parserlist.add(s -> ParamsParser.parse(s,false)); for (Function<String, Map<String, String>> parser : parserlist) { Map<String, String> parsed = parser.apply(oneline); if (parsed!=null) { logger.debug("parsed request: " + parsed.toString()); cmd.putAll(parsed); break; } } } // Always add the named params, but warn if they overwrite any oneline named params params.forEach((k, v) -> { if (cmd.containsKey(k)) { logger.warn("command property override: '" + k + "' superseded by param form with value '" + v + "'"); } }); cmd.putAll(params); cmd.forEach((param, value) -> { ParsedTemplate paramTemplate = new ParsedTemplate(value, bindings); if (paramTemplate.getBindPoints().size() > 0) { BindingsTemplate paramBindings = new BindingsTemplate(paramTemplate.getBindPoints()); StringBindings paramStringBindings = new StringBindingsTemplate(value, paramBindings).resolve(); dynamics.put(param, paramStringBindings); statics.put(param, null); } else { statics.put(param, value); } }); } public Map<String, String> getCommand(long cycle) { HashMap<String, String> map = new HashMap<>(statics); dynamics.forEach((k, v) -> { map.put(k, v.bind(cycle)); }); return map; } public String getName() { return name; } public boolean isStatic() { return this.dynamics.size() == 0; } public Set<String> getPropertyNames() { return this.statics.keySet(); } // private static List<String> namedGroups(String regex) { // List<String> namedGroups = new ArrayList<String>(); // // Matcher m = Pattern.compile("\\(\\?<([a-zA-Z][a-zA-Z0-9]*)>").matcher(regex); // // while (m.find()) { // namedGroups.add(m.group(1)); // } // // return namedGroups; // } }
40.410853
176
0.647612
365f129902043a41a76cf4c70e4c0aec1cbf2e09
1,048
package org.gemini4j.cucumber; import org.gemini4j.browser.Browser; import org.gemini4j.core.Gemini4jConfiguration; import org.gemini4j.imageresolver.ClasspathReferenceImageResolver; import org.gemini4j.imageresolver.ReferenceImageResolver; import org.gemini4j.reporter.Reporter; import org.gemini4j.selenium.WebDriverBrowser; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; public class Config implements Gemini4jConfiguration<WebDriver> { private static final String IMAGE_PREFIX = "org/gemini4j/cucumber/shots/"; private static final ReferenceImageResolver IMAGE_RESOLVER = new ClasspathReferenceImageResolver(IMAGE_PREFIX); @Override public Reporter getReporter() { return CucumberTests.REPORTER; } @Override public ReferenceImageResolver getReferenceImageResolver() { return IMAGE_RESOLVER; } @Override public Browser<WebDriver> getBrowser() { return new WebDriverBrowser("http://localhost:4444/wd/hub", new ChromeOptions()); } }
32.75
115
0.783397
4dec9b2931490f9cddcad4f99def09d8fad15ae4
2,904
package ru.job4j.bomberman; import ru.job4j.bomberman.enums.GameLevel; import ru.job4j.bomberman.threads.EndGameThread; import ru.job4j.bomberman.units.Hero; import ru.job4j.bomberman.units.Unit; import java.util.concurrent.ExecutionException; /** * @author shaplov * @since 24.05.2019 */ public class Game { /** * Difficulty level. */ private final GameLevel level; /** * Board size. */ private final int size; /** * Default constructor. * @param level Difficulty. * @param size board size. */ public Game(final GameLevel level, final int size) { this.level = level; this.size = size; } /** * Inits classes and start threads. */ public void start() { Hero hero = new Hero(new Cell(0, 0), "Hero"); Board board = new Board(size, hero); putBlocks(board); ThreadsControl control = new ThreadsControl(monsterNumber(), board, hero); control.init(); EndGameThread endGame = new EndGameThread(board, control); endGame.start(); try { control.waitJobs(); endGame.join(); } catch (ExecutionException | InterruptedException e) { control.close(); e.printStackTrace(); } } /** * Put blocks on board. * @param board board. */ private void putBlocks(Board board) { if (GameLevel.MEDIUM.equals(level) || GameLevel.HARD.equals(level)) { board.placeOnBoard(new Unit(new Cell(1, 1), "Block")); board.placeOnBoard(new Unit(new Cell(board.size() - 2, 1), "Block")); board.placeOnBoard(new Unit(new Cell(1, board.size() - 2), "Block")); board.placeOnBoard(new Unit(new Cell(board.size() - 2, board.size() - 2), "Block")); } if (GameLevel.HARD.equals(level)) { board.placeOnBoard(new Unit(new Cell(board.size() / 2, board.size() / 2), "Block")); board.placeOnBoard(new Unit(new Cell(board.size() / 2 + 1, board.size() / 2 + 1), "Block")); board.placeOnBoard(new Unit(new Cell(board.size() / 2 - 1, board.size() / 2 - 1), "Block")); board.placeOnBoard(new Unit(new Cell(board.size() / 2 - 1, board.size() / 2 + 1), "Block")); board.placeOnBoard(new Unit(new Cell(board.size() / 2 + 1, board.size() / 2 - 1), "Block")); } } /** * @return monster number * depending on the difficulty level. */ private int monsterNumber() { final int monsterNumber; if (GameLevel.EASY.equals(level)) { monsterNumber = 2; } else if (GameLevel.MEDIUM.equals(level)) { monsterNumber = 3; } else if (GameLevel.HARD.equals(level)) { monsterNumber = 5; } else { monsterNumber = 0; } return monsterNumber; } }
30.893617
104
0.569559
b35916931fc990001ee46b16337ea6b150689581
1,279
package com.example.cli.valid.result.impl; import com.example.cli.valid.exception.ValidRuntimeException; import com.example.cli.valid.result.IConstraintResult; import com.example.cli.valid.result.IResult; import lombok.Data; import lombok.ToString; import java.util.List; /** * @author liwei * @title: DefaultResult * @projectName sdkproxy * @description: TODO * @date 2020-01-03 09:06 */ @Data @ToString public class DefaultResult implements IResult { /** * 是否全部通过验证 */ private boolean pass; /** * 未通过的列表信息 */ private List<IConstraintResult> notPassList; /** * 所有的验证结果列表 */ private List<IConstraintResult> allList; @Override public boolean pass() { return pass; } @Override public List<IConstraintResult> notPassList() { return notPassList; } @Override public List<IConstraintResult> allList() { return allList; } @Override public IResult print() { System.out.println(this); return this; } @Override public IResult throwsEx() { if(!pass) { final String message = this.notPassList.get(0).message(); throw new ValidRuntimeException(message); } return this; } }
19.089552
69
0.633307
869a8edeca8e6a841679c639f5711119443bdda4
288
package com.jxin.faas.scheduler.infrastructure.plug.db.type.mybatis.properties; import lombok.Data; import java.util.Map; /** * 复数DB配置参数类 * @author Jxin * @version 1.0 * @since 2020/1/13 20:01 */ @Data public class MutilDbProperties { private Map<String, DbProperties> dbs; }
16.941176
79
0.722222
61e8ff427a5d5be962ffad7c22e5a78e6bc845dc
21,727
package ca.corefacility.bioinformatics.irida.ria.web.projects; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.security.Principal; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Scope; import org.springframework.format.Formatter; import org.springframework.format.datetime.DateFormatter; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import ca.corefacility.bioinformatics.irida.exceptions.ProjectWithoutOwnerException; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.sample.Sample; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.ria.utilities.converters.FileSizeConverter; import ca.corefacility.bioinformatics.irida.ria.web.cart.CartController; import ca.corefacility.bioinformatics.irida.ria.web.models.datatables.DTProject; import ca.corefacility.bioinformatics.irida.security.permissions.sample.UpdateSamplePermission; import ca.corefacility.bioinformatics.irida.service.ProjectService; import ca.corefacility.bioinformatics.irida.service.TaxonomyService; import ca.corefacility.bioinformatics.irida.service.sample.SampleService; import ca.corefacility.bioinformatics.irida.service.user.UserService; import ca.corefacility.bioinformatics.irida.util.TreeNode; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; /** * Controller for project related views */ @Controller @Scope("session") public class ProjectsController { // Sub Navigation Strings public static final String ACTIVE_NAV = "activeNav"; private static final String ACTIVE_NAV_ACTIVITY = "activity"; private static final String ACTIVE_NAV_ANALYSES = "analyses"; // Page Names public static final String PROJECTS_DIR = "projects/"; public static final String LIST_PROJECTS_PAGE = PROJECTS_DIR + "projects"; public static final String PROJECT_MEMBERS_PAGE = PROJECTS_DIR + "project_members"; public static final String SPECIFIC_PROJECT_PAGE = PROJECTS_DIR + "project_details"; public static final String SYNC_NEW_PROJECT_PAGE = PROJECTS_DIR + "project_sync"; public static final String CREATE_NEW_PROJECT_PAGE = PROJECTS_DIR + "project_new"; public static final String PROJECT_SAMPLES_PAGE = PROJECTS_DIR + "project_samples"; private static final Logger logger = LoggerFactory.getLogger(ProjectsController.class); // Services private final ProjectService projectService; private final SampleService sampleService; private final UserService userService; private final ProjectControllerUtils projectControllerUtils; private final TaxonomyService taxonomyService; private final MessageSource messageSource; private final CartController cartController; private final UpdateSamplePermission updateSamplePermission; /* * Converters */ Formatter<Date> dateFormatter; FileSizeConverter fileSizeConverter; // CONSTANTS private final List<Map<String, String>> EXPORT_TYPES = ImmutableList.of( ImmutableMap.of("format", "xlsx", "name", "Excel"), ImmutableMap.of("format", "csv", "name", "CSV")); @Autowired public ProjectsController(ProjectService projectService, SampleService sampleService, UserService userService, ProjectControllerUtils projectControllerUtils, TaxonomyService taxonomyService, CartController cartController, UpdateSamplePermission updateSamplePermission, MessageSource messageSource) { this.projectService = projectService; this.sampleService = sampleService; this.userService = userService; this.projectControllerUtils = projectControllerUtils; this.taxonomyService = taxonomyService; this.dateFormatter = new DateFormatter(); this.messageSource = messageSource; this.cartController = cartController; this.fileSizeConverter = new FileSizeConverter(); this.updateSamplePermission = updateSamplePermission; } /** * Request for the page to display a list of all projects available to the currently logged in user. * * @param model The model to add attributes to for the template. * @return The name of the page. */ @RequestMapping("/projects") public String getProjectsPage(Model model) { model.addAttribute("ajaxURL", "/projects/ajax/list"); model.addAttribute("exportTypes", EXPORT_TYPES); model.addAttribute("isAdmin", false); return LIST_PROJECTS_PAGE; } /** * Get the admin projects page. * * @param model {@link Model} * @return The name of the page */ @RequestMapping("/projects/all") @PreAuthorize("hasAnyRole('ROLE_ADMIN')") public String getAllProjectsPage(Model model) { model.addAttribute("ajaxURL", "/projects/admin/ajax/list"); model.addAttribute("isAdmin", true); model.addAttribute("exportTypes", EXPORT_TYPES); return LIST_PROJECTS_PAGE; } /** * Request for a specific project details page. * * @param projectId The id for the project to show details for. * @param model Spring model to populate the html page. * @param principal a reference to the logged in user. * @return The name of the project details page. */ @RequestMapping(value = "/projects/{projectId}/activity") public String getProjectSpecificPage(@PathVariable Long projectId, final Model model, final Principal principal) { logger.debug("Getting project information for [Project " + projectId + "]"); Project project = projectService.read(projectId); model.addAttribute("project", project); projectControllerUtils.getProjectTemplateDetails(model, principal, project); model.addAttribute(ACTIVE_NAV, ACTIVE_NAV_ACTIVITY); return SPECIFIC_PROJECT_PAGE; } /** * Gets the name of the template for the new project page * * @param useCartSamples Whether or not to use the samples in the cart when creating * the project * @param model {@link Model} * @param owner whether or not to lock the sample(s) from being modified from new * the project * @return The name of the create new project page */ @RequestMapping(value = "/projects/new", method = RequestMethod.GET) public String getCreateProjectPage( @RequestParam(name = "cart", required = false, defaultValue = "false") boolean useCartSamples, final Model model, @RequestParam(name = "lockSamples", required = false, defaultValue = "true") boolean owner) { model.addAttribute("useCartSamples", useCartSamples); Map<Project, List<Sample>> selected = cartController.getSelected(); // Check which samples they can modify Set<Sample> allowed = new HashSet<>(); Set<Sample> disallowed = new HashSet<>(); selected.values() .forEach(set -> { set.stream() .forEach(s -> { if (canModifySample(s)) { allowed.add(s); } else { disallowed.add(s); } }); }); model.addAttribute("allowedSamples", allowed); model.addAttribute("disallowedSamples", disallowed); if (!model.containsAttribute("errors")) { model.addAttribute("errors", new HashMap<>()); } return CREATE_NEW_PROJECT_PAGE; } /** * Get the page to synchronize remote projects * * @return Name of the project sync page */ @RequestMapping(value = "/projects/synchronize", method = RequestMethod.GET) public String getSynchronizeProjectPage() { return SYNC_NEW_PROJECT_PAGE; } /** * Creates a new project and displays a list of users for the user to add to * the project * * @param model {@link Model} * @param project the {@link Project} to create * @param useCartSamples add all samples in the cart to the project * @param owner lock sample modification from the new project * @return The name of the add users to project page */ @RequestMapping(value = "/projects/new", method = RequestMethod.POST) public String createNewProject(final Model model, @ModelAttribute Project project, @RequestParam(required = false, defaultValue = "false") boolean useCartSamples, @RequestParam(name = "lockSamples", required = false, defaultValue = "true") boolean owner) { try { if (useCartSamples) { Map<Project, List<Sample>> selected = cartController.getSelected(); List<Long> sampleIds = selected.entrySet() .stream() .flatMap(e -> e.getValue() .stream() .filter(s -> { return canModifySample(s); }) .map(i -> i.getId())) .collect(Collectors.toList()); project = projectService.createProjectWithSamples(project, sampleIds, owner); } else { project = projectService.create(project); } } catch (ConstraintViolationException e) { model.addAttribute("errors", getErrorsFromViolationException(e)); model.addAttribute("project", project); return getCreateProjectPage(useCartSamples, model, owner); } return "redirect:/projects/" + project.getId() + "/settings"; } /** * Get the page for analyses shared with a given {@link Project} * * @param projectId the ID of the {@link Project} * @param principal the logged in user * @param model model for view variables * @return name of the analysis view page */ @RequestMapping("/projects/{projectId}/analyses") public String getProjectAnalysisList(@PathVariable Long projectId, Principal principal, Model model) { Project project = projectService.read(projectId); projectControllerUtils.getProjectTemplateDetails(model, principal, project); model.addAttribute("project", project); projectControllerUtils.getProjectTemplateDetails(model, principal, project); model.addAttribute(ACTIVE_NAV, ACTIVE_NAV_ANALYSES); model.addAttribute("page", "analyses"); return "projects/analyses/pages/analyses_table.html"; } /** * Get the page for analysis output files shared with a given {@link Project} * * @param projectId the ID of the {@link Project} * @param principal the logged in user * @param model model for view variables * @return name of the analysis view page */ @RequestMapping("/projects/{projectId}/analyses/shared-outputs") public String getProjectSharedOutputFilesPage(@PathVariable Long projectId, Principal principal, Model model) { Project project = projectService.read(projectId); model.addAttribute("project", project); projectControllerUtils.getProjectTemplateDetails(model, principal, project); model.addAttribute("ajaxURL", "/ajax/analysis/project/" + projectId + "/list"); model.addAttribute(ACTIVE_NAV, ACTIVE_NAV_ANALYSES); model.addAttribute("page", "shared"); return "projects/analyses/pages/outputs.html"; } /** * Get the page for automated analysis output files shared with a given {@link Project} * * @param projectId the ID of the {@link Project} * @param principal the logged in user * @param model model for view variables * @return name of the analysis view page */ @RequestMapping("/projects/{projectId}/analyses/automated-outputs") public String getProjectAutomatedOutputFilesPage(@PathVariable Long projectId, Principal principal, Model model) { Project project = projectService.read(projectId); model.addAttribute("project", project); projectControllerUtils.getProjectTemplateDetails(model, principal, project); model.addAttribute("ajaxURL", "/ajax/analysis/project/" + projectId + "/list"); model.addAttribute(ACTIVE_NAV, ACTIVE_NAV_ANALYSES); model.addAttribute("page", "automated"); return "projects/analyses/pages/outputs.html"; } /** * Search for taxonomy terms. This method will return a map of found taxonomy terms and their child nodes. * <p> * Note: If the search term was not included in the results, it will be added as an option * * @param searchTerm The term to find taxa for * @return A {@code List<Map<String,Object>>} which will contain a taxonomic tree of matching terms */ @RequestMapping("/projects/ajax/taxonomy/search") @ResponseBody public List<Map<String, Object>> searchTaxonomy(@RequestParam String searchTerm) { Collection<TreeNode<String>> search = taxonomyService.search(searchTerm); TreeNode<String> searchTermNode = new TreeNode<>(searchTerm); // add a property to this node to indicate that it's the search term searchTermNode.addProperty("searchTerm", true); List<Map<String, Object>> elements = new ArrayList<>(); // get the search term in first if it's not there yet if (!search.contains(searchTermNode)) { elements.add(transformTreeNode(searchTermNode)); } for (TreeNode<String> node : search) { Map<String, Object> transformTreeNode = transformTreeNode(node); elements.add(transformTreeNode); } return elements; } /** * Export Projects table as either an excel file or CSV * * @param type of file to export (csv or excel) * @param isAdmin if the currently logged in user is an administrator * @param response {@link HttpServletResponse} * @param principal {@link Principal} * @param locale {@link Locale} * @throws IOException thrown if cannot open the {@link HttpServletResponse} {@link OutputStream} */ @RequestMapping("/projects/ajax/export") public void exportProjectsToFile(@RequestParam(value = "dtf") String type, @RequestParam(required = false, defaultValue = "false", value = "admin") Boolean isAdmin, HttpServletResponse response, Principal principal, Locale locale) throws IOException { // Let's make sure the export type is set properly if (!(type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("csv"))) { throw new IllegalArgumentException( "No file type sent for downloading all projects. Expecting parameter 'dtf=' xlsx or csv"); } List<Project> projects; // If viewing the admin projects page give the user all the projects. if (isAdmin) { projects = (List<Project>) projectService.findAll(); } // If on the users projects page, give the user their projects. else { User user = userService.getUserByUsername(principal.getName()); projects = projectService.getProjectsForUser(user) .stream() .map(Join::getSubject) .collect(Collectors.toList()); } List<DTProject> dtProjects = projects.stream() .map(this::createDataTablesProject) .collect(Collectors.toList()); List<String> headers = ImmutableList.of("ProjectsTable_th_id", "ProjectsTable_th_name", "ProjectsTable_th_organism", "ProjectsTable_th_samples", "ProjectsTable_th_created_date", "ProjectsTable_th_modified_date") .stream() .map(h -> messageSource.getMessage(h, new Object[] {}, locale)) .collect(Collectors.toList()); // Create the filename Date date = new Date(); DateFormat fileDateFormat = new SimpleDateFormat(messageSource.getMessage("date.iso-8601", null, locale)); String filename = "IRIDA_projects_" + fileDateFormat.format(date); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "." + type + "\""); if (type.equals("xlsx")) { writeProjectsToExcelFile(headers, dtProjects, locale, response); } else { writeProjectsToCsvFile(headers, dtProjects, locale, response); } } /** * Write the projects as a CSV file * * @param headers {@link List} for {@link String} headers for the information. * @param projects {@link List} of {@link DTProject} to export * @param locale {@link Locale} * @param response {@link HttpServletResponse} * @throws IOException Thrown if cannot get the {@link PrintWriter} for the response */ private void writeProjectsToCsvFile(List<String> headers, List<DTProject> projects, Locale locale, HttpServletResponse response) throws IOException { PrintWriter writer = response.getWriter(); try (CSVPrinter printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withRecordSeparator(System.lineSeparator()))) { printer.printRecord(headers); DateFormat dateFormat = new SimpleDateFormat(messageSource.getMessage("locale.date.long", null, locale)); for (DTProject p : projects) { List<String> record = new ArrayList<>(); record.add(String.valueOf(p.getId())); record.add(p.getName()); record.add(p.getOrganism()); record.add(String.valueOf(p.getSamples())); record.add(dateFormat.format(p.getCreatedDate())); record.add(dateFormat.format(p.getModifiedDate())); printer.printRecord(record); } printer.flush(); } } /** * Write the projects as a Excel file * * @param headers {@link List} for {@link String} headers for the information. * @param projects {@link List} of {@link DTProject} to export * @param locale {@link Locale} * @param response {@link HttpServletResponse} * @throws IOException Thrown if cannot get the {@link OutputStream} for the response */ private void writeProjectsToExcelFile(List<String> headers, List<DTProject> projects, Locale locale, HttpServletResponse response) throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(); int rowCount = 0; // Create the headers Row headerRow = sheet.createRow(rowCount++); for (int cellCount = 0; cellCount < headers.size(); cellCount++) { Cell cell = headerRow.createCell(cellCount); cell.setCellValue(headers.get(cellCount)); } // Create the rest of the sheet DateFormat dateFormat = new SimpleDateFormat(messageSource.getMessage("locale.date.long", null, locale)); for (DTProject p : projects) { Row row = sheet.createRow(rowCount++); int cellCount = 0; row.createCell(cellCount++) .setCellValue(String.valueOf(p.getId())); row.createCell(cellCount++) .setCellValue(p.getName()); row.createCell(cellCount++) .setCellValue(p.getOrganism()); row.createCell(cellCount++) .setCellValue(String.valueOf(p.getSamples())); row.createCell(cellCount++) .setCellValue(dateFormat.format(p.getCreatedDate())); row.createCell(cellCount) .setCellValue(dateFormat.format(p.getModifiedDate())); } // Write the file try (OutputStream stream = response.getOutputStream()) { workbook.write(stream); stream.flush(); } } /** * Changes a {@link ConstraintViolationException} to a usable map of strings for displaing in the UI. * * @param e {@link ConstraintViolationException} for the form submitted. * @return Map of string {fieldName, error} */ private Map<String, String> getErrorsFromViolationException(ConstraintViolationException e) { Map<String, String> errors = new HashMap<>(); for (ConstraintViolation<?> violation : e.getConstraintViolations()) { String message = violation.getMessage(); String field = violation.getPropertyPath() .toString(); errors.put(field, message); } return errors; } /** * Handle a {@link ProjectWithoutOwnerException} error. Returns a forbidden error * * @param ex the exception to handle. * @return response entity with FORBIDDEN error */ @ExceptionHandler(ProjectWithoutOwnerException.class) @ResponseBody public ResponseEntity<String> roleChangeErrorHandler(Exception ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.FORBIDDEN); } /** * Test whether the logged in user can modify a {@link Sample} * * @param sample the {@link Sample} to check * @return true if they can modify */ private boolean canModifySample(Sample sample) { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); return updateSamplePermission.isAllowed(authentication, sample); } /** * } * <p> * /** Recursively transform a {@link TreeNode} into a json parsable map object * * @param node The node to transform * @return A Map<String,Object> which may contain more children */ private Map<String, Object> transformTreeNode(TreeNode<String> node) { Map<String, Object> current = new HashMap<>(); // add the node properties to the map for (Entry<String, Object> property : node.getProperties() .entrySet()) { current.put(property.getKey(), property.getValue()); } current.put("id", node.getValue()); current.put("text", node.getValue()); List<Object> children = new ArrayList<>(); for (TreeNode<String> child : node.getChildren()) { Map<String, Object> transformTreeNode = transformTreeNode(child); children.add(transformTreeNode); } if (!children.isEmpty()) { current.put("children", children); } return current; } /** * Extract the details of the a {@link Project} into a {@link DTProject} which is consumable by the UI * * @param project {@link Project} * @return {@link DTProject} */ private DTProject createDataTablesProject(Project project) { return new DTProject(project, sampleService.getNumberOfSamplesForProject(project)); } }
38.319224
213
0.740829
dec6d79ff81128daaa7b332242e6d9225cfc6c01
306
package net.openid.conformance.condition.client; import org.springframework.http.HttpStatus; public class CheckTokenEndpointHttpStatus503 extends AbstractCheckTokenEndpointHttpStatus { @Override protected HttpStatus getExpectedHttpStatus() { return HttpStatus.SERVICE_UNAVAILABLE; } }
23.538462
92
0.810458
8fef689ed70339632e6fe5681fdc6b3124205a90
155
package il.co.codeguru.corewars8086.gui.widgets; public class JSeparator { public static int HORIZONTAL = 1; public JSeparator(int v) { } }
15.5
48
0.696774
ae3da2c6f93fd9bf62278188c1d9e4f224c5a4ca
344
package action; import include.Command; import Func.Com; public class SkillThread extends Thread { public void run(){ Com com=new Com(); boolean createDm=com.createDm(); SkillFunc skillFunc=new SkillFunc(com.activeDm); while(Command.mainThread&&createDm){ skillFunc.action(); } com.releaseDm(); } }
18.105263
51
0.668605
2be45edf7aced129f55c7e7352e0acc8ad04e909
32
bug main string args table empty
32
32
0.84375
92f0e7808e679e69199f4789360ddde0897c6fc1
703
package com.iasmar.toronto.data.repositories.websites; import com.iasmar.toronto.data.modules.WebSite; import com.iasmar.toronto.data.repositories.BaseDataSource; import java.util.List; import io.reactivex.Flowable; /** * Created by Asmar on 15/10/2017. * <p> * Remote entry point for accessing websites data. * * @author Asmar * @version 1 * @see WebSite * @see BaseDataSource * @see WebsitesDataSource * @since 0.1.0 */ public interface RemoteWebsitesDataSource extends WebsitesDataSource { /** * Gets websites. * * @return the List of {@link WebSite} module. */ Flowable<List<WebSite>> getWebsites(String sort); Flowable<List<WebSite>> getTopFives(); }
22.677419
70
0.711238
4eaca99d9ad702394963df251af08e7cd8ab0b39
975
/* * 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 Modelo; /** * * @author raphael */ public class Aluno { private Long codigo_aluno; private Long codigo_disciplina; private String matricula; public Long getCodigo() { return codigo_aluno; } public void setCodigo(Long codigo) { this.codigo_aluno = codigo; } public Long getCodigo_disciplina() { return codigo_disciplina; } public void setCodigo_disciplina(Long codigo_disciplina) { this.codigo_disciplina = codigo_disciplina; } public String getMatricula() { return matricula; } public void setMatricula(String matricula) { this.matricula = matricula; } @Override public String toString() { return matricula; } }
18.75
79
0.638974
bc57b99362a55ee6eaa886057f897e4575a51c74
41,463
package eu.slipo.workbench.rpc.tests.unit.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.collections4.IterableUtils; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import eu.slipo.workbench.common.model.poi.EnumDataFormat; import eu.slipo.workbench.common.model.poi.EnumOperation; import eu.slipo.workbench.common.model.poi.EnumTool; import eu.slipo.workbench.common.model.process.CatalogResource; import eu.slipo.workbench.common.model.process.EnumInputType; import eu.slipo.workbench.common.model.process.ProcessDefinition; import eu.slipo.workbench.common.model.process.ProcessDefinitionBuilderFactory; import eu.slipo.workbench.common.model.process.ProcessInput; import eu.slipo.workbench.common.model.process.ProcessOutput; import eu.slipo.workbench.common.model.process.Step; import eu.slipo.workbench.common.model.resource.FileSystemDataSource; import eu.slipo.workbench.common.model.resource.ResourceIdentifier; import eu.slipo.workbench.common.model.resource.ResourceMetadataCreate; import eu.slipo.workbench.common.model.tool.DeerConfiguration; import eu.slipo.workbench.common.model.tool.FagiConfiguration; import eu.slipo.workbench.common.model.tool.LimesConfiguration; import eu.slipo.workbench.common.model.tool.RegisterToCatalogConfiguration; import eu.slipo.workbench.common.model.tool.Triplegeo; import eu.slipo.workbench.common.model.tool.TriplegeoConfiguration; import eu.slipo.workbench.common.model.tool.output.EnumDeerOutputPart; import eu.slipo.workbench.common.model.tool.output.EnumImportDataOutputPart; import eu.slipo.workbench.common.model.tool.output.EnumLimesOutputPart; import eu.slipo.workbench.common.model.tool.output.EnumOutputType; import eu.slipo.workbench.common.model.tool.output.EnumTriplegeoOutputPart; import eu.slipo.workbench.common.model.tool.output.OutputPart; import eu.slipo.workflows.util.digraph.DependencyGraph; import eu.slipo.workflows.util.digraph.DependencyGraphs; @RunWith(SpringRunner.class) @ActiveProfiles({ "testing" }) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ProcessDefinitionTests { private static final String DATASOURCE_1_PATH = "uploads/1.csv"; private static final String DATASOURCE_2_PATH = "uploads/2.csv"; private static final ResourceIdentifier RESOURCE_1_ID = ResourceIdentifier.of(1L, 5L); private static final String RESOURCE_1_NAME = "resource-example-1"; private static final ResourceIdentifier RESOURCE_2_ID = ResourceIdentifier.of(19L, 1L); private static final String RESOURCE_2_NAME = "resource-example-2"; enum BazOutputPart implements OutputPart<Triplegeo> { BAZ_1("baz1"), BAZ_2("baz2") ; private final String key; private BazOutputPart(String key) { this.key = key; } @Override public String key() { return key; } @Override public EnumOutputType outputType() { return EnumOutputType.OUTPUT; } @Override public Class<Triplegeo> toolType() { return Triplegeo.class; } } @TestConfiguration public static class Setup { @Bean public ObjectMapper jsonMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); return objectMapper; } @Bean public ProcessDefinitionBuilderFactory processDefinitionBuilderFactory(ObjectMapper objectMapper) { return new ProcessDefinitionBuilderFactory(objectMapper); } @Bean public TriplegeoConfiguration sampleTriplegeoConfiguration1() { TriplegeoConfiguration config = new TriplegeoConfiguration(); config.setInputFormat(EnumDataFormat.CSV); config.setOutputFormat(EnumDataFormat.N_TRIPLES); config.setOutputDir("/var/local/triplegeo/1"); config.setTmpDir("/tmp/triplegeo/1"); config.setMappingSpec("classpath:config/triplegeo/profiles/1/mappings.yml"); config.setClassificationSpec("classpath:config/triplegeo/profiles/1/classification.yml"); config.setAttrX("lon"); config.setAttrX("lat"); config.setFeatureSource("points"); config.setAttrKey("id"); config.setAttrName("name"); config.setAttrCategory("type"); return config; } @Bean public FagiConfiguration sampleFagiConfiguration1() { FagiConfiguration config = new FagiConfiguration(); return config; } @Bean public LimesConfiguration sampleLimesConfiguration1() { LimesConfiguration config = new LimesConfiguration(); config.setMetric("trigrams(a.level, b.level)"); config.setSource("a", "/tmp/limes/input/a.nt", "?x", "slipo:name/slipo:nameType RENAME label"); config.setTarget("b", "/tmp/limes/input/b.nt", "?y", "slipo:name/slipo:nameType RENAME label"); config.setOutputDir("/tmp/limes/output"); config.setOutputFormatFromString("N-TRIPLES"); config.setAccepted(0.98, "accepted.nt"); config.setReview(0.95, "review.nt"); return config; } @Bean public DeerConfiguration sampleDeerConfiguration1() { DeerConfiguration config = new DeerConfiguration(); config.setInputFormat(EnumDataFormat.N_TRIPLES); config.setInput("1.nt"); config.setOutputFormat(EnumDataFormat.N_TRIPLES); config.setOutputDir("out"); config.setSpec("classpath:config/deer/defaults/1.ttl"); return config; } @Bean public FileSystemDataSource dataSource1() { return new FileSystemDataSource(DATASOURCE_1_PATH); } @Bean public FileSystemDataSource dataSource2() { return new FileSystemDataSource(DATASOURCE_2_PATH); } } @Autowired private ObjectMapper jsonMapper; @Autowired private ProcessDefinitionBuilderFactory processDefinitionBuilderFactory; @Autowired private FileSystemDataSource dataSource1; @Autowired private FileSystemDataSource dataSource2; @Autowired private TriplegeoConfiguration sampleTriplegeoConfiguration1; @Autowired private DeerConfiguration sampleDeerConfiguration1; @Autowired private LimesConfiguration sampleLimesConfiguration1; @Autowired private FagiConfiguration sampleFagiConfiguration1; private ProcessDefinition buildDefinition1a() { final String TRANSFORM_1_KEY = "transformed-1", TRANSFORM_2_KEY = "transformed-2", LINKS_KEY = "links"; ResourceMetadataCreate metadataForTransformed1 = new ResourceMetadataCreate("tr-1", "The 1st RDF file"); ResourceMetadataCreate metadataForTransformed2 = new ResourceMetadataCreate("tr-2", "The 2nd RDF file"); ResourceMetadataCreate metadataForLinks = new ResourceMetadataCreate("links-1-2", "A set of sameAs links between 1st and 2nd RDF files"); ProcessDefinition definition = processDefinitionBuilderFactory.create("proc-1-a") .transform("triplegeo-1", b -> b .group(1) .outputKey(TRANSFORM_1_KEY) .source(dataSource1) .configuration(sampleTriplegeoConfiguration1)) .transform("triplegeo-2", b -> b .group(1) .outputKey(TRANSFORM_2_KEY) .source(dataSource2) .configuration(sampleTriplegeoConfiguration1)) .interlink("link-1-with-2", b -> b .group(2) .configuration(sampleLimesConfiguration1) .left(TRANSFORM_1_KEY, EnumTriplegeoOutputPart.TRANSFORMED) .right(TRANSFORM_2_KEY, EnumTriplegeoOutputPart.TRANSFORMED) .outputKey(LINKS_KEY) .outputFormat(EnumDataFormat.N_TRIPLES)) .register("register-1", TRANSFORM_1_KEY, EnumTriplegeoOutputPart.TRANSFORMED, metadataForTransformed1) .register("register-2", TRANSFORM_2_KEY, EnumTriplegeoOutputPart.TRANSFORMED, metadataForTransformed2) .register("register-links", LINKS_KEY, EnumLimesOutputPart.ACCEPTED, metadataForLinks) .build(); return definition; } private ProcessDefinition buildDefinition1b() { final String TRANSFORM_1_KEY = "transformed-1", TRANSFORM_2_KEY = "transformed-2", LINKS_KEY = "links"; final String RESOURCE_1_KEY = "resource-1", RESOURCE_2_KEY = "resource-2"; ResourceMetadataCreate metadataForTransformed1 = new ResourceMetadataCreate("tr-1", "The 1st RDF file"); ResourceMetadataCreate metadataForTransformed2 = new ResourceMetadataCreate("tr-2", "The 2nd RDF file"); ResourceMetadataCreate metadataForLinks = new ResourceMetadataCreate("links-1-2", "A set of sameAs links between 1st and 2nd RDF files"); ProcessDefinition definition = processDefinitionBuilderFactory.create("proc-1-b") .resource(RESOURCE_1_NAME, RESOURCE_1_KEY, RESOURCE_1_ID) .resource(RESOURCE_2_NAME, RESOURCE_2_KEY, RESOURCE_2_ID) .transform("triplegeo-1", b -> b .group(1) .outputKey(TRANSFORM_1_KEY) .input(RESOURCE_1_KEY) .configuration(sampleTriplegeoConfiguration1)) .transform("triplegeo-2", b -> b .group(1) .outputKey(TRANSFORM_2_KEY) .input(RESOURCE_2_KEY) .configuration(sampleTriplegeoConfiguration1)) .interlink("link-1-with-2", b -> b .group(2) .configuration(sampleLimesConfiguration1) .left(TRANSFORM_1_KEY) .right(TRANSFORM_2_KEY) .outputKey(LINKS_KEY) .outputFormat(EnumDataFormat.N_TRIPLES)) .register("register-links", LINKS_KEY, EnumLimesOutputPart.ACCEPTED, metadataForLinks) .register("register-1", TRANSFORM_1_KEY, EnumTriplegeoOutputPart.TRANSFORMED, metadataForTransformed1) .register("register-2", TRANSFORM_2_KEY, EnumTriplegeoOutputPart.TRANSFORMED, metadataForTransformed2) .build(); return definition; } private ProcessDefinition buildDefinition1c() { final String TRANSFORM_1_KEY = "transformed-1", ENRICHED_1_KEY = "enriched-1"; final String RESOURCE_1_KEY = "resource-1"; ResourceMetadataCreate metadataForTransformed1 = new ResourceMetadataCreate("transfomed-1", "The 1st RDF file"); ResourceMetadataCreate metadataForEnriched1 = new ResourceMetadataCreate("enriched-1", "The 1st RDF file (enriched)"); ProcessDefinition definition = processDefinitionBuilderFactory.create("proc-1-c") .resource(RESOURCE_1_NAME, RESOURCE_1_KEY, RESOURCE_1_ID) .transform("triplegeo-1", b -> b .group(1) .outputKey(TRANSFORM_1_KEY) .input(RESOURCE_1_KEY) .configuration(sampleTriplegeoConfiguration1)) .enrich("deer-1", b -> b .group(2) .outputKey(ENRICHED_1_KEY) .input(TRANSFORM_1_KEY) .configuration(sampleDeerConfiguration1)) .register("register-transformed-1", TRANSFORM_1_KEY, EnumTriplegeoOutputPart.TRANSFORMED, metadataForTransformed1) .register("register-enriched-1", ENRICHED_1_KEY, EnumDeerOutputPart.ENRICHED, metadataForEnriched1) .build(); return definition; } private void serializeToJson(ProcessDefinition definition) throws Exception { String s1 = jsonMapper.writeValueAsString(definition); ProcessDefinition definition1 = jsonMapper.readValue(s1, ProcessDefinition.class); assertEquals(s1, jsonMapper.writeValueAsString(definition1)); System.err.println(s1); } private void serializeDefault(ProcessDefinition definition) throws Exception { String definitionAsJson = jsonMapper.writeValueAsString(definition); byte[] serializedData = null; try (ByteArrayOutputStream dataStream = new ByteArrayOutputStream()) { ObjectOutputStream out = new ObjectOutputStream(dataStream); out.writeObject(definition); out.flush(); serializedData = dataStream.toByteArray(); } ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serializedData)); ProcessDefinition deserializedDefinition = (ProcessDefinition) in.readObject(); assertEquals(definitionAsJson, jsonMapper.writeValueAsString(deserializedDefinition)); } private DependencyGraph buildDependencyGraph(ProcessDefinition definition) { List<ProcessInput> resources = definition.resources(); List<Step> steps = definition.steps(); // Map each output key to the key of processing step (expected to produce it) final Map<String, Integer> outputKeyToStepKey = resources.stream() .filter(r -> r.getInputType() == EnumInputType.OUTPUT) .collect(Collectors.toMap(r -> r.key(), r -> ((ProcessOutput) r).stepKey())); // Build dependency graph final DependencyGraph graph = DependencyGraphs.create(steps.size()); for (Step step: steps) { for (String k: step.inputKeys()) { if (outputKeyToStepKey.containsKey(k)) graph.addDependency(step.key(), outputKeyToStepKey.get(k)); } } System.err.println(DependencyGraphs.toString(graph, v -> definition.stepByKey(v).name())); return graph; } @Test public void test1a_checkDefinition() throws Exception { ProcessDefinition definition1 = buildDefinition1a(); assertNotNull(definition1); assertEquals("proc-1-a", definition1.name()); List<ProcessInput> resources = definition1.resources(); assertEquals(3, resources.size()); assertEquals(3, resources.stream().map(r -> r.key()).distinct().count()); List<Step> steps = definition1.steps(); assertEquals(6, steps.size()); assertEquals(6, steps.stream().mapToInt(s -> s.key()).distinct().count()); assertEquals( ImmutableSet.of( "register-1", "register-2", "register-links", "triplegeo-1", "triplegeo-2", "link-1-with-2"), steps.stream().map(r -> r.name()).collect(Collectors.toSet())); Step step1 = steps.stream().filter(s -> s.name().equals("triplegeo-1")).findFirst().get(); assertEquals(EnumTool.TRIPLEGEO, step1.tool()); assertEquals(EnumOperation.TRANSFORM, step1.operation()); assertEquals(EnumDataFormat.N_TRIPLES, step1.outputFormat()); assertEquals(0, step1.inputKeys().size()); assertNotNull(step1.outputKey()); assertEquals(1, step1.sources().size()); assertEquals(DATASOURCE_1_PATH, ((FileSystemDataSource) step1.sources().get(0)).getPath()); assertEquals( jsonMapper.writeValueAsString(sampleTriplegeoConfiguration1), jsonMapper.writeValueAsString(step1.configuration())); assertTrue(step1.configuration() instanceof TriplegeoConfiguration); assertEquals(EnumDataFormat.N_TRIPLES, step1.configuration().getOutputFormat()); Step step2 = steps.stream().filter(s -> s.name().equals("triplegeo-2")).findFirst().get(); assertEquals(EnumTool.TRIPLEGEO, step2.tool()); assertEquals(EnumOperation.TRANSFORM, step2.operation()); assertEquals(EnumDataFormat.N_TRIPLES, step2.outputFormat()); assertEquals(0, step2.inputKeys().size()); assertNotNull(step2.outputKey()); assertEquals(1, step2.sources().size()); assertEquals(DATASOURCE_2_PATH, ((FileSystemDataSource) step2.sources().get(0)).getPath()); assertEquals( jsonMapper.writeValueAsString(sampleTriplegeoConfiguration1), jsonMapper.writeValueAsString(step2.configuration())); assertTrue(step2.configuration() instanceof TriplegeoConfiguration); assertEquals(EnumDataFormat.N_TRIPLES, step2.configuration().getOutputFormat()); Step step3 = steps.stream().filter(s -> s.name().equals("link-1-with-2")).findFirst().get(); assertEquals(EnumTool.LIMES, step3.tool()); assertEquals(EnumOperation.INTERLINK, step3.operation()); assertEquals(EnumDataFormat.N_TRIPLES, step3.outputFormat()); assertEquals(2, step3.inputKeys().size()); assertEquals(step1.outputKey(), step3.inputKeys().get(0)); assertEquals(step2.outputKey(), step3.inputKeys().get(1)); assertEquals("transformed", step3.input().get(0).partKey()); assertEquals("transformed", step3.input().get(1).partKey()); assertEquals( jsonMapper.writeValueAsString(sampleLimesConfiguration1), jsonMapper.writeValueAsString(step3.configuration())); assertTrue(step3.configuration() instanceof LimesConfiguration); Step stepR1 = steps.stream().filter(s -> s.name().equals("register-1")).findFirst().get(); assertEquals(EnumTool.REGISTER, stepR1.tool()); assertEquals(EnumOperation.REGISTER, stepR1.operation()); assertEquals(Collections.singletonList(step1.outputKey()), stepR1.inputKeys()); assertEquals("transformed", stepR1.input().get(0).partKey()); assertNull(stepR1.outputKey()); assertNotNull(stepR1.configuration()); assertTrue(stepR1.configuration() instanceof RegisterToCatalogConfiguration); Step stepR2 = steps.stream().filter(s -> s.name().equals("register-2")).findFirst().get(); assertEquals(EnumTool.REGISTER, stepR2.tool()); assertEquals(EnumOperation.REGISTER, stepR2.operation()); assertEquals(Collections.singletonList(step2.outputKey()), stepR2.inputKeys()); assertEquals("transformed", stepR2.input().get(0).partKey()); assertNull(stepR2.outputKey()); assertNotNull(stepR2.configuration()); assertTrue(stepR2.configuration() instanceof RegisterToCatalogConfiguration); Step stepR3 = steps.stream().filter(s -> s.name().equals("register-links")).findFirst().get(); assertEquals(EnumTool.REGISTER, stepR3.tool()); assertEquals(EnumOperation.REGISTER, stepR3.operation()); assertEquals(Collections.singletonList(step3.outputKey()), stepR3.inputKeys()); assertEquals("accepted", stepR3.input().get(0).partKey()); assertNull(stepR3.outputKey()); assertNotNull(stepR3.configuration()); assertTrue(stepR3.configuration() instanceof RegisterToCatalogConfiguration); List<CatalogResource> catalogResources = resources.stream() .filter(r -> r.getInputType() == EnumInputType.CATALOG) .map(CatalogResource.class::cast) .collect(Collectors.toList()); assertEquals(0, catalogResources.size()); List<ProcessOutput> outputResources = resources.stream() .filter(r -> r.getInputType() == EnumInputType.OUTPUT) .map(ProcessOutput.class::cast) .collect(Collectors.toList()); assertEquals(3, outputResources.size()); assertEquals( ImmutableSet.of("triplegeo-1", "triplegeo-2", "link-1-with-2"), outputResources.stream().map(r -> r.getName()).collect(Collectors.toSet())); } @Test public void test1b_checkDefinition() throws Exception { ProcessDefinition definition1 = buildDefinition1b(); assertNotNull(definition1); assertEquals("proc-1-b", definition1.name()); List<ProcessInput> resources = definition1.resources(); assertEquals(5, resources.size()); assertEquals(5, resources.stream().map(r -> r.key()).distinct().count()); Map<String, ProcessInput> resourcesByKey = resources.stream() .collect(Collectors.toMap(r -> r.key(), Function.identity())); List<Step> steps = definition1.steps(); assertEquals(6, steps.size()); assertEquals(6, steps.stream().mapToInt(s -> s.key()).distinct().count()); assertEquals( ImmutableSet.of( "register-1", "register-2", "register-links", "triplegeo-1", "triplegeo-2", "link-1-with-2"), steps.stream().map(r -> r.name()).collect(Collectors.toSet())); Step step1 = steps.stream().filter(s -> s.name().equals("triplegeo-1")).findFirst().get(); assertEquals(EnumTool.TRIPLEGEO, step1.tool()); assertEquals(EnumOperation.TRANSFORM, step1.operation()); assertEquals(EnumDataFormat.N_TRIPLES, step1.outputFormat()); assertEquals(1, step1.inputKeys().size()); assertNotNull(step1.outputKey()); assertEquals(0, step1.sources().size()); assertNull(step1.input().get(0).partKey()); ProcessInput inp1 = resourcesByKey.get(step1.inputKeys().get(0)); assertNotNull(inp1); assertTrue(inp1 instanceof CatalogResource); assertEquals(RESOURCE_1_ID, ((CatalogResource) inp1).getResource()); assertEquals( jsonMapper.writeValueAsString(sampleTriplegeoConfiguration1), jsonMapper.writeValueAsString(step1.configuration())); assertTrue(step1.configuration() instanceof TriplegeoConfiguration); assertEquals(EnumDataFormat.N_TRIPLES, step1.configuration().getOutputFormat()); Step step2 = steps.stream().filter(s -> s.name().equals("triplegeo-2")).findFirst().get(); assertEquals(EnumTool.TRIPLEGEO, step2.tool()); assertEquals(EnumOperation.TRANSFORM, step2.operation()); assertEquals(EnumDataFormat.N_TRIPLES, step2.outputFormat()); assertEquals(1, step2.inputKeys().size()); assertNotNull(step2.outputKey()); assertEquals(0, step2.sources().size()); assertNull(step2.input().get(0).partKey()); ProcessInput inp2 = resourcesByKey.get(step2.inputKeys().get(0)); assertNotNull(inp2); assertTrue(inp2 instanceof CatalogResource); assertEquals(RESOURCE_2_ID, ((CatalogResource) inp2).getResource()); assertEquals( jsonMapper.writeValueAsString(sampleTriplegeoConfiguration1), jsonMapper.writeValueAsString(step2.configuration())); assertTrue(step2.configuration() instanceof TriplegeoConfiguration); assertEquals(EnumDataFormat.N_TRIPLES, step2.configuration().getOutputFormat()); Step step3 = steps.stream().filter(s -> s.name().equals("link-1-with-2")).findFirst().get(); assertEquals(EnumTool.LIMES, step3.tool()); assertEquals(EnumOperation.INTERLINK, step3.operation()); assertEquals(EnumDataFormat.N_TRIPLES, step3.outputFormat()); assertEquals(2, step3.inputKeys().size()); assertNotNull(step3.outputKey()); assertEquals(0, step3.sources().size()); assertNull(step3.input().get(0).partKey()); assertNull(step3.input().get(1).partKey()); ProcessInput inp3a = resourcesByKey.get(step3.inputKeys().get(0)); ProcessInput inp3b = resourcesByKey.get(step3.inputKeys().get(1)); assertNotNull(inp3a); assertNotNull(inp3b); assertTrue(inp3a instanceof ProcessOutput); assertTrue(inp3b instanceof ProcessOutput); assertEquals(step1.outputKey(), inp3a.key()); assertEquals(step2.outputKey(), inp3b.key()); assertEquals( jsonMapper.writeValueAsString(sampleLimesConfiguration1), jsonMapper.writeValueAsString(step3.configuration())); assertTrue(step3.configuration() instanceof LimesConfiguration); assertEquals(EnumDataFormat.N_TRIPLES, step3.configuration().getOutputFormat()); Step stepR1 = steps.stream().filter(s -> s.name().equals("register-1")).findFirst().get(); assertEquals(EnumTool.REGISTER, stepR1.tool()); assertEquals(EnumOperation.REGISTER, stepR1.operation()); assertEquals(Collections.singletonList(step1.outputKey()), stepR1.inputKeys()); assertEquals("transformed", stepR1.input().get(0).partKey()); assertNull(stepR1.outputKey()); assertNotNull(stepR1.configuration()); assertTrue(stepR1.configuration() instanceof RegisterToCatalogConfiguration); Step stepR2 = steps.stream().filter(s -> s.name().equals("register-2")).findFirst().get(); assertEquals(EnumTool.REGISTER, stepR2.tool()); assertEquals(EnumOperation.REGISTER, stepR2.operation()); assertEquals(Collections.singletonList(step2.outputKey()), stepR2.inputKeys()); assertEquals("transformed", stepR2.input().get(0).partKey()); assertNull(stepR2.outputKey()); assertNotNull(stepR2.configuration()); assertTrue(stepR2.configuration() instanceof RegisterToCatalogConfiguration); Step stepR3 = steps.stream().filter(s -> s.name().equals("register-links")).findFirst().get(); assertEquals(EnumTool.REGISTER, stepR3.tool()); assertEquals(EnumOperation.REGISTER, stepR3.operation()); assertEquals(Collections.singletonList(step3.outputKey()), stepR3.inputKeys()); assertEquals("accepted", stepR3.input().get(0).partKey()); assertNull(stepR3.outputKey()); assertNotNull(stepR3.configuration()); assertTrue(stepR3.configuration() instanceof RegisterToCatalogConfiguration); List<CatalogResource> catalogResources = resources.stream() .filter(r -> r.getInputType() == EnumInputType.CATALOG) .map(CatalogResource.class::cast) .collect(Collectors.toList()); assertEquals(2, catalogResources.size()); assertEquals( ImmutableSet.of(RESOURCE_1_NAME, RESOURCE_2_NAME), catalogResources.stream().map(r -> r.getName()).collect(Collectors.toSet())); List<ProcessOutput> outputResources = resources.stream() .filter(r -> r.getInputType() == EnumInputType.OUTPUT) .map(ProcessOutput.class::cast) .collect(Collectors.toList()); assertEquals(3, outputResources.size()); assertEquals( ImmutableSet.of("triplegeo-1", "triplegeo-2", "link-1-with-2"), outputResources.stream().map(r -> r.getName()).collect(Collectors.toSet())); } @Test public void test1c_checkDefinition() throws Exception { ProcessDefinition definition1 = buildDefinition1c(); assertNotNull(definition1); assertEquals("proc-1-c", definition1.name()); List<ProcessInput> resources = definition1.resources(); assertEquals(3, resources.size()); assertEquals(3, resources.stream().map(r -> r.key()).distinct().count()); Map<String, ProcessInput> resourcesByKey = resources.stream() .collect(Collectors.toMap(r -> r.key(), Function.identity())); List<Step> steps = definition1.steps(); assertEquals(4, steps.size()); assertEquals(4, steps.stream().mapToInt(s -> s.key()).distinct().count()); assertEquals( ImmutableSet.of("register-transformed-1", "register-enriched-1", "triplegeo-1", "deer-1"), steps.stream().map(r -> r.name()).collect(Collectors.toSet())); Step step1 = steps.stream().filter(s -> s.name().equals("triplegeo-1")).findFirst().get(); assertEquals(EnumTool.TRIPLEGEO, step1.tool()); assertEquals(EnumOperation.TRANSFORM, step1.operation()); assertEquals(EnumDataFormat.N_TRIPLES, step1.outputFormat()); assertEquals(1, step1.inputKeys().size()); assertNotNull(step1.outputKey()); assertEquals(0, step1.sources().size()); assertNull(step1.input().get(0).partKey()); ProcessInput inp1 = resourcesByKey.get(step1.inputKeys().get(0)); assertNotNull(inp1); assertTrue(inp1 instanceof CatalogResource); assertEquals(RESOURCE_1_ID, ((CatalogResource) inp1).getResource()); assertEquals( jsonMapper.writeValueAsString(sampleTriplegeoConfiguration1), jsonMapper.writeValueAsString(step1.configuration())); assertTrue(step1.configuration() instanceof TriplegeoConfiguration); assertEquals(EnumDataFormat.N_TRIPLES, step1.configuration().getOutputFormat()); Step step2 = steps.stream().filter(s -> s.name().equals("deer-1")).findFirst().get(); assertEquals(EnumTool.DEER, step2.tool()); assertEquals(EnumOperation.ENRICHMENT, step2.operation()); assertEquals(EnumDataFormat.N_TRIPLES, step2.outputFormat()); assertEquals(1, step2.inputKeys().size()); assertNotNull(step2.outputKey()); assertEquals(0, step2.sources().size()); assertNull(step2.input().get(0).partKey()); ProcessInput inp2 = resourcesByKey.get(step2.inputKeys().get(0)); assertNotNull(inp2); assertTrue(inp2 instanceof ProcessOutput); assertEquals(step1.key(), ((ProcessOutput) inp2).stepKey()); assertEquals( jsonMapper.writeValueAsString(sampleDeerConfiguration1), jsonMapper.writeValueAsString(step2.configuration())); assertTrue(step2.configuration() instanceof DeerConfiguration); assertEquals(EnumDataFormat.N_TRIPLES, step2.configuration().getOutputFormat()); Step stepR1 = steps.stream().filter(s -> s.name().equals("register-transformed-1")).findFirst().get(); assertEquals(EnumTool.REGISTER, stepR1.tool()); assertEquals(EnumOperation.REGISTER, stepR1.operation()); assertEquals(Collections.singletonList(step1.outputKey()), stepR1.inputKeys()); assertEquals("transformed", stepR1.input().get(0).partKey()); assertNull(stepR1.outputKey()); assertNotNull(stepR1.configuration()); assertTrue(stepR1.configuration() instanceof RegisterToCatalogConfiguration); Step stepR2 = steps.stream().filter(s -> s.name().equals("register-enriched-1")).findFirst().get(); assertEquals(EnumTool.REGISTER, stepR1.tool()); assertEquals(EnumOperation.REGISTER, stepR1.operation()); assertEquals(Collections.singletonList(step2.outputKey()), stepR2.inputKeys()); assertEquals("enriched", stepR2.input().get(0).partKey()); assertNull(stepR2.outputKey()); assertNotNull(stepR2.configuration()); assertTrue(stepR2.configuration() instanceof RegisterToCatalogConfiguration); List<CatalogResource> catalogResources = resources.stream() .filter(r -> r.getInputType() == EnumInputType.CATALOG) .map(CatalogResource.class::cast) .collect(Collectors.toList()); assertEquals(1, catalogResources.size()); assertEquals( ImmutableSet.of(RESOURCE_1_NAME), catalogResources.stream().map(r -> r.getName()).collect(Collectors.toSet())); List<ProcessOutput> outputResources = resources.stream() .filter(r -> r.getInputType() == EnumInputType.OUTPUT) .map(ProcessOutput.class::cast) .collect(Collectors.toList()); assertEquals(2, outputResources.size()); assertEquals( ImmutableSet.of("triplegeo-1", "deer-1"), outputResources.stream().map(r -> r.getName()).collect(Collectors.toSet())); } @Test public void test1a_serializeToJson() throws Exception { serializeToJson(buildDefinition1a()); } @Test public void test1b_serializeToJson() throws Exception { serializeToJson(buildDefinition1b()); } @Test public void test1c_serializeToJson() throws Exception { serializeToJson(buildDefinition1c()); } @Test public void test1a_serializeDefault() throws Exception { serializeDefault(buildDefinition1a()); } @Test public void test1b_serializeDefault() throws Exception { serializeDefault(buildDefinition1b()); } @Test public void test1c_serializeDefault() throws Exception { serializeDefault(buildDefinition1c()); } @Test(expected = UnsupportedOperationException.class) public void test1a_checkDefinitionUnmodifiableSteps1() { ProcessDefinition definition1 = buildDefinition1a(); List<Step> steps = definition1.steps(); steps.remove(0); // attempt to remove a step } @Test(expected = UnsupportedOperationException.class) public void test1a_checkDefinitionUnmodifiableSteps2() { ProcessDefinition definition1 = buildDefinition1a(); List<Step> steps = definition1.steps(); Step step1 = steps.get(0); steps.add(step1); // attempt to add a step } @Test(expected = UnsupportedOperationException.class) public void test1a_checkDefinitionUnmodifiableResources1() { ProcessDefinition definition1 = buildDefinition1a(); List<ProcessInput> resources = definition1.resources(); resources.remove(0); // attempt to remove a resource } @Test(expected = UnsupportedOperationException.class) public void test1a_checkDefinitionUnmodifiableResources2() { ProcessDefinition definition1 = buildDefinition1a(); List<ProcessInput> resources = definition1.resources(); ProcessInput res1 = resources.get(0); resources.add(res1); } @Test(expected = IllegalStateException.class) public void test1a_checkDefinitionUnmodifiableConfiguration() { ProcessDefinition definition1 = buildDefinition1a(); Step step11 = definition1.stepByNodeName("triplegeo-1"); TriplegeoConfiguration configuration = (TriplegeoConfiguration) step11.configuration(); configuration.setAttrKey("koukou"); } @Test public void test1a_buildDependencyGraph() throws Exception { ProcessDefinition def1 = buildDefinition1a(); DependencyGraph graph = buildDependencyGraph(def1); List<Step> stepsInTopologicalOrder = Lists.newArrayList( Iterables.transform(DependencyGraphs.topologicalSort(graph), k -> def1.stepByKey(k))); List<String> stepNames = Lists.transform(stepsInTopologicalOrder, s -> s.name()); System.err.println(stepNames); assertTrue(stepNames.indexOf("triplegeo-1") < stepNames.indexOf("register-1")); assertTrue(stepNames.indexOf("triplegeo-2") < stepNames.indexOf("register-2")); assertTrue(stepNames.indexOf("link-1-with-2") < stepNames.indexOf("register-links")); assertTrue(stepNames.indexOf("triplegeo-1") < stepNames.indexOf("link-1-with-2")); assertTrue(stepNames.indexOf("triplegeo-2") < stepNames.indexOf("link-1-with-2")); } @Test(expected = IllegalStateException.class) public void test_checkRegisterUndefinedResource1() { final String resourceKey = "something"; // not a catalog resource, neither is an output from another step ProcessDefinition definition = processDefinitionBuilderFactory.create("register-1") .register("register-1", resourceKey, new ResourceMetadataCreate("sample", "Another sample")) .build(); System.err.println(definition); } @Test(expected = IllegalStateException.class) public void test_checkInputFromUndefinedResource1() { final String inputKey1 = "res-1"; final String inputKey2 = "res-X"; // not a catalog resource, neither is an output from another step final String outputKey = "transformed-1"; ProcessDefinition definition = processDefinitionBuilderFactory.create("register-1") .resource("res-1", inputKey1, ResourceIdentifier.of(5L, 27L)) .transform("triplegeo-1", builder -> builder .input(inputKey2) .configuration(sampleTriplegeoConfiguration1) .outputFormat(EnumDataFormat.N_TRIPLES) .outputKey(outputKey)) .build(); System.err.println(definition); } @Test(expected = IllegalStateException.class) public void test_checkInputOfNonExistingOutputPart() { final String RESOURCE_1_KEY = "res-1", TRANSFORM_1_KEY = "transformed-1"; final ResourceMetadataCreate metadata = new ResourceMetadataCreate("tr-1", "An RDF file"); ProcessDefinition definition = processDefinitionBuilderFactory.create("register-1") .resource(RESOURCE_1_NAME, RESOURCE_1_KEY, RESOURCE_1_ID) .transform("triplegeo-1", builder -> builder .input(RESOURCE_1_KEY, EnumImportDataOutputPart.DOWNLOAD) // a catalog resource has no parts! .configuration(sampleTriplegeoConfiguration1) .outputFormat(EnumDataFormat.N_TRIPLES) .outputKey(TRANSFORM_1_KEY)) .register("register-1", TRANSFORM_1_KEY, EnumTriplegeoOutputPart.TRANSFORMED, metadata) .build(); System.err.println(definition); } @Test(expected = IllegalStateException.class) public void test_checkInputOfUnknownOutputPart() { final String RESOURCE_1_KEY = "res-1", TRANSFORM_1_KEY = "transformed-1"; final ResourceMetadataCreate metadata = new ResourceMetadataCreate("tr-1", "An RDF file"); ProcessDefinition definition = processDefinitionBuilderFactory.create("register-1") .resource(RESOURCE_1_NAME, RESOURCE_1_KEY, RESOURCE_1_ID) .transform("triplegeo-1", builder -> builder .input(RESOURCE_1_KEY) .configuration(sampleTriplegeoConfiguration1) .outputFormat(EnumDataFormat.N_TRIPLES) .outputKey(TRANSFORM_1_KEY)) // Cannot refer to a non-existing part of output identified by TRANSFORM_1_KEY! .register("register-1", TRANSFORM_1_KEY, BazOutputPart.BAZ_1, metadata) .build(); System.err.println(definition); } @Test(expected = IllegalArgumentException.class) public void test_checkInputOfInvalidOutputPart() { final String RESOURCE_1_KEY = "res-1", TRANSFORM_1_KEY = "transformed-1"; final ResourceMetadataCreate metadata = new ResourceMetadataCreate("tr-1", "An RDF file"); ProcessDefinition definition = processDefinitionBuilderFactory.create("register-1") .resource(RESOURCE_1_NAME, RESOURCE_1_KEY, RESOURCE_1_ID) .transform("triplegeo-1", builder -> builder .input(RESOURCE_1_KEY) .configuration(sampleTriplegeoConfiguration1) .outputFormat(EnumDataFormat.N_TRIPLES) .outputKey(TRANSFORM_1_KEY)) // Cannot refer to a part of a non-OUTPUT output (e.g. KPI data)! .register("register-1", TRANSFORM_1_KEY, EnumTriplegeoOutputPart.TRANSFORMED_METADATA, metadata) .build(); System.err.println(definition); } @Test public void test1a_scratch() throws Exception { ProcessDefinition definition1 = buildDefinition1a(); String s1 = jsonMapper.writeValueAsString(definition1); System.err.println(s1); ProcessDefinition definition1a = jsonMapper.readValue(s1, ProcessDefinition.class); String s2 = jsonMapper.writeValueAsString(definition1a); assertEquals(s1, s2); final List<ProcessInput> inputs = definition1.resources(); final List<Step> steps = definition1.steps(); final DependencyGraph dependencyGraph = buildDependencyGraph(definition1); Iterable<Step> stepsInTopologicalOrder = IterableUtils.transformedIterable( DependencyGraphs.topologicalSort(dependencyGraph), k -> definition1.stepByKey(k)); } }
44.824865
113
0.671563
69a15370b7d0e4dc8a7879db4e7e637ea93c5719
274
package deltix.luminary; public class TypeUInt64 extends Type { private TypeUInt64() { super(TypeKind.UINT64); } public static final TypeUInt64 INSTANCE = new TypeUInt64(); @Override public String toString() { return "UInt64"; } }
18.266667
63
0.645985
89c1fec8880b2dfa973a094c722f0e526e8f06cc
1,653
package io.codejournal.codingbat.array1; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.codejournal.codingbat.array1.MakeLast; public class MakeLastTest { private MakeLast fixture; @BeforeEach public void setUp() { fixture = new MakeLast(); } @Test public void testcase1() { final int[] nums = new int[] { 4, 5, 6 }; final int[] expected = new int[] { 0, 0, 0, 0, 0, 6 }; final int[] actual = fixture.makeLast(nums); assertThat(actual).isEqualTo(expected); } @Test public void testcase2() { final int[] nums = new int[] { 1, 2 }; final int[] expected = new int[] { 0, 0, 0, 2 }; final int[] actual = fixture.makeLast(nums); assertThat(actual).isEqualTo(expected); } @Test public void testcase3() { final int[] nums = new int[] { 3 }; final int[] expected = new int[] { 0, 3 }; final int[] actual = fixture.makeLast(nums); assertThat(actual).isEqualTo(expected); } @Test public void shouldReturnEmptyWhenNumsIsNull() { final int[] nums = null; final int[] expected = new int[] {}; final int[] actual = fixture.makeLast(nums); assertThat(actual).isEqualTo(expected); } @Test public void shouldReturnEmptyWhenNumsIsEmpty() { final int[] nums = new int[] {}; final int[] expected = new int[] {}; final int[] actual = fixture.makeLast(nums); assertThat(actual).isEqualTo(expected); } }
20.924051
62
0.594071
a3ec679177f04bd5cf3dac6ad64a63a2a8e74bd0
4,433
/** * Copyright (c) 2016-2019 人人开源 All rights reserved. * <p> * https://www.renren.io * <p> * 版权所有,侵权必究! */ package io.renren.modules.org_cbs.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import io.renren.common.utils.Constant; import io.renren.common.utils.PageUtils; import io.renren.common.utils.QueryPage; import io.renren.modules.org_cbs.dao.OrgCbsUserDao; import io.renren.modules.org_cbs.entity.OrgCbsUserEntity; import io.renren.modules.org_cbs.service.OrgCbsRoleService; import io.renren.modules.org_cbs.service.OrgCbsUserRoleService; import io.renren.modules.org_cbs.service.OrgCbsUserService; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; import org.apache.shiro.crypto.hash.Sha256Hash; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.Date; import java.util.List; /** * 系统用户 * * @author Mark sunlightcs@gmail.com */ @Service("orgCbsUserService") public class OrgCbsUserServiceImpl extends ServiceImpl<OrgCbsUserDao, OrgCbsUserEntity> implements OrgCbsUserService { @Autowired private OrgCbsUserRoleService orgCbsUserRoleService; @Autowired private OrgCbsRoleService orgCbsRoleService; @Override public PageUtils queryPage(OrgCbsUserEntity entity) { QueryWrapper<OrgCbsUserEntity> qw = new QueryWrapper<>(); qw.eq("tenant_id", entity.getTenantId()); qw.ne("username", "admin"); qw.like(StringUtils.isNotBlank(entity.getUsername()), "username", entity.getUsername()); IPage<OrgCbsUserEntity> page = this.page(new QueryPage<OrgCbsUserEntity>().getPage(entity), qw); return new PageUtils(page); } @Override public List<String> queryAllPerms(Long userId) { return baseMapper.queryAllPerms(userId); } @Override public List<Long> queryAllMenuId(Long userId) { return baseMapper.queryAllMenuId(userId); } @Override public OrgCbsUserEntity queryByUserName(Long tenantId, String username) { return baseMapper.selectOne(new QueryWrapper<OrgCbsUserEntity>().eq("username", username).eq("tenant_id", tenantId)); } @Override @Transactional public void saveUser(OrgCbsUserEntity user) { //检查角色是否越权 checkRole(user); user.setCreateTime(new Date()); //sha256加密 String salt = RandomStringUtils.randomAlphanumeric(20); user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex()); user.setSalt(salt); this.save(user); //保存用户与角色关系 orgCbsUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList()); } @Override @Transactional public void update(OrgCbsUserEntity user) { //检查角色是否越权 checkRole(user); if (StringUtils.isBlank(user.getPassword())) { user.setPassword(user.getPassword()); } else { user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex()); } this.updateById(user); //保存用户与角色关系 orgCbsUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList()); } @Override public void deleteBatch(Long[] userId) { this.removeByIds(Arrays.asList(userId)); } @Override public boolean updatePassword(Long userId, String password, String newPassword) { return this.update(OrgCbsUserEntity.builder().password(newPassword).build(), new QueryWrapper<OrgCbsUserEntity>().eq("user_id", userId).eq("password", password)); } /** * 检查角色是否越权 */ private void checkRole(OrgCbsUserEntity user) { if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) { return; } //如果不是超级管理员,则需要判断用户的角色是否自己创建 if (Constant.SUPER_ADMIN_NAME.equals(user.getUsername())) { return; } //查询用户创建的角色列表 List<Long> roleIdList = orgCbsRoleService.queryRoleIdList(user.getCreateUserId()); //判断是否越权 // if (!roleIdList.containsAll(user.getRoleIdList())) { // throw new RRException("新增用户所选角色,不是本人创建"); // } } }
32.595588
125
0.695015
b4004de4aa8e007ed32891fb05c0a79dcad71f78
1,357
package com.zhao.platform.configuration; import lombok.Data; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import java.util.concurrent.ThreadPoolExecutor; /** * @author zhaoyanjiang-pc */ public class ThreadConfig { static TaskExecutor taskExecutor = ThreadConfig.taskExecutor(); public static TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 设置核心线程数 executor.setCorePoolSize(1); // 设置最大线程数 executor.setMaxPoolSize(1); // 设置队列容量 executor.setQueueCapacity(1); // 设置线程活跃时间(秒) executor.setKeepAliveSeconds(60); // 设置默认线程名称 executor.setThreadNamePrefix("system-"); // 设置拒绝策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); executor.initialize(); return executor; } public static TaskExecutor getInstance(){ return taskExecutor; } }
32.309524
88
0.728077
90440568808eac431aa72b851568850eabc1c672
17,605
/** * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.datascience; import com.oracle.bmc.datascience.requests.*; import com.oracle.bmc.datascience.responses.*; /** * Use the Data Science APIs to organize your data science work, access data and computing resources, and build, train, deploy, and manage models on Oracle Cloud. * */ @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20190101") public interface DataScience extends AutoCloseable { /** * Sets the endpoint to call (ex, https://www.example.com). * @param endpoint The endpoint of the service. */ void setEndpoint(String endpoint); /** * Sets the region to call (ex, Region.US_PHOENIX_1). * <p> * Note, this will call {@link #setEndpoint(String) setEndpoint} after resolving the endpoint. If the service is not available in this Region, however, an IllegalArgumentException will be raised. * @param region The region of the service. */ void setRegion(com.oracle.bmc.Region region); /** * Sets the region to call (ex, 'us-phoenix-1'). * <p> * Note, this will first try to map the region ID to a known Region and call * {@link #setRegion(Region) setRegion}. * <p> * If no known Region could be determined, it will create an endpoint based on the * default endpoint format ({@link com.oracle.bmc.Region#formatDefaultRegionEndpoint(Service, String)} * and then call {@link #setEndpoint(String) setEndpoint}. * @param regionId The public region ID. */ void setRegion(String regionId); /** * Activates the model. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ActivateModelResponse activateModel(ActivateModelRequest request); /** * Activates the notebook session. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ActivateNotebookSessionResponse activateNotebookSession(ActivateNotebookSessionRequest request); /** * Cancels a work request that has not started. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ CancelWorkRequestResponse cancelWorkRequest(CancelWorkRequestRequest request); /** * Moves a model resource into a different compartment. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ChangeModelCompartmentResponse changeModelCompartment(ChangeModelCompartmentRequest request); /** * Moves a notebook session resource into a different compartment. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ChangeNotebookSessionCompartmentResponse changeNotebookSessionCompartment( ChangeNotebookSessionCompartmentRequest request); /** * Moves a project resource into a different compartment. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ChangeProjectCompartmentResponse changeProjectCompartment( ChangeProjectCompartmentRequest request); /** * Creates a new model. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ CreateModelResponse createModel(CreateModelRequest request); /** * Creates model artifact for specified model. * * Note: This operation consumes a stream. * * If the stream supports {@link java.io.InputStream#mark(int)} and {@link java.io.InputStream#reset()}, when a retry is * necessary, the stream is reset so it starts at the beginning (or whatever the stream's position was at the time this * operation is called}. * * Note this means that if the caller has used {@link java.io.InputStream#mark(int)} before, then the mark * will not be the same anymore after this operation, and a subsequent call to {@link java.io.InputStream#reset()} by * the caller will reset the stream not to the caller's mark, but to the position the stream was in when this operation * was called. * * If the stream is a {@link java.io.FileInputStream}, and the stream's {@link java.nio.channels.FileChannel} position * can be changed (like for a regular file), the stream will be wrapped in such a way that it does provide * support for {@link java.io.InputStream#mark(int)} and {@link java.io.InputStream#reset()}. Then the same procedure as * above is followed. If the stream's {@link java.nio.channels.FileChannel} position cannot be changed (like for a * named pipe), then the stream's contents will be buffered in memory, as described below. * * If the stream does not support {@link java.io.InputStream#mark(int)} and {@link java.io.InputStream#reset()}, then * the stream is wrapped in a {@link java.io.BufferedInputStream}, which means the entire contents may * be buffered in memory. Then the same procedure as above is followed. * * The contents of the stream, except when the stream is a {@link java.io.FileInputStream} whose * {@link java.nio.channels.FileChannel} position can be changed, should be less than 2 GiB in size if retries are used. * This is because streams 2 GiB in size or larger do no guarantee that mark-and-reset can be performed. If the stream * is larger, do not use built-in retries and manage retries yourself. * * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ CreateModelArtifactResponse createModelArtifact(CreateModelArtifactRequest request); /** * Creates provenance information for the specified model. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ CreateModelProvenanceResponse createModelProvenance(CreateModelProvenanceRequest request); /** * Creates a new notebook session. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ CreateNotebookSessionResponse createNotebookSession(CreateNotebookSessionRequest request); /** * Creates a new project. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ CreateProjectResponse createProject(CreateProjectRequest request); /** * Deactivates the model. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ DeactivateModelResponse deactivateModel(DeactivateModelRequest request); /** * Deactivates the notebook session. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ DeactivateNotebookSessionResponse deactivateNotebookSession( DeactivateNotebookSessionRequest request); /** * Deletes the specified model. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ DeleteModelResponse deleteModel(DeleteModelRequest request); /** * Deletes the specified notebook session. Any unsaved work in this notebook session will be lost. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ DeleteNotebookSessionResponse deleteNotebookSession(DeleteNotebookSessionRequest request); /** * Deletes the specified project. This operation will fail unless all associated resources (such as notebook sessions or models) are in a DELETED state. You must delete all associated resources before deleting a project. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ DeleteProjectResponse deleteProject(DeleteProjectRequest request); /** * Gets the specified model's information. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ GetModelResponse getModel(GetModelRequest request); /** * Downloads model artifact content for specified model. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ GetModelArtifactContentResponse getModelArtifactContent(GetModelArtifactContentRequest request); /** * Gets provenance information for specified model. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ GetModelProvenanceResponse getModelProvenance(GetModelProvenanceRequest request); /** * Gets the specified notebook session's information. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ GetNotebookSessionResponse getNotebookSession(GetNotebookSessionRequest request); /** * Gets the specified project's information. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ GetProjectResponse getProject(GetProjectRequest request); /** * Gets the specified work request's information. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ GetWorkRequestResponse getWorkRequest(GetWorkRequestRequest request); /** * Gets model artifact metadata for specified model. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ HeadModelArtifactResponse headModelArtifact(HeadModelArtifactRequest request); /** * Lists models in the specified compartment. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ListModelsResponse listModels(ListModelsRequest request); /** * Lists the valid notebook session shapes. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ListNotebookSessionShapesResponse listNotebookSessionShapes( ListNotebookSessionShapesRequest request); /** * Lists notebook sessions in the specified compartment. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ListNotebookSessionsResponse listNotebookSessions(ListNotebookSessionsRequest request); /** * Lists projects in the specified compartment. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ListProjectsResponse listProjects(ListProjectsRequest request); /** * Lists work request errors for the specified work request. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ListWorkRequestErrorsResponse listWorkRequestErrors(ListWorkRequestErrorsRequest request); /** * Lists work request logs for the specified work request. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ListWorkRequestLogsResponse listWorkRequestLogs(ListWorkRequestLogsRequest request); /** * Lists work requests in the specified compartment. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ ListWorkRequestsResponse listWorkRequests(ListWorkRequestsRequest request); /** * Updates the properties of a model. You can update the `displayName`, `description`, `freeformTags`, and `definedTags` properties. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ UpdateModelResponse updateModel(UpdateModelRequest request); /** * Updates provenance information for the specified model. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ UpdateModelProvenanceResponse updateModelProvenance(UpdateModelProvenanceRequest request); /** * Updates the properties of a notebook session. You can update the `displayName`, `freeformTags`, and `definedTags` properties. * When the notebook session is in the INACTIVE lifecycle state, you can update `notebookSessionConfigurationDetails` and change `shape`, `subnetId`, and `blockStorageSizeInGBs`. * Changes to the `notebookSessionConfigurationDetails` will take effect the next time the `ActivateNotebookSession` action is invoked on the notebook session resource. * * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ UpdateNotebookSessionResponse updateNotebookSession(UpdateNotebookSessionRequest request); /** * Updates the properties of a project. You can update the `displayName`, `description`, `freeformTags`, and `definedTags` properties. * @param request The request object containing the details to send * @return A response object containing details about the completed operation * @throws BmcException when an error occurs. */ UpdateProjectResponse updateProject(UpdateProjectRequest request); /** * Gets the pre-configured waiters available for resources for this service. * * @return The service waiters. */ DataScienceWaiters getWaiters(); /** * Gets the pre-configured paginators available for list operations in this service which may return multiple * pages of data. These paginators provide an {@link java.lang.Iterable} interface so that service responses, or * resources/records, can be iterated through without having to manually deal with pagination and page tokens. * * @return The service paginators. */ DataSciencePaginators getPaginators(); }
48.101093
246
0.731667
01431871d4cf0c169df2d31e3cf3987ff818e257
27,304
/* * Copyright 2012 Achim Nierbeck. * * 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.ops4j.pax.web.utils; import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Pattern; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utilities to perform bundle scanning - using only OSGi Core APIs (without using e.g., XBean Finder) * @author achim */ public class ClassPathUtil { private static final Logger LOG = LoggerFactory.getLogger(ClassPathUtil.class); private ClassPathUtil() { } /** * <p>Returns a list of urls for jars that compose the Bundle-ClassPath and (with {@code useClassSpace} = {@code true}) * also a list of different URLs for bundles in <em>class space</em> (which includes bundles for imported packages, * fragments, wires of fragments and required bundles).</p> * <p>This method doesn't return the URL of passed bundle itself.</p> * * @param bundle the bundle from which the class path should be taken * @param useClassSpace wheter to add also bundles reachable via different <em>wires</em> (required bundles, * imported packages and fragments) * @return list or urls to jars that composes the Bundle-ClassPath. Each JAR is returned as URL in the form * {@code jar:<location>!/}, where {@code <location>} may be for example * {@code bundle://30.0:0/WEB-INF/lib/myfaces-impl-2.2.12.jar} */ public static URL[] getClassPathJars(final Bundle bundle, boolean useClassSpace) { final List<URL> urls = new ArrayList<>(); final String bundleClasspath = bundle.getHeaders() == null ? null : bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); if (bundleClasspath != null) { String[] segments = bundleClasspath.split("\\s*,\\s*"); for (String segment : segments) { final URL url = bundle.getEntry(segment); if (url != null && url.toExternalForm().endsWith("jar")) { try { // sun.net.www.protocol.jar.Handler.separator = "!/" urls.add(new URL("jar:" + url.toExternalForm() + "!/")); } catch (MalformedURLException ignore) { LOG.debug(ignore.getMessage()); } } } } if (useClassSpace) { // adds the depending bundles to the "classloader" space urls.addAll(getLocationsOfBundlesInClassSpace(bundle)); } return urls.toArray(new URL[urls.size()]); } /** * <p>Returns a list of urls for all entries that compose the Bundle-ClassPath.</p> * * @param bundle * @return */ public static URL[] getClassPathURLs(final Bundle bundle) { final List<URL> urls = new ArrayList<>(); final String bundleClasspath = bundle.getHeaders() == null ? null : bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); if (bundleClasspath != null) { String[] segments = bundleClasspath.split("\\s*,\\s*"); for (String segment : segments) { final URL url = bundle.getEntry(segment); if (url == null) { continue; } String ef = url.toExternalForm(); try { if (ef.endsWith("jar")) { // sun.net.www.protocol.jar.Handler.separator = "!/" urls.add(new URL("jar:" + ef + "!/")); } else { // assume it's a subdirectory of a bundle if (!ef.endsWith("/")) { urls.add(new URL(ef + "/")); } else { urls.add(url); } } } catch (MalformedURLException ignore) { LOG.debug(ignore.getMessage()); } } } return urls.toArray(new URL[urls.size()]); } /** * <p>Returns a list of urls for all non-JAR entries that compose the Bundle-ClassPath.</p> * * @param bundle * @return */ public static URL[] getClassPathNonJars(final Bundle bundle) { final List<URL> urls = new ArrayList<>(); final String bundleClasspath = bundle.getHeaders() == null ? null : bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); if (bundleClasspath == null) { // fallback to just root directory of the bundle return new URL[] { bundle.getEntry("/") }; } else { String[] segments = bundleClasspath.split("\\s*,\\s*"); for (String segment : segments) { final URL url = bundle.getEntry(segment); if (url == null) { continue; } String ef = url.toExternalForm(); try { if (!ef.endsWith("jar")) { // assume it's a subdirectory of a bundle if (!ef.endsWith("/")) { urls.add(new URL(ef + "/")); } else { urls.add(url); } } } catch (MalformedURLException ignore) { LOG.debug(ignore.getMessage()); } } } return urls.toArray(new URL[urls.size()]); } /** * Returns a list of urls to jars that composes the Bundle-ClassPath and also a list of different URLs for bundles * in <em>class space</em> (which includes bundles for imported packages, fragments, wires of fragments and * required bundles) * * @param bundle the bundle from which the class path should be taken * @return list or urls to jars that composes the Bundle-ClassPath. * * @deprecated use {@link #getClassPathJars(Bundle, boolean)}. */ @Deprecated public static URL[] getClassPathJars(final Bundle bundle) { return getClassPathJars(bundle, true); } /** * Gets the locations of the bundles in the Class Space. Beware, in Karaf * this will return the URL with which the bundle was originally * provisioned, i.e. could potentially return wrap:..., mvn:..., etc. and * even include URL parameters (i.e. ?Webapp-Context=...). * * @param bundle the bundle for which to perform the lookup * @return list of locations of bundles in class space */ private static List<URL> getLocationsOfBundlesInClassSpace(Bundle bundle) { List<URL> urls = new ArrayList<>(); Set<Bundle> importedBundles = getBundlesInClassSpace(bundle, new HashSet<>()); for (Bundle importedBundle : importedBundles) { URL url = getLocationOfBundle(importedBundle); if (url != null) { urls.add(url); } } return urls; } private static URL getLocationOfBundle(Bundle bundle) { URL url = null; try { url = new URL(bundle.getLocation()); } catch (MalformedURLException e) { try { url = bundle.getEntry("/"); } catch (Exception e2) { LOG.warn("Exception while calculating location of bundle", e); } } return url; } /** * Gets a list of bundles that are imported or required by given {@link Bundle}. This method also returns * attached fragments. * * @param bundle * @param bundleSet * @return */ public static Set<Bundle> getBundlesInClassSpace(Bundle bundle, Set<Bundle> bundleSet) { BundleWiring bundleWiring = bundle == null ? null : bundle.adapt(BundleWiring.class); if (bundle == null || bundleWiring == null) { throw new IllegalArgumentException("Bundle, BundleContext or BundleWiring is null"); } Set<Bundle> bundles = new HashSet<>(); // This will give us all required Wires (including Require-Bundle). We're mostly interested in // wires from namespaces: // - org.osgi.framework.namespace.BundleNamespace.BUNDLE_NAMESPACE = "osgi.wiring.bundle" // - org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE = "osgi.wiring.package" List<BundleWire> requiredWires = bundleWiring.getRequiredWires(null); for (BundleWire bundleWire : requiredWires) { if (!(bundleWire.getRequirement().getNamespace().equals(BundleNamespace.BUNDLE_NAMESPACE) || (bundleWire.getRequirement().getNamespace().equals(PackageNamespace.PACKAGE_NAMESPACE)))) { continue; } Bundle exportingBundle = bundleWire.getCapability().getRevision().getBundle(); if (exportingBundle.getBundleId() == 0) { continue; // system bundle is skipped this one isn't needed } bundles.add(exportingBundle); } // fragments attached to checked bundle List<BundleWire> providedWires = bundleWiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); if (providedWires != null) { for (BundleWire wire : providedWires) { Bundle b = wire.getRequirerWiring().getBundle(); bundles.add(b); } } if (!bundleSet.containsAll(bundles)) { // there are new bundles found, that are not in the set that we're collecting, // leave the new ones bundles.removeAll(bundleSet); // include the new ones in the set we're collecting bundleSet.addAll(bundles); // collect transitively for (Bundle b : bundles) { getBundlesInClassSpace(b, bundleSet); } } // Sanity checkpoint to remove uninstalled bundles bundleSet.removeIf(b -> b.getState() == Bundle.UNINSTALLED); // And system bundle bundleSet.removeIf(b -> b.getBundleId() == 0L); return bundleSet; } /** * <p>This method uses {@link BundleWiring#listResources} that delegates to classloader. If there are * more visible resources with the same name, only one is returned.</p> * * <p>This method is not a good choice to discover manifests or e.g., {@code faces-context.xml} files, * if for single bundle many resources with the same path may be returned (as in case of WAR with Bundle-ClassPath * or with fragments).</p> * * <p>This method is also not good choice to get {@code /META-INF/services/*} files, as these should be accessed * using classloaders - a {@link Bundle} may have multiple entries on its {@code Bundle-ClassPath}, so * such service descriptors should be loaded from all the roots.</p> * * @param bundles * @param path * @param pattern * @param recurse * @return */ public static List<URL> listResources(Iterable<Bundle> bundles, String path, String pattern, boolean recurse) { List<URL> resources = new ArrayList<>(); for (Bundle bundle : bundles) { int options = BundleWiring.LISTRESOURCES_LOCAL | (recurse ? BundleWiring.LISTRESOURCES_RECURSE : 0); boolean isFragment = bundle.adapt(BundleRevision.class) != null && (bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0; if (!isFragment) { // for fragment, org.osgi.framework.wiring.BundleWiring.listResources() should return "empty // collection" and it's exactly the case with Equinox, however Felix returns some names... // and later org.osgi.framework.Bundle.getResource() returns null for this name BundleWiring wiring = bundle.adapt(BundleWiring.class); Collection<String> names = wiring.listResources(path, pattern, options); for (String name : names) { resources.add(bundle.getResource(name)); } } } return resources; } /** * <p>This method uses {@link Bundle#getResources(String)} that delegates to classloader. If there are more visible * resources with the same name, <strong>all are returned</strong> (differently than with * {@link #listResources}).</p> * * <p>This method is the only choice to load resources using classloaders (respecting {@code Bundle-ClassPath}), * and checking attached bundle fragments, but the problem is that it doesn't allow to use patterns.</p> * * <p>The important thing to note is that if the bundle is in INSTALLED state, there'll be an attempt to resolve * it.</p> * * @param bundles * @param path * @return */ public static List<URL> getResources(Iterable<Bundle> bundles, String path) { List<URL> resources = new ArrayList<>(); for (Bundle bundle : bundles) { boolean isFragment = bundle.adapt(BundleRevision.class) != null && (bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0; if (!isFragment) { Enumeration<URL> e = null; try { e = bundle.getResources(path); if (e != null) { while (e.hasMoreElements()) { resources.add(e.nextElement()); } } } catch (IOException ioe) { LOG.warn("Problem getting {} resource from {}: {}", path, bundle, ioe.getMessage(), ioe); } } } return resources; } /** * This method uses {@link BundleWiring#findEntries} that doesn't involve classloaders so we can get resources * from fixed path. This way we can find multiple resources with the same path (when for example a bundle has * attached fragment, which has the same entries). Normally {@link BundleWiring#findEntries} doesn't check JARs * listed on {@code Bundle-ClassPath} (because it doesn't work at classloader level), however we can explicitly * tell it to do so. * * @param bundle * @param path * @param pattern * @param recurse * @param useBundleClasspath * @return * @throws IOException */ public static List<URL> findEntries(Bundle bundle, String path, String pattern, boolean recurse, boolean useBundleClasspath) throws IOException { return findEntries(Collections.singletonList(bundle), path, pattern, recurse, useBundleClasspath); } /** * This method uses {@link BundleWiring#findEntries} that doesn't involve classloaders so we can get resources * from fixed path. This way we can find multiple resources with the same path (when for example a bundle has * attached fragment, which has the same entries). Normally {@link BundleWiring#findEntries} doesn't check JARs * listed on {@code Bundle-ClassPath} (because it doesn't work at classloader level), however we can explicitly * tell it to do so. * * @param bundles * @param path * @param pattern * @param recurse * @param useBundleClasspath additionally search the JARs on Bundle-ClassPath * @return */ public static List<URL> findEntries(Iterable<Bundle> bundles, String path, String pattern, boolean recurse, boolean useBundleClasspath) throws IOException { List<URL> resources = new LinkedList<>(); if (pattern != null) { while (pattern.startsWith("/")) { pattern = pattern.substring(1); } } else { pattern = "*"; } for (Bundle bundle : bundles) { int options = recurse ? BundleWiring.FINDENTRIES_RECURSE : 0; BundleWiring wiring = bundle.adapt(BundleWiring.class); if (wiring != null) { List<URL> entries = wiring.findEntries(normalizeBase(path, false), pattern, options); resources.addAll(entries); if (useBundleClasspath) { URL[] jars = getClassPathURLs(bundle); resources.addAll(findEntries(bundle, jars, normalizeBase(path, true), pattern, recurse)); } } } return resources; } /** * Normalizes the path as <em>base</em>, which means changing "/" to empty string, changing non-empty path * to a pat that doesn't start with slash and where we can ask for trailing slash if needed. * @param path * @param ensureTrailingSlash should non-empty base path end with slash? * @return */ private static String normalizeBase(String path, boolean ensureTrailingSlash) { String base = path == null ? "" : path; while (base.startsWith("/")) { base = base.substring(1); } if (ensureTrailingSlash && !"".equals(base) && !base.endsWith("/")) { base += "/"; } return base; } /** * <p>This method matches {@link Bundle#findEntries(String, String, boolean)} but should be used when we don't * have access to any {@link Bundle}. It is used as a fallback in some resource-finding methods when * {@link org.osgi.framework.FrameworkUtil#getBundle(Class)} doesn't return anything (which may be a case in * unit tests).</p> * * <p>This method is inspired by Spring's * {@code org.springframework.core.io.support.PathMatchingResourcePatternResolver#doFindAllClassPathResources()} * where the most important problem of {@code ""} resource base was cleverly solved. Though we won't traverse * up the classloader parents and we won't check {@link ClassLoader#getSystemResources(String)}.</p> * * <p>Spring's {@code org.springframework.core.io.support.PathMatchingResourcePatternResolver#getResources()} * allows passing argument like {@code classpath*:/META-INF/** /*.tld} (ANT-style), however * {@code org.springframework.util.AntPathMatcher#doMatch()} is a bit complicated and very different from * {@link Bundle#findEntries(String, String, boolean)}, so we'll just test the entry for:<ul> * <li>begins with {@code path}</li> * <li>ends (or matches) {@code pattern}, where the patterns is simple glob ({@code *} and {@code ?} * supported).</li> * <li>{@code /META-INF/tlds/my.tld} should NOT match when {@code path=/META-INF/tlds} and * {@code pattern=tlds/*.tld}</li> * </ul></p> * * @param loader * @param path never a pattern. Should indicate the <em>base</em> used for relative path searching and * is always treated as base <em>directory</em> * @param pattern file pattern (only for matching last path segment == no slashes) to match. If this pattern * is {@code null}, we assume {@code *} which means <em>directory listing in the base path</em> * @param recurse whether we should look at any depth or only within {@code path} * @return */ public static List<URL> findEntries(ClassLoader loader, String path, String pattern, boolean recurse) throws IOException { if (pattern == null) { pattern = "*"; } while (pattern.startsWith("/")) { pattern = pattern.substring(1); } String base = normalizeBase(path, true); List<URL> roots = new LinkedList<>(); if ("".equals(base)) { // can't call cl.getResources(base), we have to find the roots just as in // org.springframework.core.io.support.PathMatchingResourcePatternResolver.doFindAllClassPathResources() // but only in current loader // sun.misc.URLClassPath.loaders may contain two (by default) kinds of loaders: // - sun.misc.URLClassPath.FileLoader // - sun.misc.URLClassPath.JarLoader // and simply in JarLoader, java.util.jar.JarFile.getJarEntry("") doesn't return anything, while // in FileLoader we get sun.misc.URLClassPath.Loader.getBaseURL() as the URL for "". if (loader instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) loader).getURLs(); if (urls.length == 1) { // let's handle surefire here if (urls[0].toExternalForm().endsWith("jar")) { urls = jarToItsClassPath(urls[0]); } } for (URL entry : urls) { if ("jar".equals(entry.getProtocol())) { roots.add(entry); } else { if (entry.getPath().endsWith(".jar")) { // don't bother with ZIPs, WARs, ... roots.add(new URL("jar:" + entry.toExternalForm() + "!/")); } else if ("file".equals(entry.getProtocol())) { // this may be file:/path/to/maven/project/test-classes/ for example File dir = new File(URI.create(entry.toExternalForm())); if (dir.isDirectory()) { roots.add(dir.toURI().toURL()); } } } } } } else { // let's rely only on java.lang.ClassLoader.getResources() Enumeration<URL> e = loader.getResources(base); while (e.hasMoreElements()) { roots.add(e.nextElement()); } } List<URL> resources = new LinkedList<>(); scanRoots(null, roots, pattern, recurse, resources); return resources; } /** * Used in tests, when there's only surefire on the classpath * @param url * @return */ public static URL[] jarToItsClassPath(URL url) throws IOException { URL[] urls = new URL[] { url }; URLConnection con = new URL("jar:" + urls[0].toExternalForm() + "!/").openConnection(); if (con instanceof JarURLConnection) { String cp = ((JarURLConnection) con).getManifest().getMainAttributes().getValue("Class-Path"); if (cp != null) { String[] entries = cp.split(" "); urls = new URL[entries.length]; int pos = 0; for (String e : entries) { urls[pos++] = new URL(e); } } } return urls; } /** * Third {@code findEntries()} method - this one starts with an array of roots (which are for example * JARs from {@code Bundle-ClassPath}, but may be other "roots". * @param bundle the bundle from where the roots come from. It's needed if extracting a <em>directory</em> entry * from a bundle * @param roots URLs that should end with "/" (jar: URLs should end with "!/") * @param path * @param pattern * @param recurse * @return * @throws IOException */ public static List<URL> findEntries(Bundle bundle, URL[] roots, String path, String pattern, boolean recurse) throws IOException { List<URL> resources = new LinkedList<>(); while (pattern.startsWith("/")) { pattern = pattern.substring(1); } // change roots into roots + the base path List<URL> newRoots = new LinkedList<>(); String base = normalizeBase(path, true); for (URL root : roots) { newRoots.add(new URL(root, base)); } scanRoots(bundle, newRoots, pattern, recurse, resources); return resources; } private static void scanRoots(Bundle bundle, List<URL> roots, String pattern, boolean recurse, List<URL> resources) { Pattern p = Pattern.compile(pattern.replaceAll("\\?", ".").replaceAll("\\*", ".*")); for (URL root : roots) { String protocol = root.getProtocol(); if ("jar".equals(protocol) && !jarClassPathEntryExists(root)) { continue; } if ("jar".equals(protocol)) { scanJar(root, p, recurse, resources); } else if ("file".equals(protocol)) { // assume it exists, otherwise it shouldn't be on roots list scanDirectory(new File(URI.create(root.toExternalForm())), p, recurse, resources); } else if (bundle != null && ("bundle".equals(protocol) || "bundleresource".equals(protocol) || "bundleentry".equals(protocol))) { scanBundle(bundle, root, pattern, recurse, resources); } } } /** * Similar to Spring's {@code PathMatchingResourcePatternResolver#doFindPathMatchingJarResources()} * @param root * @param pattern * @param recurse * @param result */ private static void scanJar(URL root, Pattern pattern, boolean recurse, Collection<URL> result) { // root can be "jar:<location>!/" or "jar:<location>!/some/base" try { URLConnection con = root.openConnection(); JarFile jar = null; // this should never start with "/" String rootEntryPath = null; boolean closeJar = false; if (con instanceof JarURLConnection) { // should be the case in most of the times JarURLConnection jarCon = (JarURLConnection) con; jar = jarCon.getJarFile(); JarEntry jarEntry = jarCon.getJarEntry(); rootEntryPath = (jarEntry != null ? jarEntry.getName() : ""); closeJar = !jarCon.getUseCaches(); } else { String location = root.getFile(); int separator = location.indexOf("!/"); if (separator != -1) { jar = new JarFile(location.substring(0, separator)); rootEntryPath = location.substring(separator + 2); } else { jar = new JarFile(location); rootEntryPath = ""; } closeJar = true; } // actual scanning if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) { // we need the root to be a directory entry, unless it's the root rootEntryPath += "/"; } for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements(); ) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); if (entryPath.startsWith(rootEntryPath)) { String relativePath = entryPath.substring(rootEntryPath.length()); if (relativePath.startsWith("/")) { relativePath = relativePath.substring(1); } if (matches(relativePath, pattern, recurse)) { // org.springframework.core.io.UrlResource.createRelativeURL() // # can appear in filenames, java.net.URL should not treat it as a fragment relativePath = relativePath.replaceAll("#", "%23"); result.add(new URL(root, relativePath)); } } } } catch (IOException e) { LOG.warn(e.getMessage(), e); } } /** * Scan a bundle (using OSGi-runtime-specific protocol handler) * @param bundle * @param root * @param pattern * @param recurse * @param result */ private static void scanBundle(Bundle bundle, URL root, String pattern, boolean recurse, Collection<URL> result) { Enumeration<URL> e = bundle.findEntries(root.getPath(), pattern, recurse); if (e == null) { return; } while (e.hasMoreElements()) { result.add(e.nextElement()); } } /** * Similar to Spring's {@code PathMatchingResourcePatternResolver#doFindPathMatchingFileResources()} * @param file * @param pattern * @param recurse */ private static void scanDirectory(File file, Pattern pattern, boolean recurse, final Collection<URL> result) { // org.springframework.core.io.support.PathMatchingResourcePatternResolver.doRetrieveMatchingFiles() if (!file.isDirectory()) { return; } try { final Path root = file.toPath(); Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String relativePath = root.relativize(file).toString(); if (matches(relativePath, pattern, recurse)) { result.add(new URL(root.toUri().toURL(), relativePath)); } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } /** * Returns {@code true} if passed path matches the pattern * @param path * @param pattern * @param recurse * @return */ private static boolean matches(String path, Pattern pattern, boolean recurse) { String nPath = path.replaceAll("\\\\", "/"); return recurse ? pattern.matcher(nPath).find() : pattern.matcher(nPath).matches(); } /** * Checks whether jar: location exists as proper <em>classpath element</em> * @param root * @return */ public static boolean jarClassPathEntryExists(URL root) { String protocol = root.getProtocol(); if (!"jar".equals(protocol)) { throw new IllegalArgumentException(root + " url not supported"); } try { URLConnection con = root.openConnection(); // as in org.springframework.core.io.AbstractFileResolvingResource.exists() if (con.getContentLengthLong() > 0L) { return true; } con.getInputStream().close(); return true; } catch (IOException e) { return false; } } }
35.926316
157
0.68294
2d68ca54357a690188e4ac9345604cf708e7a6cf
1,389
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.publish; import org.gradle.api.Incubating; import org.gradle.api.Named; /** * A publication is a description of a consumable representation of one or more artifacts, and possibly associated metadata. * * @since 1.3 */ public interface Publication extends Named { /** * Disables publication of a unique build identifier in Gradle Module Metadata. * <p> * The build identifier is published by default. * * @since 6.6 */ @Incubating void withoutBuildIdentifier(); /** * Enables publication of a unique build identifier in Gradle Module Metadata. * <p> * The build identifier is published by default. * * @since 6.6 */ @Incubating void withBuildIdentifier(); }
28.346939
124
0.697624
0c74c60ecd3ff4b20b6cba4555837e1366db6dee
1,645
package com.renyu.threadstudydemo; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchTest { private static final CountDownLatch countDownLatch = new CountDownLatch(3); private static final ExecutorService executorService = Executors.newFixedThreadPool(3); public static void main(String[] args) { executorService.submit(() -> { System.out.println("A去上厕所"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("A回来了"); countDownLatch.countDown(); }); executorService.submit(() -> { System.out.println("B去上厕所"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("B回来了"); countDownLatch.countDown(); }); executorService.submit(() -> { System.out.println("C去上厕所"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("C回来了"); countDownLatch.countDown(); }); System.out.println("等待所有人来"); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("所有人都来了"); executorService.shutdown(); } }
31.634615
91
0.550152
8da9cf20af5a013505342af8bf39c5a77af57ce3
1,053
package com.rposcro.jwavez.core.commands.supported; import com.rposcro.jwavez.core.commands.types.SwitchMultiLevelCommandType; import com.rposcro.jwavez.core.commands.supported.switchmultilevel.SwitchMultilevelReport; import com.rposcro.jwavez.core.classes.CommandClass; import com.rposcro.jwavez.core.model.NodeId; import com.rposcro.jwavez.core.utils.ImmutableBuffer; import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; @SupportedCommandResolver(commandClass = CommandClass.CMD_CLASS_SWITCH_MULTILEVEL) public class SwitchMultilevelCommandResolver extends AbstractCommandResolver<SwitchMultiLevelCommandType> { private static Map<SwitchMultiLevelCommandType, BiFunction<ImmutableBuffer, NodeId, ZWaveSupportedCommand>> suppliersPerCommandType; static { suppliersPerCommandType = new HashMap<>(); suppliersPerCommandType.put(SwitchMultiLevelCommandType.SWITCH_MULTILEVEL_REPORT, SwitchMultilevelReport::new); } public SwitchMultilevelCommandResolver() { super(suppliersPerCommandType); } }
39
134
0.842355
b9279535cb4962fafe1d3d1bcbfd212c7cafe08c
3,017
// // Decompiled by Procyon v0.5.36 // package org.codehaus.groovy.runtime; import java.util.ArrayList; import java.util.Collections; import java.util.List; public abstract class MethodKey { private int hash; private String name; private Class sender; private boolean isCallToSuper; public MethodKey(final Class sender, final String name, final boolean isCallToSuper) { this.sender = sender; this.name = name; this.isCallToSuper = isCallToSuper; } public MethodKey createCopy() { final int size = this.getParameterCount(); final Class[] paramTypes = new Class[size]; for (int i = 0; i < size; ++i) { paramTypes[i] = this.getParameterType(i); } return new DefaultMethodKey(this.sender, this.name, paramTypes, this.isCallToSuper); } @Override public boolean equals(final Object that) { return this == that || (that instanceof MethodKey && this.equals((MethodKey)that)); } public boolean equals(final MethodKey that) { if (this.sender != that.sender) { return false; } if (this.isCallToSuper != that.isCallToSuper) { return false; } if (!this.name.equals(that.name)) { return false; } final int size; if ((size = this.getParameterCount()) != that.getParameterCount()) { return false; } for (int i = 0; i < size; ++i) { if (this.getParameterType(i) != that.getParameterType(i)) { return false; } } return true; } @Override public int hashCode() { if (this.hash == 0) { this.hash = this.createHashCode(); if (this.hash == 0) { this.hash = -889275714; } } return this.hash; } @Override public String toString() { return super.toString() + "[name:" + this.name + "; params:" + this.getParamterTypes(); } public String getName() { return this.name; } public List getParamterTypes() { final int size = this.getParameterCount(); if (size <= 0) { return Collections.EMPTY_LIST; } final List params = new ArrayList(size); for (int i = 0; i < size; ++i) { params.add(this.getParameterType(i)); } return params; } public abstract int getParameterCount(); public abstract Class getParameterType(final int p0); protected int createHashCode() { int answer = this.name.hashCode(); for (int size = this.getParameterCount(), i = 0; i < size; ++i) { answer *= 37; answer += 1 + this.getParameterType(i).hashCode(); } answer *= 37; answer += (this.isCallToSuper ? 1 : 0); answer *= 37; answer += 1 + this.sender.hashCode(); return answer; } }
27.678899
95
0.549221
17bb4aa701e7b8e334cb63a99702f538a383ede6
2,081
package mavliwala.nazmuddin.domain; import java.util.concurrent.TimeUnit; import mavliwala.nazmuddin.domain.executers.ExecutionThread; import mavliwala.nazmuddin.domain.executers.PostExecutionThread; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.functions.Action1; /** * Created by nazmuddinmavliwala on 12/03/17. */ public abstract class UseCase<T extends Repository> { protected final ExecutionThread executionThread; protected final PostExecutionThread postExecutionThread; protected final T repository; protected Subscription subscriber; public UseCase(ExecutionThread executionThread, PostExecutionThread postExecutionThread, T repository) { this.executionThread = executionThread; this.postExecutionThread = postExecutionThread; this.repository = repository; } protected <P>void execute(Observable<P> observable, Subscriber<P> subscriber) { this.subscriber = getScheduledObservable(observable) .subscribe(subscriber); } protected <P>void execute(Observable<P> observable, Action1<P> action1) { this.subscriber = getScheduledObservable(observable) .subscribe(action1); } protected <P> Observable<P> getScheduledObservable(Observable<P> observable) { return observable.subscribeOn(executionThread.getScheduler()) .observeOn(postExecutionThread.getScheduler()); } protected <T> Observable.Transformer<T, T> applySchedulers() { return new Observable.Transformer<T, T>() { @Override public Observable<T> call(Observable<T> observable) { return observable .delay(1000, TimeUnit.MILLISECONDS) .subscribeOn(executionThread.getScheduler()) .observeOn(postExecutionThread.getScheduler()); } }; } public void unsubscribe() { if (this.subscriber != null) this.subscriber.unsubscribe(); } }
31.059701
83
0.673715
e654bdcba393c2ae265f323e52c693a91be9b3dc
2,991
package com.naio.diagnostic.trames; import java.nio.ByteBuffer; import java.util.Date; import com.naio.diagnostic.utils.Config; public class GPSTrame extends Trame { private byte[] time = new byte[8]; private byte[] lat = new byte[8]; private byte[] lon = new byte[8]; private byte[] alt = new byte[8]; private byte unit; private byte numberOfSat; private byte quality; private byte[] groundSpeed = new byte[8]; private boolean instantiate; public GPSTrame(byte[] naio01, byte id, byte[] size, byte[] payload, byte[] checksum) { super(naio01, id, size, payload, checksum); } public GPSTrame(byte[] data) { super(data); if (data == null) { return; } instantiate = true; int offset = Config.LENGHT_FULL_HEADER; time = new byte[] { data[offset+7], data[offset+6], data[offset+5], data[offset+4], data[offset+3], data[offset+2], data[offset+1], data[offset] }; lat = new byte[] { data[offset+15], data[offset+14], data[offset+13], data[offset+12], data[offset+11], data[offset+10], data[offset+9], data[offset+8] }; lon = new byte[] { data[offset+23], data[offset+22], data[offset+21], data[offset+20], data[offset+19], data[offset+18], data[offset+17], data[offset+16] }; alt = new byte[] { data[offset+31], data[offset+30], data[offset+29], data[offset+28], data[offset+27], data[offset+26], data[offset+25], data[offset+24] }; unit = data[offset+32]; numberOfSat = data[offset+33]; quality = data[offset+34]; groundSpeed = new byte[] { data[offset+42], data[offset+41], data[offset+40], data[offset+39], data[offset+38], data[offset+37], data[offset+36], data[offset+35] }; } public String show() { if (instantiate) { Date date = new Date((long) ((ByteBuffer.wrap(time).getDouble(0)))); return "" + date.toString() + "___lat:" + ByteBuffer.wrap(lat).getDouble(0) + "___lon:" + ByteBuffer.wrap(lon).getDouble(0) + "__alt:" + ByteBuffer.wrap(alt).getDouble(0) + "__unit:" + unit + "___nbrSat:" + numberOfSat + "___quality:" + quality + "___groundSpeed:" + ByteBuffer.wrap(groundSpeed).getDouble(0); } return null; } /** * @return the time */ public byte[] getTime() { return time; } /** * @return the lat */ public double getLat() { return ByteBuffer.wrap(lat).getDouble(0); } /** * @return the lon */ public double getLon() { return ByteBuffer.wrap(lon).getDouble(0); } /** * @return the alt */ public double getAlt() { return ByteBuffer.wrap(alt).getDouble(0); } /** * @return the unit */ public byte getUnit() { return unit; } /** * @return the quality */ public byte getQuality() { return quality; } /** * @return the groundSpeed */ public double getGroundSpeed() { return ByteBuffer.wrap(groundSpeed).getDouble(0); } }
19.050955
71
0.605817
e8ab4aca406f76ad558539da2bad69157c53be72
632
package com.showka.service.query.u11.i; import java.util.List; import java.util.Optional; import com.showka.domain.u11.ShohinIdo; import com.showka.value.EigyoDate; public interface ShohinIdoUriageQuery { /** * 売上の最新の商品移動取得. * * @param uriageId * 売上ID * @return 商品移動 */ public Optional<ShohinIdo> getNewest(String uriageId); /** * 引数.日付の売上の商品移動取得. * * <pre> * 売上訂正の商品移動も取得する(あれば)。 * </pre> * * @param uriageId * 売上ID * @param date * 日付 * @return 商品移動 */ public List<ShohinIdo> get(String uriageId, EigyoDate date); }
18.057143
62
0.598101
06cf3ae8a659be513ece33c274a6ff626b2758e9
4,735
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hdfs.FailoverClientHandler; import org.apache.hadoop.hdfs.server.namenode.CheckpointSignature; import org.apache.hadoop.hdfs.server.protocol.BlocksWithLocations; import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol; import org.apache.hadoop.hdfs.server.protocol.RemoteEditLogManifest; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.protocol.LocatedBlocksWithMetaInfo; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.ipc.ProtocolSignature; import org.apache.hadoop.ipc.RPC.VersionIncompatible; /** * This class implements the NamenodeProtocol such that it can work correctly * across AvatarNode failovers. Currently we support this protocol only for * the use case of the Balancer. Rest of the API's are left for implementation * in future when we actually need them. */ public class FailoverNameNodeProtocol implements NamenodeProtocol { private NamenodeProtocol namenode; private final FailoverClientHandler failoverHandler; private final Log LOG = LogFactory.getLog(FailoverNameNodeProtocol.class); public FailoverNameNodeProtocol(NamenodeProtocol namenode, FailoverClientHandler failoverHandler) { this.namenode = namenode; this.failoverHandler = failoverHandler; } public NamenodeProtocol getNameNode() { return this.namenode; } public void setNameNode(NamenodeProtocol namenode) { this.namenode = namenode; } @Override public long getProtocolVersion(final String protocol, final long clientVersion) throws VersionIncompatible, IOException { return (failoverHandler.new ImmutableFSCaller<Long>() { @Override public Long call() throws IOException { return namenode.getProtocolVersion(protocol, clientVersion); } }).callFS(); } @Override public ProtocolSignature getProtocolSignature(final String protocol, final long clientVersion, final int clientMethodsHash) throws IOException { return (failoverHandler.new ImmutableFSCaller<ProtocolSignature>() { @Override public ProtocolSignature call() throws IOException { return namenode.getProtocolSignature(protocol, clientVersion, clientMethodsHash); } }).callFS(); } @Override public BlocksWithLocations getBlocks(final DatanodeInfo datanode, final long size) throws IOException { return (failoverHandler.new ImmutableFSCaller<BlocksWithLocations>() { @Override public BlocksWithLocations call() throws IOException { return namenode.getBlocks(datanode, size); } }).callFS(); } @Override public CheckpointSignature rollEditLog() throws IOException { throw new IOException("Operation not supported"); } @Override public void rollFsImage(CheckpointSignature newImageSignature) throws IOException { throw new IOException("Operation not supported"); } @Override public long[] getBlockLengths(final long[] blockIds) { throw new RuntimeException("Operation not supported"); } @Override public CheckpointSignature getCheckpointSignature() { throw new RuntimeException("Operation not supported"); } @Override public LocatedBlocksWithMetaInfo updateDatanodeInfo( LocatedBlocks locatedBlocks) throws IOException { throw new IOException("Operation not supported"); } @Override public long getTransactionID() throws IOException { // TODO Auto-generated method stub return 0; } @Override public RemoteEditLogManifest getEditLogManifest(long l) throws IOException { // TODO Auto-generated method stub return null; } @Override public int register() throws IOException { // TODO Auto-generated method stub return 0; } }
32.655172
81
0.757339
e00c4bcf24db31002707e8b0d78ef49488141e4d
11,178
package com.github.subho57.spotifyclone.ui; import android.app.Fragment; import android.graphics.Bitmap; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.github.subho57.spotifyclone.R; import com.github.subho57.spotifyclone.manager.ListManager; import com.github.subho57.spotifyclone.manager.SearchPager; import com.github.subho57.spotifyclone.model.SimplePlaylist; import com.github.subho57.spotifyclone.model.TopArtist; import com.github.subho57.spotifyclone.model.TopTrack; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import java.util.ArrayList; import java.util.List; /** * Created by subho57 */ public class HomeFragment extends Fragment { public static final String TAG = "Spotify HomeFragment"; private RecyclerView mMadeForYouRecyclerView; private RecyclerView mTopArtistRecyclerView; private RecyclerView mTopTrackRecyclerView; private HorizontalSimpleListAdapter simpleListAdapter; private HorizontalArtistAdapter artistAdapter; private HorizontalTrackAdapter trackAdapter; private SearchPager.onCompleteTopArtistListener artistListener; private SearchPager.onCompleteTopTrackListener trackListener; public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false); mMadeForYouRecyclerView = view.findViewById(R.id.made_for_you_RecyclerView); mTopArtistRecyclerView = view.findViewById(R.id.top_artist_RecyclerView); mTopTrackRecyclerView = view.findViewById(R.id.top_tracks_RecyclerView); LinearLayoutManager horizontal_home_layout = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); LinearLayoutManager horizontal_artist_layout = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); LinearLayoutManager horizontal_track_layout = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); mMadeForYouRecyclerView.setLayoutManager(horizontal_home_layout); mTopArtistRecyclerView.setLayoutManager(horizontal_artist_layout); mTopTrackRecyclerView.setLayoutManager(horizontal_track_layout); updateUI(); return view; } private void updateUI() { setMadeForYou(); setTopArtists(); setTopTracks(); } private void setMadeForYou() { ArrayList<SimplePlaylist> mlist = ListManager.getInstance().getSimplePlaylists(); if (mlist == null || mlist.isEmpty()) { Log.d(TAG, "List is empty"); return; } if (simpleListAdapter == null) simpleListAdapter = new HorizontalSimpleListAdapter(mlist.subList(0, 10)); mMadeForYouRecyclerView.setAdapter(simpleListAdapter); } private void setTopArtists() { List<TopArtist> artists = ListManager.getInstance().getTopArtists(); if (artists.size() == 0) { artistListener = new SearchPager.onCompleteTopArtistListener() { @Override public void onComplete() { Log.d(TAG, "onComplete!"); artistAdapter.notifyDataSetChanged(); setTopArtists(); } @Override public void onError(Throwable error) { } }; SearchPager.getInstance(getContext()).getMyTopArtist(artistListener); } if (artistAdapter == null) artistAdapter = new HorizontalArtistAdapter(artists); mTopArtistRecyclerView.setAdapter(artistAdapter); } private void setTopTracks() { List<TopTrack> tracks = ListManager.getInstance().getTopTracks(); if (tracks.size() == 0) { trackListener = new SearchPager.onCompleteTopTrackListener() { @Override public void onComplete() { trackAdapter.notifyDataSetChanged(); setTopTracks(); } @Override public void onError(Throwable error) { } }; SearchPager.getInstance(getContext()).getMyTopTracks(trackListener); } if (trackAdapter == null) trackAdapter = new HorizontalTrackAdapter(tracks); mTopTrackRecyclerView.setAdapter(trackAdapter); } private class HorizontalTrackHolder extends RecyclerView.ViewHolder { private ImageView album_image_field; private TextView album_name_view; private HorizontalTrackHolder(View itemView) { super(itemView); album_image_field = itemView.findViewById(R.id.track_image_field); album_name_view = itemView.findViewById(R.id.track_name); } private void bindTrack(final TopTrack track) { album_name_view.setText(track.getName()); Picasso.with(getContext()) .load(track.getImg_url()) .transform(new Transformation() { @Override public Bitmap transform(Bitmap source) { final Bitmap copy = source.copy(source.getConfig(), true); source.recycle(); return copy; } @Override public String key() { return track.getName(); } }) .into(album_image_field); } } private class HorizontalTrackAdapter extends RecyclerView.Adapter<HorizontalTrackHolder> { private List<TopTrack> tracks; private HorizontalTrackAdapter(List<TopTrack> list) { tracks = list; } @Override public HorizontalTrackHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.track_view, parent, false); return new HorizontalTrackHolder(view); } @Override public void onBindViewHolder(HorizontalTrackHolder holder, int position) { holder.bindTrack(tracks.get(position)); } @Override public int getItemCount() { return tracks.size(); } } private class HorizontalArtistHolder extends RecyclerView.ViewHolder { private TopArtist artist; private TextView artist_name_view; private ImageView artist_image_field; private HorizontalArtistHolder(View itemView) { super(itemView); artist_name_view = itemView.findViewById(R.id.artist_name); artist_image_field = itemView.findViewById(R.id.artist_image_field); } private void bindArtist(final TopArtist artist) { this.artist = artist; artist_name_view.setText(artist.getName()); Picasso.with(getContext()) .load(artist.getImg_url()) .transform(new Transformation() { @Override public Bitmap transform(Bitmap source) { final Bitmap copy = source.copy(source.getConfig(), true); source.recycle(); return copy; } @Override public String key() { return artist.getName(); } }) .into(artist_image_field); } } private class HorizontalArtistAdapter extends RecyclerView.Adapter<HorizontalArtistHolder> { private List<TopArtist> artists; private HorizontalArtistAdapter(List<TopArtist> list) { this.artists = list; } @Override public HorizontalArtistHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.artist_view, parent, false); return new HorizontalArtistHolder(view); } @Override public void onBindViewHolder(HorizontalArtistHolder holder, int position) { holder.bindArtist(artists.get(position)); } @Override public int getItemCount() { return artists.size(); } } private class HorizontalSimpleListHolder extends RecyclerView.ViewHolder { private ImageView imageView; private TextView titleView; private HorizontalSimpleListHolder(View itemView) { super(itemView); imageView = itemView.findViewById(R.id.playlist_album_image); titleView = itemView.findViewById(R.id.playlist_album_title); } private void bindItem(final SimplePlaylist simple) { titleView.setText(simple.getName()); Picasso.with(getContext()) .load(simple.getImg_url()) .transform(new Transformation() { @Override public Bitmap transform(Bitmap source) { final Bitmap copy = source.copy(source.getConfig(), true); source.recycle(); return copy; } @Override public String key() { return simple.getName(); } }) .into(imageView); } } private class HorizontalSimpleListAdapter extends RecyclerView.Adapter<HorizontalSimpleListHolder> { private List<SimplePlaylist> testList; private HorizontalSimpleListAdapter(List<SimplePlaylist> list) { testList = list; } @Override public HorizontalSimpleListHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.album_view, parent, false); return new HorizontalSimpleListHolder(view); } @Override public void onBindViewHolder(HorizontalSimpleListHolder holder, int position) { holder.bindItem(testList.get(position)); } @Override public int getItemCount() { return testList.size(); } } }
31.05
132
0.615137
8023cdd051501adad6c46ab94b1749566e0e41d0
24,004
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.kie.server.integrationtests.jbpm.cases; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.BeforeClass; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.runtime.process.ProcessInstance; import org.kie.server.api.model.ReleaseId; import org.kie.server.api.model.cases.CaseFile; import org.kie.server.api.model.cases.CaseInstance; import org.kie.server.api.model.cases.CaseStage; import org.kie.server.api.model.instance.TaskSummary; import org.kie.server.client.CaseServicesClient; import org.kie.server.integrationtests.jbpm.JbpmKieServerBaseIntegrationTest; import org.kie.server.integrationtests.shared.KieServerDeployer; import org.kie.server.integrationtests.shared.KieServerReflections; public class CaseServiceIntegrationTest extends JbpmKieServerBaseIntegrationTest { private static ReleaseId releaseId = new ReleaseId("org.kie.server.testing", "case-insurance", "1.0.0.Final"); private static final String CONTAINER_ID = "insurance"; private static final String PROPERTY_DAMAGE_REPORT_CLASS_NAME = "org.kie.server.testing.PropertyDamageReport"; private static final String CLAIM_REPORT_CLASS_NAME = "org.kie.server.testing.ClaimReport"; private static final String CLAIM_CASE_ID_PREFIX = "CAR_INS"; private static final String CLAIM_CASE_DEF_ID = "insurance-claims.CarInsuranceClaimCase"; private static final String CLAIM_CASE_DESRIPTION = "CarInsuranceClaimCase"; private static final String CASE_INSURED_ROLE = "insured"; private static final String CASE_INS_REP_ROLE = "insuranceRepresentative"; private static final String CASE_ASSESSOR_ROLE = "assessor"; private static final String CONTAINER_ALIAS = "ins"; private static final String CAR_PRODUCER_REPORT_PARAMETER = "carId"; private static final String CAR_PRODUCER_REPORT_OUTPUT = "carProducerReport"; private static final String NON_EXISTENT_STAGE_ID = "I don't exist stage"; private static final String NON_EXISTENT_CASE_ID = "I don't exist case"; private static final String BAD_CONTAINER_ID = "not-existing-container"; private static final String BAD_CASE_ID = "not-existing-case"; private static final String TWO_STAGES_CASE_P_ID = "CaseWithTwoStages"; private static final String ACCIDENT_TASK_NAME = "Provide accident information"; @BeforeClass public static void buildAndDeployArtifacts() { KieServerDeployer.buildAndDeployCommonMavenParent(); KieServerDeployer.buildAndDeployMavenProject(ClassLoader.class.getResource("/kjars-sources/case-insurance").getFile()); kieContainer = KieServices.Factory.get().newKieContainer(releaseId); createContainer(CONTAINER_ID, releaseId, CONTAINER_ALIAS); } @Override protected void addExtraCustomClasses(Map<String, Class<?>> extraClasses) throws Exception { extraClasses.put(CLAIM_REPORT_CLASS_NAME, Class.forName(CLAIM_REPORT_CLASS_NAME, true, kieContainer.getClassLoader())); extraClasses.put(PROPERTY_DAMAGE_REPORT_CLASS_NAME, Class.forName(PROPERTY_DAMAGE_REPORT_CLASS_NAME, true, kieContainer.getClassLoader())); } @Test public void testCreateCaseWithEmptyCaseFile() { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); Assertions.assertThat(caseId).isNotNull(); Assertions.assertThat(caseId).startsWith(CLAIM_CASE_ID_PREFIX); CaseInstance caseInstance = caseClient.getCaseInstance(CONTAINER_ID, caseId); assertCarInsuranceCaseInstance(caseInstance, caseId, USER_YODA); List<TaskSummary> tasks = taskClient.findTasksAssignedAsPotentialOwner(USER_YODA, 0, 10); Assertions.assertThat(tasks).hasSize(1); } @Test public void testCreateCaseWithEmptyCaseFileButWithRoleAssignments() { CaseFile caseFile = CaseFile.builder().addUserAssignments(CASE_INSURED_ROLE, USER_YODA) .addUserAssignments(CASE_INS_REP_ROLE, USER_JOHN) .build(); String caseId = caseClient.startCase(CONTAINER_ID, CLAIM_CASE_DEF_ID, caseFile); Assertions.assertThat(caseId).isNotNull(); Assertions.assertThat(caseId).startsWith(CLAIM_CASE_ID_PREFIX); CaseInstance caseInstance = caseClient.getCaseInstance(CONTAINER_ID, caseId); assertCarInsuranceCaseInstance(caseInstance, caseId, USER_YODA); List<TaskSummary> tasks = taskClient.findTasksAssignedAsPotentialOwner(USER_YODA, 0, 10); assertEquals(1, tasks.size()); TaskSummary task = tasks.get(0); Assertions.assertThat(task).isNotNull(); Assertions.assertThat(task.getName()).isEqualTo(ACCIDENT_TASK_NAME); Assertions.assertThat(task.getActualOwner()).isNull(); Assertions.assertThat(task.getStatus()).isEqualTo("Ready"); } @Test public void testCreateCaseWithCaseFile() { Map<String, Object> caseData = new HashMap<>(); caseData.put("car", "ford"); CaseFile caseFile = CaseFile.builder().addUserAssignments(CASE_INSURED_ROLE, USER_YODA) .addUserAssignments(CASE_INS_REP_ROLE, USER_JOHN) .data(caseData) .build(); String caseId = caseClient.startCase(CONTAINER_ID, CLAIM_CASE_DEF_ID, caseFile); Assertions.assertThat(caseId).isNotNull(); Assertions.assertThat(caseId).startsWith(CLAIM_CASE_ID_PREFIX); caseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId); Assertions.assertThat(caseData).isNotNull(); Assertions.assertThat(caseData).hasSize(1); Assertions.assertThat(caseData.get("car")).isEqualTo("ford"); caseClient.putCaseInstanceData(CONTAINER_ID, caseId, "car", "fiat"); Object carCaseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId, "car"); Assertions.assertThat(carCaseData).isNotNull(); Assertions.assertThat(carCaseData).isInstanceOf(String.class); Assertions.assertThat(carCaseData).isEqualTo("fiat"); List<TaskSummary> tasks = taskClient.findTasksAssignedAsPotentialOwner(USER_YODA, 0, 10); Assertions.assertThat(tasks).hasSize(1); TaskSummary task = tasks.get(0); Assertions.assertThat(task).isNotNull(); Assertions.assertThat(task.getName()).isEqualTo(ACCIDENT_TASK_NAME); Assertions.assertThat(task.getStatus()).isEqualTo("Ready"); Assertions.assertThat(task.getActualOwner()).isNull(); Map<String, Object> output = new HashMap<>(); Object claimReport = createInstance(CLAIM_REPORT_CLASS_NAME); KieServerReflections.setValue(claimReport, "name", "John Doe"); output.put("claimReport_", claimReport); taskClient.completeAutoProgress(CONTAINER_ID, task.getId(), USER_YODA, output); caseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId); Assertions.assertThat(caseData).isNotNull(); Assertions.assertThat(caseData).hasSize(2); Assertions.assertThat(caseData.get("car")).isEqualTo("fiat"); Object caseClaimReport = caseData.get("claimReport"); Assertions.assertThat(caseClaimReport).isNotNull(); Assertions.assertThat(caseClaimReport.getClass().getName()).isEqualTo(CLAIM_REPORT_CLASS_NAME); caseClient.removeCaseInstanceData(CONTAINER_ID, caseId, "claimReport"); caseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId); Assertions.assertThat(caseData).isNotNull(); Assertions.assertThat(caseData).hasSize(1); Assertions.assertThat(caseData.get("car")).isEqualTo("fiat"); Map<String, Object> data = new HashMap<>(); data.put("owner", "john"); data.put("report", caseClaimReport); caseClient.putCaseInstanceData(CONTAINER_ID, caseId, data); caseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId); Assertions.assertThat(caseData).isNotNull(); Assertions.assertThat(caseData).hasSize(3); Assertions.assertThat(caseData.get("car")).isEqualTo("fiat"); Assertions.assertThat(caseData.get("owner")).isEqualTo("john"); caseClaimReport = caseData.get("report"); Assertions.assertThat(caseClaimReport).isNotNull(); Assertions.assertThat(caseClaimReport.getClass().getName()).isEqualTo(CLAIM_REPORT_CLASS_NAME); caseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId, Arrays.asList("car", "owner")); Assertions.assertThat(caseData).isNotNull(); Assertions.assertThat(caseData).hasSize(2); Assertions.assertThat(caseData.get("car")).isEqualTo("fiat"); Assertions.assertThat(caseData.get("owner")).isEqualTo("john"); } @Test public void testCreateCaseWithEmptyCaseFileThenDestroyIt() { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); Assertions.assertThat(caseId).isNotNull(); Assertions.assertThat(caseId).startsWith(CLAIM_CASE_ID_PREFIX); CaseInstance caseInstance = caseClient.getCaseInstance(CONTAINER_ID, caseId); assertCarInsuranceCaseInstance(caseInstance, caseId, USER_YODA); List<TaskSummary> tasks = taskClient.findTasksAssignedAsPotentialOwner(USER_YODA, 0, 10); assertEquals(1, tasks.size()); caseClient.destroyCaseInstance(CONTAINER_ID, caseId); CaseInstance closed = caseClient.getCaseInstance(CONTAINER_ID, caseId); Assertions.assertThat(closed.getCaseStatus()).isEqualTo(3); } @Test public void testCreateCancelAndReopenCaseWithEmptyCaseFile() { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); Assertions.assertThat(caseId).isNotNull(); Assertions.assertThat(caseId).startsWith(CLAIM_CASE_ID_PREFIX); CaseInstance caseInstance = caseClient.getCaseInstance(CONTAINER_ID, caseId); assertCarInsuranceCaseInstance(caseInstance, caseId, USER_YODA); caseClient.cancelCaseInstance(CONTAINER_ID, caseId); CaseInstance closed = caseClient.getCaseInstance(CONTAINER_ID, caseId); Assertions.assertThat(closed.getCaseStatus()).isEqualTo(3); Map<String, Object> data = new HashMap<>(); data.put("additionalComment", "reopening the case"); caseClient.reopenCase(caseId, CONTAINER_ID, CLAIM_CASE_DEF_ID, data); caseInstance = caseClient.getCaseInstance(CONTAINER_ID, caseId); Assertions.assertThat(caseInstance).isNotNull(); Assertions.assertThat(caseInstance.getCaseId()).isEqualTo(caseId); Object additionalComment = caseClient.getCaseInstanceData(CONTAINER_ID, caseId, "additionalComment"); Assertions.assertThat(additionalComment).isNotNull(); Assertions.assertThat(additionalComment).isEqualTo("reopening the case"); } @Test public void testCreateCaseWithEmptyCaseFileWithContainerAlias() { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); Assertions.assertThat(caseId).isNotNull(); Assertions.assertThat(caseId).startsWith(CLAIM_CASE_ID_PREFIX); CaseInstance caseInstance = caseClient.getCaseInstance(CONTAINER_ALIAS, caseId); assertCarInsuranceCaseInstance(caseInstance, caseId, USER_YODA); List<TaskSummary> tasks = taskClient.findTasksAssignedAsPotentialOwner(USER_YODA, 0, 10); Assertions.assertThat(tasks).hasSize(1); } @Test public void testCancelCaseInstanceNotExistingContainer() { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); assertClientException(() -> caseClient.cancelCaseInstance(BAD_CONTAINER_ID, caseId), 404 , BAD_CONTAINER_ID); } @Test public void testCancelCaseInstanceNotExistingCase() { assertClientException(() -> caseClient.cancelCaseInstance(CONTAINER_ID, BAD_CASE_ID), 404 , BAD_CASE_ID); } @Test public void testDestroyCaseInstance() { Map<String, Object> caseData = new HashMap<>(); caseData.put("car", "ford"); CaseFile caseFile = CaseFile.builder() .data(caseData) .addUserAssignments(CASE_INSURED_ROLE, USER_YODA) .addUserAssignments(CASE_INS_REP_ROLE, USER_JOHN) .addUserAssignments(CASE_ASSESSOR_ROLE, USER_YODA) .build(); String caseId = caseClient.startCase(CONTAINER_ID, CLAIM_CASE_DEF_ID, caseFile); Assertions.assertThat(caseId).isNotNull(); CaseInstance caseInstance = caseClient.getCaseInstance(CONTAINER_ID, caseId); assertCarInsuranceCaseInstance(caseInstance, caseId, USER_YODA); caseClient.destroyCaseInstance(CONTAINER_ID, caseId); CaseInstance closed = caseClient.getCaseInstance(CONTAINER_ID, caseId); Assertions.assertThat(closed.getCaseStatus()).isEqualTo(3); // Should throw exception because destroyed case cannot be reopen. assertClientException(() -> caseClient.reopenCase(caseId, CONTAINER_ID, CLAIM_CASE_DEF_ID), 404 , caseId); } @Test public void testDestroyCaseInstanceNotExistingContainer() { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); assertClientException(() -> caseClient.destroyCaseInstance(BAD_CONTAINER_ID, caseId), 404 , BAD_CONTAINER_ID); } @Test public void testDestroyCaseInstanceNotExistingCase() { assertClientException(() -> caseClient.destroyCaseInstance(CONTAINER_ID, BAD_CASE_ID), 404 , BAD_CASE_ID); } @Test public void testAddDynamicWorkItemTask() { String carId = "Ford Mustang"; String producerReportResponse = carId + " was regularly maintained and checked."; String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); Map<String, Object> data = new HashMap<>(); data.put(CAR_PRODUCER_REPORT_PARAMETER, carId); caseClient.addDynamicTask(CONTAINER_ID, caseId, "ContactCarProducer", "Contact car producer", data); Map<String, Object> caseInstanceData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId); Assertions.assertThat(caseInstanceData).containsKey(CAR_PRODUCER_REPORT_OUTPUT); Assertions.assertThat(caseInstanceData.get(CAR_PRODUCER_REPORT_OUTPUT)).isEqualTo(producerReportResponse); } @Test public void testAddDynamicWorkItemTaskNotExistingContainer() { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); assertClientException( () -> caseClient.addDynamicTask(BAD_CONTAINER_ID, caseId, "ContactCarProducer", "Contact car producer", null), 404 , BAD_CONTAINER_ID); } @Test public void testAddDynamicWorkItemTaskNotExistingCase() { assertClientException( () -> caseClient.addDynamicTask(CONTAINER_ID, BAD_CASE_ID, "ContactCarProducer", "Contact car producer", null), 404 , BAD_CASE_ID); } @Test public void testAddDynamicTaskToNotExistingStage() throws Exception { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); Assertions.assertThat(caseId).isNotNull(); assertClientException( () -> caseClient.addDynamicTaskToStage(CONTAINER_ID, caseId, NON_EXISTENT_STAGE_ID, "ContactCarProducer", "Contact car producer", null), 404, NON_EXISTENT_STAGE_ID); } @Test public void testAddDynamicTaskToStageNotExistingCase() throws Exception { assertClientException( () -> caseClient.addDynamicTaskToStage(CONTAINER_ID, NON_EXISTENT_CASE_ID, "Stage One", "ContactCarProducer", "Contact car producer", null), 404, NON_EXISTENT_CASE_ID); } @Test public void testAddDynamicTaskToStageInvalidContainer() throws Exception { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); Assertions.assertThat(caseId).isNotNull(); List<CaseStage> caseStages = caseClient.getStages(CONTAINER_ID, caseId, false, 0, 100); Assertions.assertThat(caseStages).isNotNull(); Assertions.assertThat(caseStages).isNotEmpty(); CaseStage firstCaseStage = caseStages.iterator().next(); String firstStageId = firstCaseStage.getIdentifier(); assertClientException( () -> caseClient.addDynamicTaskToStage(BAD_CONTAINER_ID, caseId, firstStageId, "ContactCarProducer", "Contact car producer", null), 404, BAD_CONTAINER_ID); } @Test public void testCreateCloseAndReopenCaseWithEmptyCaseFile() { String caseId = startCarInsuranceClaimCase(USER_YODA, USER_JOHN, USER_YODA); Assertions.assertThat(caseId).isNotNull(); Assertions.assertThat(caseId).startsWith(CLAIM_CASE_ID_PREFIX); CaseInstance caseInstance = caseClient.getCaseInstance(CONTAINER_ID, caseId); assertCarInsuranceCaseInstance(caseInstance, caseId, USER_YODA); caseClient.closeCaseInstance(CONTAINER_ID, caseId, "work done at the moment"); CaseInstance closed = caseClient.getCaseInstance(CONTAINER_ID, caseId); Assertions.assertThat(closed.getCaseStatus()).isEqualTo(2); Assertions.assertThat(closed.getCompletionMessage()).isEqualTo("work done at the moment"); Map<String, Object> data = new HashMap<>(); data.put("additionalComment", "reopening the case"); caseClient.reopenCase(caseId, CONTAINER_ID, CLAIM_CASE_DEF_ID, data); caseInstance = caseClient.getCaseInstance(CONTAINER_ID, caseId); Assertions.assertThat(caseInstance).isNotNull(); Assertions.assertThat(caseInstance.getCaseId()).isEqualTo(caseId); Object additionalComment = caseClient.getCaseInstanceData(CONTAINER_ID, caseId, "additionalComment"); Assertions.assertThat(additionalComment).isNotNull(); Assertions.assertThat(additionalComment).isEqualTo("reopening the case"); } @Test public void testCreateCaseWithCaseFileWithRestrictions() { Map<String, Object> caseData = new HashMap<>(); caseData.put("car", "ford"); CaseFile caseFile = CaseFile.builder() .addUserAssignments(CASE_INSURED_ROLE, USER_YODA) .addUserAssignments(CASE_INS_REP_ROLE, USER_JOHN) .addDataAccessRestrictions("car", CASE_INSURED_ROLE) .data(caseData) .build(); String caseId = caseClient.startCase(CONTAINER_ID, CLAIM_CASE_DEF_ID, caseFile); Assertions.assertThat(caseId).isNotNull(); Assertions.assertThat(caseId).startsWith(CLAIM_CASE_ID_PREFIX); caseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId); Assertions.assertThat(caseData).isNotNull(); Assertions.assertThat(caseData).hasSize(1); Assertions.assertThat(caseData.get("car")).isEqualTo("ford"); // remove yoda from insured role to simulate lack of access caseClient.removeUserFromRole(CONTAINER_ID, caseId, CASE_INSURED_ROLE, USER_YODA); caseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId); Assertions.assertThat(caseData).isNotNull(); Assertions.assertThat(caseData).hasSize(0); // add back yoda to insured role caseClient.assignUserToRole(CONTAINER_ID, caseId, CASE_INSURED_ROLE, USER_YODA); List<String> restrictions = new ArrayList<>(); restrictions.add(CaseServicesClient.ACCESS_PUBLIC_GROUP); caseClient.putCaseInstanceData(CONTAINER_ID, caseId, "car", "fiat", restrictions); Object carCaseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId, "car"); Assertions.assertThat(carCaseData).isNotNull(); Assertions.assertThat(carCaseData).isInstanceOf(String.class); Assertions.assertThat(carCaseData).isEqualTo("fiat"); // remove yoda from insured role to simulate lack of access caseClient.removeUserFromRole(CONTAINER_ID, caseId, CASE_INSURED_ROLE, USER_YODA); // but it should have access to it as all now eligible to see it carCaseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId, "car"); Assertions.assertThat(carCaseData).isNotNull(); Assertions.assertThat(carCaseData).isInstanceOf(String.class); Assertions.assertThat(carCaseData).isEqualTo("fiat"); restrictions = new ArrayList<>(); restrictions.add(CASE_INSURED_ROLE); Map<String, Object> updates = new HashMap<>(); updates.put("car", "opel"); caseClient.putCaseInstanceData(CONTAINER_ID, caseId, updates, restrictions); caseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId); Assertions.assertThat(caseData).isNotNull(); Assertions.assertThat(caseData).hasSize(0); assertClientException(() -> caseClient.removeCaseInstanceData(CONTAINER_ID, caseId, "car"), 403, "does not have access to data item named car"); // add back yoda to insured role caseClient.assignUserToRole(CONTAINER_ID, caseId, CASE_INSURED_ROLE, USER_YODA); caseClient.removeCaseInstanceData(CONTAINER_ID, caseId, "car"); caseData = caseClient.getCaseInstanceData(CONTAINER_ID, caseId); Assertions.assertThat(caseData).isNotNull(); Assertions.assertThat(caseData).hasSize(0); } private void assertCarInsuranceCaseInstance(CaseInstance caseInstance, String caseId, String owner) { Assertions.assertThat(caseInstance).isNotNull(); Assertions.assertThat(caseInstance.getCaseId()).isEqualTo(caseId); Assertions.assertThat(caseInstance.getCaseDefinitionId()).isEqualTo(CLAIM_CASE_DEF_ID); Assertions.assertThat(caseInstance.getCaseDescription()).isEqualTo(CLAIM_CASE_DESRIPTION); Assertions.assertThat(caseInstance.getCaseOwner()).isEqualTo(owner); Assertions.assertThat(caseInstance.getCaseStatus().intValue()).isEqualTo(ProcessInstance.STATE_ACTIVE); Assertions.assertThat(caseInstance.getStartedAt()).isNotNull(); Assertions.assertThat(caseInstance.getCompletedAt()).isNull(); Assertions.assertThat(caseInstance.getCompletionMessage()).isEqualTo(""); Assertions.assertThat(caseInstance.getContainerId()).isEqualTo(CONTAINER_ID); } private String startCarInsuranceClaimCase(String insured, String insuranceRep, String assessor) { Map<String, Object> data = new HashMap<>(); data.put("s", "first case started"); CaseFile caseFile = CaseFile.builder() .addUserAssignments(CASE_INSURED_ROLE, insured) .addUserAssignments(CASE_INS_REP_ROLE, insuranceRep) .addUserAssignments(CASE_ASSESSOR_ROLE, assessor) .data(data) .build(); String caseId = caseClient.startCase(CONTAINER_ID, CLAIM_CASE_DEF_ID, caseFile); assertNotNull(caseId); return caseId; } }
46.97456
152
0.716422
d29d1491d6ffb86f825368bdacd31ceaba5bf60d
2,641
package imangazaliev.scripto.js; import java.lang.reflect.Method; import imangazaliev.scripto.Scripto; /** * Calls JavaScript functions from Java */ class JavaScriptFunction { private Scripto scripto; private final String proxyId; final String jsFunction; JavaScriptFunction(Scripto scripto, String jsVariableName, Method method, Object[] args, String proxyId) { this.scripto = scripto; this.proxyId = proxyId; this.jsFunction = buildJavaScriptFunctionCall(jsVariableName, method, args); } String getJsFunction() { return jsFunction; } /** * Constructs a string to JS-function * * @param method - JS-function name * @param args - JS-function arguments * @return JS-code of function call with arguments */ private String buildJavaScriptFunctionCall(String jsVariableName, Method method, Object[] args) { //если функция имеет callback убираем его из аргументов JavaScriptArguments arguments = new JavaScriptArguments(scripto, args); String functionTemplate = "%s(%s);"; String functionCall = String.format(functionTemplate, getFunctionName(method), arguments.getFormattedArguments()); //если аннотация есть на методе, то аннотацию на классе мы ее не учитываем jsVariableName = (method.isAnnotationPresent(JsVariableName.class)) ? getVariableName(method) : jsVariableName; //если аннотация есть на классе или методе, присоединяем имя переменной через точку functionCall = (jsVariableName != null) ? String.format("%s.%s", jsVariableName, functionCall) : functionCall; return functionCall; } private String getVariableName(Method method) { return method.getAnnotation(JsVariableName.class).value(); } private String getFunctionName(Method method) { return method.isAnnotationPresent(JsFunctionName.class) ? method.getAnnotation(JsFunctionName.class).value() : method.getName(); } /** * Forms JS-code to call a function and run it * * @param callId - unique identifier of call */ public void callJavaScriptFunction(String callId) { String jsCall = "javascript:" + "(function(){" + " try {" + " var response = " + jsFunction + proxyId + ".onCallbackResponse('" + callId + "', response);" + " } catch (err) {" + proxyId + ".onCallbackError('" + callId + "', err.message);" + " }" + "})();"; scripto.getWebView().loadUrl(jsCall); } }
35.689189
136
0.643317
e832a7a52fd6288953f2a58c5dd65c8ba636bcbb
22,422
package src.comitton.config; import src.comitton.common.DEF; import io.github.yuma2a.comittonac.R; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; public class SetImageActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { private ListPreference mViewRota; private ListPreference mFileSort; private ListPreference mIniScale; private ListPreference mQuality; private ListPreference mPageWay; private ListPreference mInitView; private ListPreference mAlgoMode; private ListPreference mZoomType; private ListPreference mScrlWay; private ListPreference mMgnCut; private ListPreference mEffect; private ListPreference mViewPt; private ListPreference mVolKey; private ListPreference mLastPage; private ListPreference mPageSel; private OperationPreference mTapPattern; private PageNumberPreference mPageNumber; private TimeAndBatteryPreference mTimeAndBattery; public static final int FileSortName[] = { R.string.fsort00 // ソートなし , R.string.fsort01 // ファイル名-昇順 , R.string.fsort02 }; // ファイル名-降順 public static final int ViewPtName[] = { R.string.posi00 // 右上 , R.string.posi01 // 左上 , R.string.posi02 // 右下 , R.string.posi03 // 左下 , R.string.posi04 }; // 左下 public static final int ScaleName[] = { R.string.selsize00 // 元のサイズで表示 , R.string.selsize01 // 幅に合わせて表示 , R.string.selsize02 // 高さに合わせて表示 , R.string.selsize03 // 全体を表示 , R.string.selsize04 // 画面全体で表示 , R.string.selsize05 // 画面全体で表示(見開き対応) , R.string.selsize06 // 幅に合わせて表示(見開き対応) , R.string.selsize07 }; // 全体を表示(見開き対応) public static final int PageWayName[] = { R.string.pgway00 // 右から左 , R.string.pgway01 }; // 左から右 public static final int ViewName[] = { R.string.selview00 // そのまま表示 , R.string.selview01 // 見開き表示 , R.string.selview02 // 単ページ表示 , R.string.selview04 }; // 単ページ/見開き public static final int RotateName[] = { R.string.rota00 // 回転あり , R.string.rota01 // 縦固定 , R.string.rota02 // 横固定 , R.string.rota03 }; // 縦固定(90°回転) public static final int LoupeName[] = { R.string.loupe00 // 原寸x1.0 , R.string.loupe01 // 原寸x2.0 , R.string.loupe02 // 原寸x3.0 , R.string.loupe03 // 表示x1.5 , R.string.loupe04 // 表示x2.0 , R.string.loupe05 // 表示x2.5 , R.string.loupe06 }; // 表示x3.0 public static final int AlgoModeName[] = { R.string.selalgo00 // 最近傍補間 , R.string.selalgo01 // 双一次補間 , R.string.selalgo02 // 双一次補間(2Step) , R.string.selalgo03 // 双三次補間 , R.string.selalgo04 }; // 双三次補間(2Step) // , R.string.selalgo05 }; // Lanczos3 public static final int ImgRotaName[] = { R.string.selrota00 // 回転無しで表示 , R.string.selrota01 // 90°回転して表示 , R.string.selrota02 // 180°回転して表示 , R.string.selrota03 }; // 270°回転して表示 public static final int VolKeyName[] = { R.string.volkey00 // 使用しない , R.string.volkey01 // VolUp:前/Down:次 , R.string.volkey02 }; // VolUp:次/Down:前 public static final int ScrlWayName[] = { R.string.scrlway00 // 横→縦 , R.string.scrlway01 }; // 縦→横 public static final int MgnCutName[] = { R.string.mgncut00 // なし , R.string.mgncut01 // 弱 , R.string.mgncut02 // 中 , R.string.mgncut03 // 強 , R.string.mgncut04 // 最強 , R.string.mgncut05 }; // 縦横比無視 public static final int EffectName[] = { R.string.effect00 // なし , R.string.effect01 // フリップ , R.string.effect02 // フェードイン , R.string.effect03 }; // スクロール public static final int QualityName[] = { R.string.quality00 // 速度優先 , R.string.quality01 }; // 画質優先 public static final int PnumFormatName[] = { R.string.pnumformat00 // page / total , R.string.pnumformat01 }; // page1-2 / total public static final int PnumPosName[] = { R.string.pnumpos00 // 左上 , R.string.pnumpos01 // 中央上 , R.string.pnumpos02 // 右上 , R.string.pnumpos03 // 左下 , R.string.pnumpos04 // 中央下 , R.string.pnumpos05 }; // 右下 public static final int PnumColorName[] = { R.string.pnumcolor00 // 白 , R.string.pnumcolor01 }; // 黒 public static final int TimeFormatName[] = { R.string.timeformat00 // 24:00 , R.string.timeformat01 // 24:00 [100%] , R.string.timeformat02 // 24:00 [100%] [AC] , R.string.timeformat03 // 24:00 , R.string.timeformat04 // 24:00 [100%] , R.string.timeformat05 }; // 24:00 [100%] [AC] Resources mResources; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.image); mViewRota = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_VIEWROTA); mFileSort = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_FILESORT); mIniScale = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_INISCALE); mPageWay = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_PAGEWAY); mInitView = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_INITVIEW); mZoomType = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_ZOOMTYPE); mAlgoMode = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_ALGOMODE); mScrlWay = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_SCRLWAY); mMgnCut = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_MARGINCUT); mEffect = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_EFFECTLIST); mTapPattern = (OperationPreference)getPreferenceScreen().findPreference(DEF.KEY_TAPPATTERN); mPageNumber = (PageNumberPreference)getPreferenceScreen().findPreference(DEF.KEY_PAGENUMBER); mTimeAndBattery = (TimeAndBatteryPreference) getPreferenceScreen().findPreference(DEF.KEY_TIMEANDBATTERY); mViewPt = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_VIEWPT); mVolKey = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_VOLKEY); mQuality = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_QUALITY); mLastPage = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_LASTPAGE); mPageSel = (ListPreference)getPreferenceScreen().findPreference(DEF.KEY_PAGESELECT); mResources = getResources(); // 項目選択 PreferenceScreen onlineHelp = (PreferenceScreen) findPreference(DEF.KEY_IMAGEHELP); onlineHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { // Activityの遷移 Resources res = getResources(); String url = res.getString(R.string.url_image); // 設定画面 Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; } }); } @Override protected void onResume() { super.onResume(); SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences(); sharedPreferences.registerOnSharedPreferenceChangeListener(this); mViewRota.setSummary(getViewRotaSummary(sharedPreferences)); // イメージ画面の回転制御 mFileSort.setSummary(getFileSortSummary(sharedPreferences)); // 書庫内ファイルソート mIniScale.setSummary(getIniScaleSummary(sharedPreferences)); // 初期拡大モード mPageWay.setSummary(getPageWaySummary(sharedPreferences)); // ページめくり方向 mInitView.setSummary(getInitViewSummary(sharedPreferences)); // 表示モード mZoomType.setSummary(getZoomTypeSummary(sharedPreferences)); // ルーペ拡大率 mAlgoMode.setSummary(getAlgoModeSummary(sharedPreferences)); // 補間方式 mScrlWay.setSummary(getScrlWaySummary(sharedPreferences)); // スクロール方向 mMgnCut.setSummary(getMgnCutSummary(sharedPreferences)); // 余白削除 mEffect.setSummary(getEffectSummary(sharedPreferences)); // エフェクト mQuality.setSummary(getQualitySummary(sharedPreferences)); // 画質と速度 mTapPattern.setSummary(SetImageText.getTapPatternSummary(mResources, sharedPreferences)); // 操作パターン mPageNumber.setSummary(getPageNumberSummary(sharedPreferences)); // ページ表示 mTimeAndBattery.setSummary(getTimeSummary(sharedPreferences)); // 時刻と充電表示 mViewPt.setSummary(SetImageText.getViewPtSummary(mResources, sharedPreferences)); // イメージ画面の回転制御 mVolKey.setSummary(SetImageText.getVolKeySummary(mResources, sharedPreferences)); // Volキー動作 mLastPage.setSummary(SetImageText.getLastPageSummary(mResources, sharedPreferences)); // 最終ページでの確認 mPageSel.setSummary(SetImageText.getPageSelectSummary(mResources, sharedPreferences)); // ページ選択方法 } @Override protected void onPause() { super.onPause(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if(key.equals(DEF.KEY_VIEWROTA)){ // mViewRota.setSummary(getViewRotaSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_FILESORT)){ // mFileSort.setSummary(getFileSortSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_INISCALE)){ // mIniScale.setSummary(getIniScaleSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_PAGEWAY)){ // mPageWay.setSummary(getPageWaySummary(sharedPreferences)); } else if(key.equals(DEF.KEY_INITVIEW)){ // mInitView.setSummary(getInitViewSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_ZOOMTYPE)){ // mZoomType.setSummary(getZoomTypeSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_ALGOMODE)){ // mAlgoMode.setSummary(getAlgoModeSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_SCRLWAY)){ // mScrlWay.setSummary(getScrlWaySummary(sharedPreferences)); } else if(key.equals(DEF.KEY_MARGINCUT)){ // mMgnCut.setSummary(getMgnCutSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_EFFECTLIST)){ // mEffect.setSummary(getEffectSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_QUALITY)){ // mQuality.setSummary(getQualitySummary(sharedPreferences)); } else if(key.equals(DEF.KEY_TAPPATTERN) || key.equals(DEF.KEY_TAPRATE)){ // mTapPattern.setSummary(SetImageText.getTapPatternSummary(mResources, sharedPreferences)); } else if(key.equals(DEF.KEY_PNUMDISP) || key.equals(DEF.KEY_PNUMFORMAT) || key.equals(DEF.KEY_PNUMPOS) || key.equals(DEF.KEY_PNUMSIZE) || key.equals(DEF.KEY_PNUMCOLOR)){ // mPageNumber.setSummary(getPageNumberSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_TIMEDISP) || key.equals(DEF.KEY_TIMEFORMAT) || key.equals(DEF.KEY_TIMEPOS) || key.equals(DEF.KEY_TIMESIZE) || key.equals(DEF.KEY_TIMECOLOR)){ // mTimeAndBattery.setSummary(getTimeSummary(sharedPreferences)); } else if(key.equals(DEF.KEY_VIEWPT)){ // mViewPt.setSummary(SetImageText.getViewPtSummary(mResources, sharedPreferences)); } else if(key.equals(DEF.KEY_VOLKEY)){ // mVolKey.setSummary(SetImageText.getVolKeySummary(mResources, sharedPreferences)); } else if(key.equals(DEF.KEY_LASTPAGE)){ // mLastPage.setSummary(SetImageText.getLastPageSummary(mResources, sharedPreferences)); } else if(key.equals(DEF.KEY_PAGESELECT)){ // mPageSel.setSummary(SetImageText.getPageSelectSummary(mResources, sharedPreferences)); } } // 設定の読込 public static int getViewRota(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_VIEWROTA, "0"); if( val < 0 || val > 3 ){ val = 0; } return val; } public static int getFileSort(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_FILESORT, "1"); if( val < 0 || val > 2 ){ val = 0; } return val; } public static int getIniScale(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_INISCALE, "5"); if( val < 0 || val >= ScaleName.length ){ val = 0; } return val; } public static int getPageWay(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_PAGEWAY, "0"); if( val < 0 || val > 2 ){ val = 0; } return val; } public static int getInitView(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_INITVIEW, "1"); if(val < 0 || val >= ViewName.length){ val = 1; } return val; } public static int getZoomType(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_ZOOMTYPE, "4"); if (val < 0 || val >= LoupeName.length){ val = 0; } return val; } public static int getAlgoMode(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_ALGOMODE, "2"); if (val < 0 || val >= AlgoModeName.length){ val = 2; } return val; } public static int getScrlWay(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_SCRLWAY, "0"); if (val < 0 || val >= ScrlWayName.length){ val = 0; } return val; } public static int getEffect(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_EFFECTLIST, "1"); if( val < 0 || val > EffectName.length){ val = 1; } return val; } public static int getQuality(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_QUALITY, DEF.DEFAULT_QUALITY); if( val < 0 || val >= QualityName.length){ val = 1; } return val; } public static int getMgnCut(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_MARGINCUT, "0"); if (val < 0 || val >= MgnCutName.length){ val = 0; } return val; } public static int getBright(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_BRIGHT, "0"); return val; } public static int getGamma(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_GAMMA, "0"); return val; } public static int getBkLight(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_BKLIGHT, "11"); return val; } public static int getPnumFormat(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_PNUMFORMAT, DEF.DEFAULT_PNUMFORMAT); if( val < 0 || val >= PnumFormatName.length){ val = 1; } return val; } public static int getPnumPos(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_PNUMPOS, DEF.DEFAULT_PNUMPOS); if( val < 0 || val >= PnumPosName.length){ val = 5; } return val; } public static int getPnumSize(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_PNUMSIZE, DEF.DEFAULT_PNUMSIZE); return val; } public static boolean getPnumDisp(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_PNUMDISP, DEF.DEFAULT_PNUMDISP); return flag; } public static int getPnumColor(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_PNUMCOLOR, DEF.DEFAULT_PNUMCOLOR); if( val < 0 || val >= PnumColorName.length){ val = 1; } return val; } public static int getTimeFormat(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_TIMEFORMAT, DEF.DEFAULT_TIMEFORMAT); if( val < 0 || val >= TimeFormatName.length){ val = 1; } return val; } public static int getTimePos(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_TIMEPOS, DEF.DEFAULT_TIMEPOS); if( val < 0 || val >= PnumPosName.length){ val = 5; } return val; } public static int getTimeSize(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_TIMESIZE, DEF.DEFAULT_TIMESIZE); return val; } public static boolean getTimeDisp(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_TIMEDISP, DEF.DEFAULT_TIMEDISP); return flag; } public static int getTimeColor(SharedPreferences sharedPreferences){ int val = DEF.getInt(sharedPreferences, DEF.KEY_TIMECOLOR, DEF.DEFAULT_TIMECOLOR); if( val < 0 || val >= PnumColorName.length){ val = 1; } return val; } public static boolean getSharpen(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_SHARPEN, false); return flag; } public static boolean getGray(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_GRAY, false); return flag; } public static boolean getInvert(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_INVERT, false); return flag; } public static boolean getColoring(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_COLORING, false); return flag; } public static boolean getMoire(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_MOIRE, false); return flag; } public static boolean getTopSingle(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_TOPSINGLE, false); return flag; } public static boolean getNotice(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_NOTICE, true); return flag; } public static boolean getNoSleep(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_NOSLEEP, false); return flag; } public static boolean getFitDual(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_FITDUAL, true); return flag; } public static boolean getCenterMargin(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_CMARGIN, true); return flag; } public static boolean getCenterShadow(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_CSHADOW, false); return flag; } public static boolean getNoExpand(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_NOEXPAND, true); return flag; } public static boolean getScrlNext(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_SCRLNEXT, false); return flag; } // public static boolean getEffect(SharedPreferences sharedPreferences){ // boolean flag; // flag = DEF.getBoolean(sharedPreferences, DEF.KEY_EFFECT, true); // return flag; // } public static boolean getDelShare(SharedPreferences sharedPreferences){ boolean flag; flag = DEF.getBoolean(sharedPreferences, DEF.KEY_DELSHARE, true); return flag; } // 設定の読込(定義変更中) private String getViewRotaSummary(SharedPreferences sharedPreferences){ int val = getViewRota(sharedPreferences); Resources res = getResources(); return res.getString(RotateName[val]); } private String getFileSortSummary(SharedPreferences sharedPreferences){ int val = getFileSort(sharedPreferences); Resources res = getResources(); return res.getString(FileSortName[val]); } private String getIniScaleSummary(SharedPreferences sharedPreferences){ int val = getIniScale(sharedPreferences); Resources res = getResources(); return res.getString(ScaleName[val]); } private String getPageWaySummary(SharedPreferences sharedPreferences){ int val = getPageWay(sharedPreferences); Resources res = getResources(); return res.getString(PageWayName[val]); } private String getInitViewSummary(SharedPreferences sharedPreferences){ int val = getInitView(sharedPreferences); Resources res = getResources(); return res.getString(ViewName[val]); } private String getZoomTypeSummary(SharedPreferences sharedPreferences){ int val = getZoomType(sharedPreferences); Resources res = getResources(); return res.getString(LoupeName[val]); } private String getAlgoModeSummary(SharedPreferences sharedPreferences){ int val = getAlgoMode(sharedPreferences); Resources res = getResources(); return res.getString(AlgoModeName[val]); } private String getScrlWaySummary(SharedPreferences sharedPreferences){ int val = getScrlWay(sharedPreferences); Resources res = getResources(); return res.getString(ScrlWayName[val]); } private String getMgnCutSummary(SharedPreferences sharedPreferences){ int val = getMgnCut(sharedPreferences); Resources res = getResources(); return res.getString(MgnCutName[val]); } private String getEffectSummary(SharedPreferences sharedPreferences){ int val = getEffect(sharedPreferences); Resources res = getResources(); return res.getString(EffectName[val]); } private String getQualitySummary(SharedPreferences sharedPreferences){ int val = getQuality(sharedPreferences); Resources res = getResources(); return res.getString(QualityName[val]); } private String getPageNumberSummary(SharedPreferences sharedPreferences){ boolean disp = getPnumDisp(sharedPreferences); int format = getPnumFormat(sharedPreferences); int pos = getPnumPos(sharedPreferences); int size = getPnumSize(sharedPreferences); int color = getPnumColor(sharedPreferences); Resources res = getResources(); String summ; if (disp) { summ = res.getString(PnumFormatName[format]) + ", " + res.getString(PnumPosName[pos]) + ", " + DEF.getPnumSizeStr(size, res.getString(R.string.unitSumm1)) + ", " + res.getString(PnumColorName[color]); } else { summ = res.getString(R.string.pnumnodisp); } return summ; } private String getTimeSummary(SharedPreferences sharedPreferences){ boolean disp = getTimeDisp(sharedPreferences); int format = getTimeFormat(sharedPreferences); int pos = getTimePos(sharedPreferences); int size = getTimeSize(sharedPreferences); int color = getTimeColor(sharedPreferences); Resources res = getResources(); String summ; if (disp) { summ = res.getString(TimeFormatName[format]) + ", " + res.getString(PnumPosName[pos]) + ", " + DEF.getPnumSizeStr(size, res.getString(R.string.unitSumm1)) + ", " + res.getString(PnumColorName[color]); } else { summ = res.getString(R.string.pnumnodisp); } return summ; } }
33.119645
170
0.745562
8a2395c4637c5ec0f5e8003773d1d8b2dd3fd9d4
3,890
package com.recognition.intellst.service.impl; import com.recognition.intellst.api.DataToSent; import com.recognition.intellst.service.VideoService; import com.recognition.intellst.utils.OpenCVImageUtils; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.opencv.core.Mat; import org.opencv.videoio.VideoCapture; import org.opencv.videoio.Videoio; import org.springframework.stereotype.Service; import org.springframework.web.server.NotAcceptableStatusException; import java.io.IOException; import java.util.Objects; import static com.recognition.intellst.recognition.face.CollectData.saveImage; import static com.recognition.intellst.recognition.face.CollectData.uuid; import static com.recognition.intellst.recognition.face.FaceDisplay.detectAndDisplay; import static com.recognition.intellst.recognition.face.FaceDisplay.threadImage; import static com.recognition.intellst.recognition.face.RecognitionConstants.VIDEO_HEIGHT; import static com.recognition.intellst.recognition.face.RecognitionConstants.VIDEO_WIDTH; import static com.recognition.intellst.recognition.temperature.ImageTemperatureReader.readTemperature; import static com.recognition.intellst.recognition.temperature.ImageTemperatureReader.temperature; @Slf4j @Service public class VideoServiceImpl implements VideoService { private static VideoCapture videoCapture; private static void grabFrame() { Mat frame = new Mat(); if (videoCapture.isOpened()) { videoCapture.read(frame); try { if (!frame.empty()) { readTemperature((Objects.requireNonNull(OpenCVImageUtils.matToBufferedImage(frame)))); if (threadImage == null) { detectAndDisplay(frame); } else { if (threadImage.isAlive()) { saveImage(frame); } else { detectAndDisplay(frame); } } } } catch (IOException e) { e.printStackTrace(); } System.gc(); } DataToSent dataToSent = new DataToSent(); int label = 1; if (!uuid.equals(uuid)) { dataToSent.setTemperature(temperature); dataToSent.setUuid(uuid); dataToSent.setPhotoFilename("src/main/resources/training/" + uuid + "/" + ++label + "-" + uuid + "_" + "1" + ".png"); } } @SneakyThrows @Override public void startCamera(String videoURL, boolean activeCamera) { log.info("method = startCamera"); if (activeCamera && videoURL != null) { videoCapture = new VideoCapture(); videoCapture.open(videoURL, Videoio.CAP_ANY); videoCapture.set(Videoio.CAP_PROP_FRAME_WIDTH, VIDEO_WIDTH); videoCapture.set(Videoio.CAP_PROP_FRAME_HEIGHT, VIDEO_HEIGHT); videoCapture.set(Videoio.CAP_PROP_FPS, 30); log.info("VideoCapture is Active"); Mat frame = new Mat(); while (true) { if (videoCapture.isOpened()) { videoCapture.read(frame); if (!frame.empty()) { grabFrame(); } } } } else if (!activeCamera) { try { videoCapture.release(); log.info("Camera is stopped"); } catch (Exception e) { log.info("Camera is stopped error occurred, camera is already stopped"); e.getCause(); } } else { throw new NotAcceptableStatusException("Video URL is Empty or incorrect"); } } }
38.9
130
0.6
0fb31dc6b05a5d1fb389108e4012d8941b56d2b8
3,500
/* * BSD 2-Clause License * * Copyright (c) 2019, Suuirad * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package de.coreengine.rendering.renderable; import de.coreengine.rendering.model.Color; import de.coreengine.rendering.model.Material; import de.coreengine.rendering.renderable.light.PointLight; import de.coreengine.rendering.renderer.MasterRenderer; import de.coreengine.util.Configuration; import javax.vecmath.Vector3f; /** * Class that reprsents a moon for post processing and lighting calculation * * @author Darius Dinger */ public class Moon { private static final float DEFAULT_SIZE = Configuration.getValuef("MOON_DEFAULT_SIZE"); // Moon size private float size = DEFAULT_SIZE; // Moon texture private String texture = Material.TEXTURE_BLANK; // Moon light sources private PointLight pointLight = new PointLight(); /** * Creating new white moon and setting its attenuation to infinity */ public Moon() { pointLight.getAttenuation().set(0.0f, 0.0f); } /** * @return Size of the moon */ public final float getSize() { return size; } /** * @param size New sizeof the moon */ public final void setSize(float size) { this.size = size; } /** * @return TextureData of the moon */ public final String getTexture() { return texture; } /** * @param texture New texture of the moon */ public final void setTexture(String texture) { this.texture = texture; } /** * Adding lights of the moon to the masterrenderer */ public final void addLights() { MasterRenderer.renderPointLight(pointLight); } /** * @return Color of the moon */ public final Color getColor() { return pointLight.getColor(); } /** * @return Worldposition of the moon */ public final Vector3f getPosition() { return pointLight.getPosition(); } /** * Setting light intensity * * @param intensity New intensity of the light */ public final void setIntensity(float intensity) { pointLight.setIntensity(intensity); } }
29.166667
91
0.689429
d938c23942f137791ebe3feb59ab9e3480c6196e
11,474
/** * Licensed to JumpMind Inc under one or more contributor * license agreements. See the NOTICE file distributed * with this work for additional information regarding * copyright ownership. JumpMind Inc licenses this file * to you under the GNU General Public License, version 3.0 (GPLv3) * (the "License"); you may not use this file except in compliance * with the License. * * You should have received a copy of the GNU General Public License, * version 3.0 (GPLv3) along with this library; if not, see * <http://www.gnu.org/licenses/>. * * 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.jumpmind.symmetric; import static org.apache.commons.lang.StringUtils.isNotBlank; import java.io.File; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; /** * Launch the SymmetricDS engine as a stand alone client or server. */ public class SymmetricLauncher extends AbstractCommandLauncher { static final Logger log = LoggerFactory.getLogger(SymmetricLauncher.class); private static final String OPTION_PORT_SERVER = "port"; private static final String OPTION_HOST_SERVER = "host"; private static final String OPTION_HTTP_BASIC_AUTH_USER = "http-basic-auth-user"; private static final String OPTION_HTTP_BASIC_AUTH_PASSWORD = "http-basic-auth-password"; private static final String OPTION_SECURE_PORT_SERVER = "secure-port"; private static final String OPTION_MAX_IDLE_TIME = "max-idle-time"; private static final String OPTION_START_SERVER = "server"; private static final String OPTION_START_CLIENT = "client"; private static final String OPTION_START_SECURE_SERVER = "secure-server"; private static final String OPTION_START_MIXED_SERVER = "mixed-server"; private static final String OPTION_NO_NIO = "no-nio"; private static final String OPTION_NO_DIRECT_BUFFER = "no-directbuffer"; private static final String OPTION_JMX_DISABLE = "jmx-disable"; private static final String OPTION_JMX_PORT = "jmx-port"; private static final String OPTION_WINXP = "winxp"; public SymmetricLauncher(String app, String argSyntax, String messageKeyPrefix) { super(app, argSyntax, messageKeyPrefix); } public static void main(String... args) throws Exception { MDC.put("engineName", "startup"); new SymmetricLauncher("sym", "", "Launcher.Option.").execute(args); } @Override protected boolean printHelpIfNoOptionsAreProvided() { return false; } @Override protected boolean requiresPropertiesFile(CommandLine line) { return false; } @Override protected void printHelp(CommandLine cmd, Options options) { System.out.println(app + " version " + Version.version()); System.out.println("Launch the SymmetricDS engine as a standalone client or server.\n"); super.printHelp(cmd, options); } @Override protected void buildOptions(Options options) { super.buildOptions(options); buildCryptoOptions(options); addOption(options, "S", OPTION_START_SERVER, false); addOption(options, "C", OPTION_START_CLIENT, false); addOption(options, "T", OPTION_START_SECURE_SERVER, false); addOption(options, "U", OPTION_START_MIXED_SERVER, false); addOption(options, "H", OPTION_HOST_SERVER, true); addOption(options, "P", OPTION_PORT_SERVER, true); addOption(options, "Q", OPTION_SECURE_PORT_SERVER, true); addOption(options, "I", OPTION_MAX_IDLE_TIME, true); addOption(options, "nnio", OPTION_NO_NIO, false); addOption(options, "ndb", OPTION_NO_DIRECT_BUFFER, false); addOption(options, "hbau", OPTION_HTTP_BASIC_AUTH_USER, true); addOption(options, "hbap", OPTION_HTTP_BASIC_AUTH_PASSWORD, true); addOption(options, "JD", OPTION_JMX_DISABLE, false); addOption(options, "J", OPTION_JMX_PORT, true); addOption(options, OPTION_WINXP, OPTION_WINXP, false); } @Override protected boolean executeWithOptions(CommandLine line) throws Exception { String host = null; int httpPort = 0; int httpSecurePort = 0; int jmxPort = 0; String webDir = SymmetricWebServer.DEFAULT_WEBAPP_DIR; int maxIdleTime = SymmetricWebServer.DEFAULT_MAX_IDLE_TIME; boolean noNio = false; boolean noDirectBuffer = false; String httpBasicAuthUser = null; String httpBasicAuthPassword = null; configureCrypto(line); removeOldHeapDumps(); if (line.hasOption(OPTION_HTTP_BASIC_AUTH_USER) && line.hasOption(OPTION_HTTP_BASIC_AUTH_PASSWORD)) { httpBasicAuthUser = line.getOptionValue(OPTION_HTTP_BASIC_AUTH_USER); httpBasicAuthPassword = line.getOptionValue(OPTION_HTTP_BASIC_AUTH_PASSWORD); } if (line.hasOption(OPTION_HOST_SERVER)) { host = line.getOptionValue(OPTION_HOST_SERVER); } if (line.hasOption(OPTION_PORT_SERVER)) { httpPort = new Integer(line.getOptionValue(OPTION_PORT_SERVER)); } if (line.hasOption(OPTION_SECURE_PORT_SERVER)) { httpSecurePort = new Integer(line.getOptionValue(OPTION_SECURE_PORT_SERVER)); } if (line.hasOption(OPTION_MAX_IDLE_TIME)) { maxIdleTime = new Integer(line.getOptionValue(OPTION_MAX_IDLE_TIME)); } if (line.hasOption(OPTION_NO_NIO)) { noNio = true; } if (line.hasOption(OPTION_NO_DIRECT_BUFFER)) { noDirectBuffer = true; } boolean jmxDisabledFlag = line.hasOption(OPTION_JMX_DISABLE); if (!jmxDisabledFlag) { if (line.hasOption(OPTION_JMX_PORT)) { jmxPort = new Integer(line.getOptionValue(OPTION_JMX_PORT)); } else { if (line.hasOption(OPTION_START_SECURE_SERVER)) { if (httpSecurePort > 0) { jmxPort = httpSecurePort + 1; } } else { if (httpPort > 0) { jmxPort = httpPort + 1; } } } } if (line.hasOption(OPTION_WINXP)) { new Thread() { { this.setDaemon(true); this.start(); } @Override public void run() { log.info("Starting workaround thread to prevent system clock acceleration on Windows XP"); while (true) { try { Thread.sleep(Integer.MAX_VALUE); } catch (InterruptedException ex) { // ignored. } } } }; } if (line.hasOption(OPTION_START_CLIENT)) { getSymmetricEngine(false).start(); } else { SymmetricWebServer webServer = new SymmetricWebServer(chooseWebDir(line, webDir), maxIdleTime, propertiesFile != null ? propertiesFile.getCanonicalPath() : null, true, noNio, noDirectBuffer); if (isNotBlank(host)) { webServer.setHost(host); } webServer.setBasicAuthUsername(httpBasicAuthUser); webServer.setBasicAuthPassword(httpBasicAuthPassword); if (jmxDisabledFlag) { webServer.setJmxEnabled(false); } if (jmxPort > 0) { webServer.setJmxPort(jmxPort); } if (httpPort > 0) { webServer.setHttpPort(httpPort); } if (httpSecurePort > 0) { webServer.setHttpsPort(httpSecurePort); } if (line.hasOption(OPTION_START_MIXED_SERVER)) { webServer.setHttpEnabled(true); webServer.setHttpsEnabled(true); if (httpPort > 0) { webServer.setHttpPort(httpPort); } if (httpSecurePort > 0) { webServer.setHttpsPort(httpSecurePort); } } else if (line.hasOption(OPTION_START_SECURE_SERVER)) { webServer.setHttpEnabled(false); webServer.setHttpsEnabled(true); if (httpSecurePort > 0) { webServer.setHttpsPort(httpSecurePort); } } else if (line.hasOption(OPTION_START_SERVER)) { webServer.setHttpEnabled(true); webServer.setHttpsEnabled(false); } webServer.start(); } return true; } protected void removeOldHeapDumps() { String heapDumpPath = null; List<String> options = ManagementFactory.getRuntimeMXBean().getInputArguments(); for (String option : options) { if (option.startsWith("-XX:HeapDumpPath=")) { heapDumpPath = option.split("=")[1]; } } if (log.isDebugEnabled()) { log.debug("Heap dump path is " + (heapDumpPath == null ? null : new File(heapDumpPath).getAbsolutePath())); } if (heapDumpPath != null) { File directory = new File(heapDumpPath); if (!directory.exists()) { // Happens if whole tmp directory is removed. return; } Collection<File> files = FileUtils.listFiles(directory, new String[] { "hprof" }, false); List<File> recentFiles = new ArrayList<File>(); List<File> oldFiles = new ArrayList<File>(); for (File file : files) { if (file.lastModified() < (System.currentTimeMillis() - 604800000)) { oldFiles.add(file); } else { recentFiles.add(file); } } Collections.sort(recentFiles, new Comparator<File>() { @Override public int compare(File f1, File f2) { return f1.lastModified() > f2.lastModified() ? -1 : 1; } }); for (int i = 2; i < recentFiles.size(); i++) { oldFiles.add(recentFiles.get(i)); } for (File file : oldFiles) { log.info("Removing old heap dump " + file.getName()); file.delete(); } } } @SuppressWarnings("unused") protected String chooseWebDir(CommandLine line, String webDir) { return webDir; } }
36.310127
119
0.595607
a81ae9ecd75ff1941e703b5e939aef3fd3129e1c
83
package net.roxeez.advancement.trigger; public class Tick implements Trigger { }
13.833333
39
0.795181
589075cbc94ee0163a26e502488c268e30df82fd
9,143
/** * Copyright (c) 2018 John Christopher Allwein (johnnyapol) * * 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 me.johnnyapol.shane; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLServerSocketFactory; public class IRCServer implements Runnable { private static final Logger logger = Logger.getLogger("Shane"); private volatile int numClients = 0; private final String PASSWORD; private List<IRCClient> connectedClients = new CopyOnWriteArrayList<IRCClient>(); private IRCConnection ircServer; private int port = 6667; private boolean useSSL = false; private boolean isRunning = true; /** * Constructs a new IRCServer instance, which is where clients connect to be proxied into the server * @param port The port at which the bouncer should run on * @param _WORD The authentication password that new clients must provide * @param enableBouncerSSL */ public IRCServer(int port, String _WORD, boolean enableBouncerSSL) { this.port = port; this.PASSWORD = _WORD; this.useSSL = enableBouncerSSL; } /** * Called to set the particular IRCConnection instance that this bouncer is responsible for * @param s The IRCConnection instance, representing the server that this particular bouncer is proxy-ing to */ public void setIRCConnection(IRCConnection s) { this.ircServer = s; } /** * Represents an IRC client connection to the bouncer. Enforces authentication standards and proxys data server <-> client * @author john */ class IRCClient implements Runnable { private int clientId; private Socket connection; private BufferedReader reader = null; private BufferedWriter writer = null; private boolean isConnected = true; private boolean hasAuthenticated = false; private String nick = "default"; private int authAttempts = 0; public IRCClient(int clientId, Socket connection) throws IOException { this.clientId = clientId; this.connection = connection; this.reader = new BufferedReader(new InputStreamReader(this.connection.getInputStream())); this.writer = new BufferedWriter(new OutputStreamWriter(this.connection.getOutputStream())); } public int getID() { return this.clientId; } public Socket getConnection() { return this.connection; } public void sendMessage(String msg) throws IOException { this.writer.write(msg + "\r\n"); this.writer.flush(); } @Override public void run() { while (IRCServer.this.isRunning || this.isConnected) { String msg = null; try { Thread.sleep(100); while ((msg = reader.readLine()) != null) { // Check if the client is authenticated, if not, their actions are basically restricted to authenticating and setting their nick logger.info("[client#" + this.clientId + "] msg: " + msg); if (!hasAuthenticated) { if (msg.toLowerCase().contains("password") || (msg.toLowerCase().contains("msg") && msg.toLowerCase().contains("bouncer"))) { String[] split = msg.split(" "); // Password check for (String s : split) { if (s.equals(PASSWORD) || s.equals(":" + PASSWORD)) { this.hasAuthenticated = true; this.sendMessage(":irc.shane.net 002 " + nick + " Thanks for authenticating! You are now connected!"); IRCServer.this.connectedClients.add(this); IRCServer.logger.info("[ircserver] Client " + this.connection.getRemoteSocketAddress().toString() + " has authenticated succesfully, under nickname " + this.nick); IRCServer.this.ircServer.onClientConnect(this); break; } } if (!hasAuthenticated) { this.sendMessage(":irc.shane.net 372 " + nick + " Wrong password! Please try again!"); authAttempts++; if (authAttempts >= 3) { this.sendMessage(":irc.shane.net 372" + nick + " Too many auth attempts! Goodbye!"); IRCServer.logger.warning("[ircserver] Too many failed authentication attempts from: " + this.connection.getRemoteSocketAddress().toString() + ", disconnecting!"); this.connection.close(); return; } } continue; } // set the clients nick if (msg.contains("NICK")) { this.nick = msg.split(" ")[1]; } continue; } // check to avoid parts caused by clients being closed if (msg.startsWith("PART")) { // ignored continue; } if (msg.startsWith("QUIT")) { // terminate connection logger.info("[ircserver] Client #" + this.clientId + " is parting!"); IRCServer.this.connectedClients.remove(this); this.connection.close(); continue; } // proxy the client's request IRCServer.this.ircServer.sendMesssage(msg); } } catch (Exception e) { logger.log(Level.SEVERE, "[ircserver] Lost connection to client: " + this.connection.getRemoteSocketAddress().toString(), e); break; } } this.isConnected = false; // Cleanup try { this.connection.close(); } catch (Throwable t) { // ignored } } public boolean isConnected() { return this.isConnected; } public boolean hasAuthenticated() { return this.hasAuthenticated; } public String getNick() { return this.nick; } public void disconnect() { this.isConnected = false; } } @Override public void run() { ServerSocket socket; try { socket = (useSSL ? (SSLServerSocketFactory.getDefault().createServerSocket(port)) : new ServerSocket(this.port)) ; } catch (IOException e) { this.isRunning = false; logger.log(Level.SEVERE, "Failed to create ServerSocket instance, aborting launch.", e); return; } while (this.isRunning) { try { Thread.sleep(100); } catch (InterruptedException e1) { // ignored } try { Socket s = socket.accept(); // apply some socket options s.setTcpNoDelay(true); s.setKeepAlive(true); numClients++; logger.info("[ircserver] Got connection id " + numClients + " from " + s.getRemoteSocketAddress()); IRCClient client = new IRCClient(numClients, s); // Send our beautiful MOTD // TODO: Am I even doing this right? client.sendMessage(":irc.shane.net 001 newClient Hello! Welcome to Shane!"); client.sendMessage(":irc.shane.net 002 newClient Your host is shanebouncer, running version 1.0"); client.sendMessage(":irc.shane.net 003 newClient Please type /password <pass> OR /msg bouncer <password> to authenticate."); Thread thread = new Thread(client, "Client-" + numClients); thread.start(); } catch (IOException e) { logger.log(Level.SEVERE, "IOException while performing handshake with client #" + this.numClients, e); } } // Cleanup try { socket.close(); } catch (IOException e) { // ignored } } /** * Sends a message to all **authenticated** clients, usually just used to echo what was received from the IRC server" * If any IOException occurs, the connection is assumed to be dead and the orphaned client will be removed from the connected list * @param msg The message to be sent */ public void distributeMessage(String msg) { for (IRCClient client : this.connectedClients) { try { client.sendMessage(msg); } catch (IOException e) { logger.log(Level.SEVERE, "Lost connection to client: " + client.getConnection().getRemoteSocketAddress().toString(), e); this.connectedClients.remove(client); if (this.connectedClients.size() == 0) { try { this.ircServer.sendMesssage("NICK " + this.ircServer.getNickName() + " afk"); } catch (IOException e1) { logger.log(Level.WARNING, "IOException occurred while setting afk status", e1); } } break; } } } /** * @return the list of connected clients */ public List<IRCClient> getConnectedClients() { return this.connectedClients; } public void stop() { this.isRunning = false; // Kick all clients off this.distributeMessage(":irc.shane.net 372 bouncer Bouncer is shutting down! Goodbye!"); for (IRCClient client : this.connectedClients) { client.disconnect(); } } public boolean isRunning() { return this.isRunning; } }
31.419244
173
0.670458
2984dd6746272b198bad8fdf5f48bf871d384d35
442
package org.realityforge.webtack.model.tools.spi; import javax.annotation.Nonnull; import org.realityforge.webtack.model.WebIDLSchema; /** * Combine two or more schemas into a single schema. */ public interface Combiner { /** * Combine two or more schemas into a single schema. * * @param schemas the schemas to combine. * @return the merged schema. */ WebIDLSchema combine( @Nonnull final WebIDLSchema... schemas ); }
23.263158
65
0.723982
511377141e6ab65bc54ab82214e7c136788252cf
4,896
package com.thefirstlineofcode.marble.ibr; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import org.apache.jmeter.gui.util.HorizontalPanel; import org.apache.jmeter.gui.util.VerticalPanel; import org.apache.jmeter.samplers.gui.AbstractSamplerGui; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.util.JMeterUtils; public class InBandRegistrationSamplerGui extends AbstractSamplerGui { private static final long serialVersionUID = 3407218947396368827L; private JTextField host; private JTextField port; private JCheckBox tlsRequired; private JTextField username; private JTextField password; public InBandRegistrationSamplerGui() { init(); } private void init() { setLayout(new BorderLayout(0, 5)); setBorder(makeBorder()); VerticalPanel mainPanel = new VerticalPanel(); JPanel hostPanel = new HorizontalPanel(); hostPanel.setBorder(BorderFactory.createTitledBorder(JMeterUtils.getResString("xmpp_host_config"))); hostPanel.add(createHostPanel(), BorderLayout.CENTER); hostPanel.add(getPortPanel(), BorderLayout.EAST); JPanel securityPanel = new HorizontalPanel(); securityPanel.setBorder(BorderFactory.createTitledBorder(JMeterUtils.getResString("xmpp_security_config"))); securityPanel.add(createTlsRequiredPanel()); JPanel loginPanel = new VerticalPanel(); loginPanel.setBorder(BorderFactory.createTitledBorder(JMeterUtils.getResString("xmpp_registration_info"))); loginPanel.add(createUsernamePanel()); loginPanel.add(createPasswordPanel()); mainPanel.add(hostPanel); mainPanel.add(securityPanel); mainPanel.add(loginPanel); add(makeTitlePanel(), BorderLayout.NORTH); add(mainPanel, BorderLayout.CENTER); } private JPanel createUsernamePanel() { JLabel label = new JLabel(JMeterUtils.getResString("xmpp_username")); username = new JTextField(10); label.setLabelFor(username); JPanel usernamePanel = new JPanel(new BorderLayout(5, 0)); usernamePanel.add(label, BorderLayout.WEST); usernamePanel.add(username, BorderLayout.CENTER); return usernamePanel; } private JPanel createPasswordPanel() { JLabel label = new JLabel(JMeterUtils.getResString("xmpp_password")); password = new JTextField(10); label.setLabelFor(password); JPanel passwordPanel = new JPanel(new BorderLayout(5, 0)); passwordPanel.add(label, BorderLayout.WEST); passwordPanel.add(password, BorderLayout.CENTER); return passwordPanel; } private Component createTlsRequiredPanel() { tlsRequired = new JCheckBox(JMeterUtils.getResString("xmpp_tls_required")); JPanel tlsRequiredPanel = new JPanel(new BorderLayout(5, 0)); tlsRequiredPanel.add(tlsRequired, BorderLayout.CENTER); return tlsRequiredPanel; } private JPanel createHostPanel() { JLabel label = new JLabel(JMeterUtils.getResString("xmpp_host")); host = new JTextField(10); label.setLabelFor(host); JPanel hostPanel = new JPanel(new BorderLayout(5, 0)); hostPanel.add(label, BorderLayout.WEST); hostPanel.add(host, BorderLayout.CENTER); return hostPanel; } private JPanel getPortPanel() { port = new JTextField(4); JLabel label = new JLabel(JMeterUtils.getResString("xmpp_port")); label.setLabelFor(port); JPanel panel = new JPanel(new BorderLayout(5, 0)); panel.add(label, BorderLayout.WEST); panel.add(port, BorderLayout.CENTER); return panel; } @Override public String getLabelResource() { return "xmpp_in_band_registration_sampler_title"; } @Override public TestElement createTestElement() { InBandRegistrationSampler sampler = new InBandRegistrationSampler(); modifyTestElement(sampler); return sampler; } @Override public void modifyTestElement(TestElement element) { InBandRegistrationSampler sampler = (InBandRegistrationSampler)element; sampler.setHost(host.getText()); sampler.setPort(port.getText()); sampler.setTlsRequired(tlsRequired.isSelected()); sampler.setUsername(username.getText()); sampler.setPassword(password.getText()); super.configureTestElement(element); } @Override public void configure(TestElement element) { super.configure(element); InBandRegistrationSampler sampler = (InBandRegistrationSampler)element; host.setText(sampler.getHost()); port.setText(sampler.getPort()); tlsRequired.setSelected(sampler.isTlsRequired()); username.setText(sampler.getUsername()); password.setText(sampler.getPassword()); } @Override public void clearGui() { super.clearGui(); host.setText(""); port.setText(""); tlsRequired.setSelected(true); username.setText(""); password.setText(""); tlsRequired.setSelected(true); } }
27.818182
110
0.754698
08d3f3ea49aead662381e723712ae0c48f98fdc1
27,130
package com.redhat.ceylon.compiler.java.runtime.metamodel.decl; import java.lang.reflect.AnnotatedElement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import ceylon.language.Anything; import ceylon.language.Empty; import ceylon.language.Sequential; import ceylon.language.empty_; import ceylon.language.meta.declaration.OpenType; import ceylon.language.meta.model.ClassOrInterface; import ceylon.language.meta.model.Member; import com.redhat.ceylon.compiler.java.Util; import com.redhat.ceylon.compiler.java.language.ObjectArrayIterable; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Ignore; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.Sequenced; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; import com.redhat.ceylon.compiler.java.metadata.TypeParameter; import com.redhat.ceylon.compiler.java.metadata.TypeParameters; import com.redhat.ceylon.compiler.java.metadata.Variance; import com.redhat.ceylon.compiler.java.runtime.metamodel.AnnotationBearing; import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel; import com.redhat.ceylon.compiler.java.runtime.metamodel.Predicates; import com.redhat.ceylon.compiler.java.runtime.metamodel.Predicates.Predicate; import com.redhat.ceylon.compiler.java.runtime.metamodel.meta.MemberClassImpl; import com.redhat.ceylon.compiler.java.runtime.metamodel.meta.MemberInterfaceImpl; import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Reference; import com.redhat.ceylon.model.typechecker.model.Setter; import com.redhat.ceylon.model.typechecker.model.Type; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.Value; @Ceylon(major = 8) @com.redhat.ceylon.compiler.java.metadata.Class public abstract class ClassOrInterfaceDeclarationImpl extends NestableDeclarationImpl implements ceylon.language.meta.declaration.ClassOrInterfaceDeclaration, AnnotationBearing { @Ignore public static final TypeDescriptor $TypeDescriptor$ = TypeDescriptor.klass(ClassOrInterfaceDeclarationImpl.class); @Ignore private static final TypeDescriptor $FunctionTypeDescriptor = TypeDescriptor.klass(ceylon.language.meta.declaration.FunctionDeclaration.class, Anything.$TypeDescriptor$, Empty.$TypeDescriptor$); @Ignore private static final TypeDescriptor $AttributeTypeDescriptor = TypeDescriptor.klass(ceylon.language.meta.declaration.ValueDeclaration.class, Anything.$TypeDescriptor$); @Ignore private static final TypeDescriptor $ClassOrInterfaceTypeDescriptor = TypeDescriptor.klass(ceylon.language.meta.declaration.ClassOrInterfaceDeclaration.class, Anything.$TypeDescriptor$); private volatile boolean initialised = false; private ceylon.language.meta.declaration.OpenClassType superclass; private Sequential<ceylon.language.meta.declaration.OpenInterfaceType> interfaces; private Sequential<? extends ceylon.language.meta.declaration.TypeParameter> typeParameters; private List<ceylon.language.meta.declaration.NestableDeclaration> declaredDeclarations; private List<ceylon.language.meta.declaration.NestableDeclaration> declarations; private Sequential<? extends ceylon.language.meta.declaration.OpenType> caseTypes; public ClassOrInterfaceDeclarationImpl(com.redhat.ceylon.model.typechecker.model.ClassOrInterface declaration) { super(declaration); } @SuppressWarnings({ "unchecked", "rawtypes" }) protected void init(){ com.redhat.ceylon.model.typechecker.model.ClassOrInterface declaration = (com.redhat.ceylon.model.typechecker.model.ClassOrInterface) this.declaration; Type superType = declaration.getExtendedType(); if(superType != null) this.superclass = (ceylon.language.meta.declaration.OpenClassType) Metamodel.getMetamodel(superType); List<Type> satisfiedTypes = declaration.getSatisfiedTypes(); ceylon.language.meta.declaration.OpenInterfaceType[] interfaces = new ceylon.language.meta.declaration.OpenInterfaceType[satisfiedTypes.size()]; int i=0; for(Type pt : satisfiedTypes){ interfaces[i++] = (ceylon.language.meta.declaration.OpenInterfaceType) Metamodel.getMetamodel(pt); } this.interfaces = Util.sequentialWrapper(ceylon.language.meta.declaration.OpenInterfaceType.$TypeDescriptor$, interfaces); if(declaration.getCaseTypes() != null) this.caseTypes = Metamodel.getMetamodelSequential(declaration.getCaseTypes()); else this.caseTypes = (Sequential<? extends ceylon.language.meta.declaration.OpenType>)(Sequential)empty_.get_(); this.typeParameters = Metamodel.getTypeParameters(declaration); List<com.redhat.ceylon.model.typechecker.model.Declaration> memberModelDeclarations = declaration.getMembers(); this.declaredDeclarations = new LinkedList<ceylon.language.meta.declaration.NestableDeclaration>(); for(com.redhat.ceylon.model.typechecker.model.Declaration memberModelDeclaration : memberModelDeclarations){ addDeclarationTo(memberModelDeclaration, declaredDeclarations); } Collection<com.redhat.ceylon.model.typechecker.model.Declaration> inheritedModelDeclarations = collectMembers(declaration); this.declarations = new LinkedList<ceylon.language.meta.declaration.NestableDeclaration>(); for(com.redhat.ceylon.model.typechecker.model.Declaration memberModelDeclaration : inheritedModelDeclarations){ addDeclarationTo(memberModelDeclaration, declarations); } } protected static void addDeclarationTo( com.redhat.ceylon.model.typechecker.model.Declaration memberModelDeclaration, List<ceylon.language.meta.declaration.NestableDeclaration> declaredDeclarations) { if(isSupportedType(memberModelDeclaration)) declaredDeclarations.add(Metamodel.<ceylon.language.meta.declaration.NestableDeclaration>getOrCreateMetamodel(memberModelDeclaration)); if (memberModelDeclaration instanceof Value) { Setter setter = ((Value)memberModelDeclaration).getSetter(); if (setter != null) { declaredDeclarations.add(Metamodel.<ceylon.language.meta.declaration.NestableDeclaration>getOrCreateMetamodel(setter)); } } } private static boolean isSupportedType(Declaration memberModelDeclaration) { return memberModelDeclaration instanceof com.redhat.ceylon.model.typechecker.model.Value || (memberModelDeclaration instanceof com.redhat.ceylon.model.typechecker.model.Function && !((com.redhat.ceylon.model.typechecker.model.Function)memberModelDeclaration).isAbstraction()) || memberModelDeclaration instanceof com.redhat.ceylon.model.typechecker.model.TypeAlias || memberModelDeclaration instanceof com.redhat.ceylon.model.typechecker.model.Interface || (memberModelDeclaration instanceof com.redhat.ceylon.model.typechecker.model.Class && !((com.redhat.ceylon.model.typechecker.model.Class)memberModelDeclaration).isAbstraction()); } private Collection<com.redhat.ceylon.model.typechecker.model.Declaration> collectMembers(com.redhat.ceylon.model.typechecker.model.TypeDeclaration base){ Map<String, com.redhat.ceylon.model.typechecker.model.Declaration> byName = new HashMap<String, com.redhat.ceylon.model.typechecker.model.Declaration>(); collectMembers(base, byName); return byName.values(); } private void collectMembers(com.redhat.ceylon.model.typechecker.model.TypeDeclaration base, Map<String, Declaration> byName) { for(com.redhat.ceylon.model.typechecker.model.Declaration decl : base.getMembers()){ if(decl.isShared() && com.redhat.ceylon.model.typechecker.model.ModelUtil.isResolvable(decl)){ Declaration otherDeclaration = byName.get(decl.getName()); if(otherDeclaration == null || decl.refines(otherDeclaration)) byName.put(decl.getName(), decl); } } com.redhat.ceylon.model.typechecker.model.Type et = base.getExtendedType(); if(et != null) { collectMembers(et.getDeclaration(), byName); } for(com.redhat.ceylon.model.typechecker.model.Type st : base.getSatisfiedTypes()){ if(st != null) { collectMembers(st.getDeclaration(), byName); } } } protected final void checkInit(){ if(!initialised){ synchronized(Metamodel.getLock()){ if(!initialised){ init(); initialised = true; } } } } @Override @TypeInfo("ceylon.language::Sequential<Kind>") @TypeParameters(@TypeParameter(value = "Kind", satisfies = "ceylon.language.meta.declaration::NestableDeclaration")) public <Kind extends ceylon.language.meta.declaration.NestableDeclaration> Sequential<? extends Kind> memberDeclarations(@Ignore TypeDescriptor $reifiedKind) { Predicates.Predicate<?> predicate = Predicates.isDeclarationOfKind($reifiedKind); return filteredMembers($reifiedKind, predicate); } @Override @TypeInfo("ceylon.language::Sequential<Kind>") @TypeParameters(@TypeParameter(value = "Kind", satisfies = "ceylon.language.meta.declaration::NestableDeclaration")) public <Kind extends ceylon.language.meta.declaration.NestableDeclaration> Sequential<? extends Kind> declaredMemberDeclarations(@Ignore TypeDescriptor $reifiedKind) { Predicates.Predicate<?> predicate = Predicates.isDeclarationOfKind($reifiedKind); return filteredDeclaredMembers($reifiedKind, predicate); } @Override @TypeInfo("ceylon.language::Sequential<Kind>") @TypeParameters({ @TypeParameter(value = "Kind", satisfies = "ceylon.language.meta.declaration::NestableDeclaration"), @TypeParameter(value = "Annotation", satisfies = "ceylon.language::Annotation") }) public <Kind extends ceylon.language.meta.declaration.NestableDeclaration, Annotation extends java.lang.annotation.Annotation> Sequential<? extends Kind> annotatedMemberDeclarations(@Ignore TypeDescriptor $reifiedKind, @Ignore TypeDescriptor $reifiedAnnotation) { Predicates.Predicate<?> predicate = Predicates.and( Predicates.isDeclarationOfKind($reifiedKind), Predicates.isDeclarationAnnotatedWith($reifiedAnnotation)); return filteredMembers($reifiedKind, predicate); } @Override @TypeInfo("ceylon.language::Sequential<Kind>") @TypeParameters({ @TypeParameter(value = "Kind", satisfies = "ceylon.language.meta.declaration::NestableDeclaration"), @TypeParameter(value = "Annotation", satisfies = "ceylon.language::Annotation") }) public <Kind extends ceylon.language.meta.declaration.NestableDeclaration, Annotation extends java.lang.annotation.Annotation> Sequential<? extends Kind> annotatedDeclaredMemberDeclarations(@Ignore TypeDescriptor $reifiedKind, @Ignore TypeDescriptor $reifiedAnnotation) { Predicates.Predicate<?> predicate = Predicates.and( Predicates.isDeclarationOfKind($reifiedKind), Predicates.isDeclarationAnnotatedWith($reifiedAnnotation)); return filteredDeclaredMembers($reifiedKind, predicate); } @SuppressWarnings({ "rawtypes", "unchecked" }) private <Kind> Sequential<? extends Kind> filteredMembers( @Ignore TypeDescriptor $reifiedKind, Predicates.Predicate predicate) { if (predicate == Predicates.false_()) { return (Sequential<? extends Kind>)empty_.get_(); } checkInit(); ArrayList<Kind> members = new ArrayList<Kind>(declarations.size()); for(ceylon.language.meta.declaration.NestableDeclaration decl : declarations){ if (predicate.accept(((NestableDeclarationImpl)decl).declaration)) { members.add((Kind) decl); } } java.lang.Object[] array = members.toArray(new java.lang.Object[0]); ObjectArrayIterable<Kind> iterable = new ObjectArrayIterable<Kind>($reifiedKind, (Kind[]) array); return (ceylon.language.Sequential) iterable.sequence(); } @SuppressWarnings({ "rawtypes", "unchecked" }) private <Kind> Sequential<? extends Kind> filteredDeclaredMembers( @Ignore TypeDescriptor $reifiedKind, Predicates.Predicate predicate) { if (predicate == Predicates.false_()) { return (Sequential<? extends Kind>)empty_.get_(); } checkInit(); ArrayList<Kind> members = new ArrayList<Kind>(declarations.size()); for(ceylon.language.meta.declaration.NestableDeclaration decl : declaredDeclarations){ if (predicate.accept(((NestableDeclarationImpl)decl).declaration)) { members.add((Kind) decl); } } java.lang.Object[] array = members.toArray(new java.lang.Object[0]); ObjectArrayIterable<Kind> iterable = new ObjectArrayIterable<Kind>($reifiedKind, (Kind[]) array); return (ceylon.language.Sequential) iterable.sequence(); } @SuppressWarnings({ "rawtypes", "unchecked" }) private <Kind> Kind filteredMember( @Ignore TypeDescriptor $reifiedKind, Predicates.Predicate predicate) { if (predicate == Predicates.false_()) { return null; } checkInit(); for(ceylon.language.meta.declaration.NestableDeclaration decl : declarations){ if (predicate.accept(((NestableDeclarationImpl)decl).declaration)) { return (Kind)decl; } } return null; } @SuppressWarnings({ "rawtypes", "unchecked" }) private <Kind> Kind filteredDeclaredMember( @Ignore TypeDescriptor $reifiedKind, Predicates.Predicate predicate) { if (predicate == Predicates.false_()) { return null; } checkInit(); for(ceylon.language.meta.declaration.NestableDeclaration decl : declaredDeclarations){ if (predicate.accept(((NestableDeclarationImpl)decl).declaration)) { return (Kind)decl; } } return null; } @Override @TypeInfo("Kind") @TypeParameters(@TypeParameter(value = "Kind", satisfies = "ceylon.language.meta.declaration::NestableDeclaration")) public <Kind extends ceylon.language.meta.declaration.NestableDeclaration> Kind getMemberDeclaration(@Ignore TypeDescriptor $reifiedKind, @Name("name") String name) { Predicates.Predicate<?> predicate = Predicates.and( Predicates.isDeclarationNamed(name), Predicates.isDeclarationOfKind($reifiedKind) ); return filteredMember($reifiedKind, predicate); } @Override @TypeInfo("Kind") @TypeParameters(@TypeParameter(value = "Kind", satisfies = "ceylon.language.meta.declaration::NestableDeclaration")) public <Kind extends ceylon.language.meta.declaration.NestableDeclaration> Kind getDeclaredMemberDeclaration(@Ignore TypeDescriptor $reifiedKind, @Name("name") String name) { Predicates.Predicate<?> predicate = Predicates.and( Predicates.isDeclarationNamed(name), Predicates.isDeclarationOfKind($reifiedKind) ); return filteredDeclaredMember($reifiedKind, predicate); } @Override @TypeInfo("ceylon.language::Sequential<ceylon.language.meta.declaration::OpenInterfaceType>") public Sequential<? extends ceylon.language.meta.declaration.OpenInterfaceType> getSatisfiedTypes() { checkInit(); return interfaces; } @Override @TypeInfo("ceylon.language.meta.declaration::OpenClassType|ceylon.language::Null") public ceylon.language.meta.declaration.OpenClassType getExtendedType() { checkInit(); return superclass; } @TypeInfo("ceylon.language::Sequential<ceylon.language.meta.declaration::OpenType>") @Override public ceylon.language.Sequential<? extends ceylon.language.meta.declaration.OpenType> getCaseTypes(){ checkInit(); return caseTypes; } @Override @TypeInfo("ceylon.language::Sequential<ceylon.language.meta.declaration::TypeParameter>") public Sequential<? extends ceylon.language.meta.declaration.TypeParameter> getTypeParameterDeclarations() { checkInit(); return typeParameters; } @Override public boolean getIsAlias(){ return ((com.redhat.ceylon.model.typechecker.model.ClassOrInterface)declaration).isAlias(); } @Override public OpenType getOpenType() { return Metamodel.getMetamodel(((com.redhat.ceylon.model.typechecker.model.ClassOrInterface)declaration).getType()); } @Override @TypeInfo("ceylon.language.meta.declaration::TypeParameter|ceylon.language::Null") public ceylon.language.meta.declaration.TypeParameter getTypeParameterDeclaration(@Name("name") String name) { return Metamodel.findDeclarationByName(getTypeParameterDeclarations(), name); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Ignore @Override public <Type> ceylon.language.meta.model.ClassOrInterface<Type> apply(@Ignore TypeDescriptor $reifiedType){ return apply($reifiedType, (Sequential)empty_.get_()); } @SuppressWarnings("unchecked") @Override @TypeInfo("ceylon.language.meta.model::ClassOrInterface<Type>") @TypeParameters({ @TypeParameter("Type"), }) public <Type extends Object> ceylon.language.meta.model.ClassOrInterface<Type> apply(@Ignore TypeDescriptor $reifiedType, @Name("typeArguments") @TypeInfo("ceylon.language::Sequential<ceylon.language.meta.model::Type<ceylon.language::Anything>>") @Sequenced Sequential<? extends ceylon.language.meta.model.Type<?>> typeArguments){ if(!getToplevel()) throw new ceylon.language.meta.model.TypeApplicationException("Cannot apply a member declaration with no container type: use memberApply"); List<com.redhat.ceylon.model.typechecker.model.Type> producedTypes = Metamodel.getProducedTypes(typeArguments); Metamodel.checkTypeArguments(null, declaration, producedTypes); com.redhat.ceylon.model.typechecker.model.Reference appliedType = declaration.appliedReference(null, producedTypes); Metamodel.checkReifiedTypeArgument("apply", "ClassOrInterface<$1>", Variance.OUT, appliedType.getType(), $reifiedType); return (ClassOrInterface<Type>) Metamodel.getAppliedMetamodel(appliedType.getType()); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Ignore @Override public <Container, Type extends Object> java.lang.Object memberApply(TypeDescriptor $reifiedContainer, TypeDescriptor $reifiedType, ceylon.language.meta.model.Type<? extends Object> containerType){ return this.<Container, Type>memberApply($reifiedContainer, $reifiedType, containerType, (Sequential)empty_.get_()); } @SuppressWarnings("rawtypes") @TypeInfo("ceylon.language.meta.model::Member<Container,ceylon.language.meta.model::ClassOrInterface<Type>>&ceylon.language.meta.model::ClassOrInterface<Type>") @TypeParameters({ @TypeParameter("Container"), @TypeParameter("Type"), }) @Override public <Container, Type extends Object> java.lang.Object memberApply( @Ignore TypeDescriptor $reifiedContainer, @Ignore TypeDescriptor $reifiedType, @Name("containerType") ceylon.language.meta.model.Type<? extends Object> containerType, @Name("typeArguments") @Sequenced Sequential<? extends ceylon.language.meta.model.Type<?>> typeArguments){ if(getToplevel()) throw new ceylon.language.meta.model.TypeApplicationException("Cannot apply a toplevel declaration to a container type: use apply"); ceylon.language.meta.model.Member<? extends Container, ceylon.language.meta.model.ClassOrInterface<?>> member = getAppliedClassOrInterface(null, null, typeArguments, containerType); // This is all very ugly but we're trying to make it cheaper and friendlier than just checking the full type and showing // implementation types to the user, such as AppliedMemberClass TypeDescriptor actualReifiedContainer; if(member instanceof MemberClassImpl) actualReifiedContainer = ((MemberClassImpl)member).$reifiedContainer; else actualReifiedContainer = ((MemberInterfaceImpl)member).$reifiedContainer; com.redhat.ceylon.model.typechecker.model.Type actualType = Metamodel.getModel((ceylon.language.meta.model.Type<?>) member); Metamodel.checkReifiedTypeArgument("memberApply", "Member<$1,ClassOrInterface<$2>>&ClassOrInterface<$2>", Variance.IN, Metamodel.getProducedType(actualReifiedContainer), $reifiedContainer, Variance.OUT, actualType, $reifiedType); return member; } @SuppressWarnings("unchecked") public <Container, Kind extends ceylon.language.meta.model.ClassOrInterface<? extends Object>> ceylon.language.meta.model.Member<Container, Kind> getAppliedClassOrInterface(@Ignore TypeDescriptor $reifiedContainer, @Ignore TypeDescriptor $reifiedKind, Sequential<? extends ceylon.language.meta.model.Type<?>> types, ceylon.language.meta.model.Type<? extends Object> container){ List<com.redhat.ceylon.model.typechecker.model.Type> producedTypes = Metamodel.getProducedTypes(types); Type qualifyingType = Metamodel.getModel(container); Metamodel.checkQualifyingType(qualifyingType, declaration); Metamodel.checkTypeArguments(qualifyingType, declaration, producedTypes); // find the proper qualifying type Type memberQualifyingType = qualifyingType.getSupertype((TypeDeclaration) declaration.getContainer()); Reference producedReference = declaration.appliedReference(memberQualifyingType, producedTypes); final Type appliedType = producedReference.getType(); return (Member<Container, Kind>) Metamodel.getAppliedMetamodel(appliedType); } @Override @Ignore public TypeDescriptor $getType$() { return $TypeDescriptor$; } public FunctionDeclarationImpl findMethod(String name) { NestableDeclarationImpl decl = this.findDeclaration(null, name); return decl instanceof FunctionDeclarationImpl ? (FunctionDeclarationImpl)decl : null; } public FunctionDeclarationImpl findDeclaredMethod(String name) { NestableDeclarationImpl decl = this.findDeclaredDeclaration(null, name); return decl instanceof FunctionDeclarationImpl ? (FunctionDeclarationImpl)decl : null; } public ValueDeclarationImpl findValue(String name) { NestableDeclarationImpl decl = this.findDeclaration(null, name); return decl instanceof ValueDeclarationImpl ? (ValueDeclarationImpl)decl : null; } public ValueDeclarationImpl findDeclaredValue(String name) { NestableDeclarationImpl decl = this.findDeclaredDeclaration(null, name); return decl instanceof ValueDeclarationImpl ? (ValueDeclarationImpl)decl : null; } public ClassOrInterfaceDeclarationImpl findType(String name) { NestableDeclarationImpl decl = this.findDeclaration(null, name); return decl instanceof ClassOrInterfaceDeclarationImpl ? (ClassOrInterfaceDeclarationImpl)decl : null; } public ClassOrInterfaceDeclarationImpl findDeclaredType(String name) { NestableDeclarationImpl decl = this.findDeclaredDeclaration(null, name); return decl instanceof ClassOrInterfaceDeclarationImpl ? (ClassOrInterfaceDeclarationImpl)decl : null; } public <T extends NestableDeclarationImpl> T findDeclaration(@Ignore TypeDescriptor $reifiedT, String name) { checkInit(); return findDeclaration($reifiedT, name, declarations); } public <T extends NestableDeclarationImpl> T findDeclaredDeclaration(@Ignore TypeDescriptor $reifiedT, String name) { checkInit(); return findDeclaration($reifiedT, name, declaredDeclarations); } @SuppressWarnings("unchecked") <T extends NestableDeclarationImpl> T findDeclaration(@Ignore TypeDescriptor $reifiedT, String name, List<ceylon.language.meta.declaration.NestableDeclaration> declarations) { for(ceylon.language.meta.declaration.NestableDeclaration decl : declarations){ // skip anonymous types which can't be looked up by name if(decl instanceof ceylon.language.meta.declaration.ClassDeclaration && ((ceylon.language.meta.declaration.ClassDeclaration) decl).getAnonymous()) continue; // in theory we can't have several members with the same name so no need to check the type // FIXME: interop and overloading if(name.equals(decl.getName())) return (T) decl; } return null; } @Override @Ignore public java.lang.annotation.Annotation[] $getJavaAnnotations$() { return Metamodel.getJavaClass(declaration).getAnnotations(); } @Override @Ignore public boolean $isAnnotated$(java.lang.Class<? extends java.lang.annotation.Annotation> annotationType) { final AnnotatedElement element = Metamodel.getJavaClass(declaration); return element != null ? element.isAnnotationPresent(annotationType) : false; } @Override public <AnnotationType extends java.lang.annotation.Annotation> boolean annotated(TypeDescriptor reifed$AnnotationType) { return Metamodel.isAnnotated(reifed$AnnotationType, this); } /** * Used by the SDK's ceylon.interop.java */ public java.lang.Class<?> getJavaClass(){ return Metamodel.getJavaClass(declaration); } }
49.871324
220
0.702912
4310dbb090b511ece065d1e439911661d23d39b8
1,135
package com.connectin.business.feed.service; import com.connectin.business.feed.manager.IFeedManager; import com.connectin.constants.Message; import com.connectin.domain.feed.FeedDTO; import com.connectin.exceptions.ConnectinBaseException; import com.connectin.utils.Response; import com.connectin.utils.ResponseGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class FeedServiceImpl implements FeedService { @Autowired IFeedManager feedManager; @Autowired ResponseGenerator<FeedDTO> responseGenerator; @Override public Response<FeedDTO> getPostByUser(int userId) { FeedDTO post = null; try { post = feedManager.getFeedByUser(userId); if (!post.equals(null)) { return responseGenerator.generateSuccessResponse(Message.SUCCESS, Message.SUCCESS_CODE, post); } } catch (ConnectinBaseException e) { return responseGenerator.generateErrorResponse(e.getMessage(), Message.ERROR_CODE, post); } return null; } }
27.02381
110
0.726872
31ea8685e89d2ec79c9f26065e487b4a4597f458
586
package com.geektcp.alpha.game.hanoi.panel; import java.awt.Color; import javax.swing.JButton; public class Disc extends JButton { private static final long serialVersionUID = 1L; private int number; private TowerPoint point; public Disc() { setBackground(Color.cyan); } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public TowerPoint getPoint() { return point; } public void setPoint(TowerPoint point) { this.point = point; } }
17.757576
52
0.634812
e1e3843fed59583e9f124feda945713e29b0ec15
1,426
/* * Copyright 2016 The Bazel Authors. 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.google.idea.blaze.clwb.cworkspace; import com.google.idea.blaze.base.settings.Blaze; import com.google.idea.blaze.cpp.BlazeCWorkspace; import com.google.idea.sdkcompat.cidr.OCWorkspaceManagerAdapter; import com.intellij.openapi.project.Project; import com.jetbrains.cidr.lang.workspace.OCWorkspace; /** #api173 Once pre-181 does not need to be supported, BlazeCWorkspaceManager can be removed */ class BlazeCWorkspaceManager extends OCWorkspaceManagerAdapter { private final Project project; public BlazeCWorkspaceManager(Project project) { this.project = project; } @Override public OCWorkspace getWorkspace() { if (Blaze.isBlazeProject(project)) { return BlazeCWorkspace.getInstance(project).getWorkspace(); } return getWorkspaceFallback(project); } }
35.65
96
0.765778
b4f3da4151db94ff8a3fd51e15a2a609393336e8
1,973
package io.tomahawkd.censys; import io.tomahawkd.censys.exception.CensysException; import io.tomahawkd.censys.module.Message; import io.tomahawkd.censys.module.reporting.ReportMessage; import io.tomahawkd.censys.module.searching.IpSearchMessage; import io.tomahawkd.censys.module.searching.SearchQueryMessage; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.List; public class IpSearchApi extends AbstractSearchApi { private static final String CENSYS_INDEX_IP = "ipv4"; public IpSearchApi(String uid, String secret) { super(uid, secret); } public IpSearchApi(AccountService accountService) { super(accountService); } @Override public IpSearchMessage search(String query, int page, List<String> fields) throws CensysException { String url = constructURL("search", CENSYS_INDEX_IP); try { Response<IpSearchMessage> response = postForClass(IpSearchMessage.class, url, accountService.getToken(), new SearchQueryMessage(query, page, fields).buildJson()); return wrapMessage(response); } catch (IOException e) { return null; } } @Override @Nullable public Message view(String id) throws CensysException { checkId(id); String url = constructURL("view", CENSYS_INDEX_IP) + "/" + id; Response response; // try { // response = get(url, null); // } catch (IOException e) { // throw new IllegalArgumentException(); // } return null; } @Override public ReportMessage report(String query, String field, int buckets) throws CensysException { String url = constructURL("report", CENSYS_INDEX_IP); return report(url, query, field, buckets); } private void checkId(String id) { try { String[] digits = id.split("."); for (int i = 0; i < 4; i++) { int digit = Integer.parseInt(digits[i]); if (digit > 255 || digit < 0) throw new IllegalArgumentException(); } } catch (Exception e) { throw new IllegalArgumentException("Not valid IP address"); } } }
27.027397
100
0.729853
1ec38d79d12442c1c0bf1906e78daadd6cc2764b
1,209
package com.learningmachine.android.app.data.cert.v20; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Anchor { public enum ChainType { bitcoin, testnet, regtest, mocknet, ethmain, unknown } @SerializedName("chain") @Expose private String chain; @SerializedName("sourceId") @Expose private String sourceId; @SerializedName("type") @Expose private String type; public String getSourceId() { return sourceId; } public void setSourceId(String sourceId) { this.sourceId = sourceId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getChain() { return chain; } public void setChain(String chain) { this.chain = chain; } public static boolean isValidChain(String chainName) { for (ChainType chainType : ChainType.values()) { if (chainType.name().equals(chainName)) { return true; } } return false; } }
18.6
58
0.582299
97fb8860c3fb598b8ea8b6b4bc3767056849ceae
138
public class Hawak implements Predector { @Override public void hunt() { System.out.println(" The Hawak can hunt"); } }
13.8
46
0.637681
4f50e7985590ea74e8273fbb88588cea544d25fa
4,117
/* * Copyright (C) 2009-2020 Lightbend Inc. <https://www.lightbend.com> */ package docs.http.javadsl; import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.ModeledCustomHeader; import akka.http.javadsl.model.headers.ModeledCustomHeaderFactory; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.JUnitRouteTest; import akka.japi.JavaPartialFunction; import org.junit.Test; import scala.PartialFunction; import java.util.Optional; import static org.junit.Assert.*; //#header-value-pf import akka.http.javadsl.server.Directives; import static akka.http.javadsl.server.Directives.headerValuePF; //#header-value-pf public class CustomHeaderExampleTest extends JUnitRouteTest { //#modeled-api-key-custom-header public static class ApiTokenHeader extends ModeledCustomHeader { ApiTokenHeader(String name, String value) { super(name, value); } public boolean renderInResponses() { return false; } public boolean renderInRequests() { return false; } } static class ApiTokenHeaderFactory extends ModeledCustomHeaderFactory<ApiTokenHeader> { public String name() { return "apiKey"; } @Override public ApiTokenHeader parse(String value) { return new ApiTokenHeader(name(), value); } } //#modeled-api-key-custom-header @Test public void showCreation() { //#conversion-creation-custom-header final ApiTokenHeaderFactory apiTokenHeaderFactory = new ApiTokenHeaderFactory(); final ApiTokenHeader token = apiTokenHeaderFactory.create("token"); assertEquals("token", token.value()); final HttpHeader header = apiTokenHeaderFactory.create("token"); assertEquals("apiKey", header.name()); assertEquals("token", header.value()); final Optional<ApiTokenHeader> fromRaw = apiTokenHeaderFactory .from(RawHeader.create("apiKey", "token")); assertTrue("Expected a header", fromRaw.isPresent()); assertEquals("apiKey", fromRaw.get().name()); assertEquals("token", fromRaw.get().value()); // will match, header keys are case insensitive final Optional<ApiTokenHeader> fromRawUpper = apiTokenHeaderFactory .from(RawHeader.create("APIKEY", "token")); assertTrue("Expected a header", fromRawUpper.isPresent()); assertEquals("apiKey", fromRawUpper.get().name()); assertEquals("token", fromRawUpper.get().value()); // won't match, different header name final Optional<ApiTokenHeader> wrong = apiTokenHeaderFactory .from(RawHeader.create("different", "token")); assertFalse(wrong.isPresent()); //#conversion-creation-custom-header } @Test public void testExtraction() { //#header-value-pf final ApiTokenHeaderFactory apiTokenHeaderFactory = new ApiTokenHeaderFactory(); final PartialFunction<HttpHeader, String> extractFromCustomHeader = new JavaPartialFunction<HttpHeader, String>() { @Override public String apply(HttpHeader header, boolean isCheck) throws Exception { if (isCheck) return null; return apiTokenHeaderFactory.from(header) .map(apiTokenHeader -> "extracted> " + apiTokenHeader) .orElseGet(() -> "raw> " + header); } }; final Route route = headerValuePF(extractFromCustomHeader, Directives::complete); testRoute(route) .run(HttpRequest.GET("/").addHeader(RawHeader.create("apiKey", "TheKey"))) .assertStatusCode(StatusCodes.OK) .assertEntity("extracted> apiKey: TheKey"); testRoute(route) .run(HttpRequest.GET("/").addHeader(RawHeader.create("somethingElse", "TheKey"))) .assertStatusCode(StatusCodes.OK) .assertEntity("raw> somethingElse: TheKey"); testRoute(route) .run(HttpRequest.GET("/").addHeader(apiTokenHeaderFactory.create("TheKey"))) .assertStatusCode(StatusCodes.OK) .assertEntity("extracted> apiKey: TheKey"); //#header-value-pf } }
31.669231
89
0.71144
cf54f55b095648f969f9f735e1044b3a0e93d629
3,430
package ru.job4j.map.equalsandhash; import org.junit.Test; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class UserEqualsAndHashCodeTest { /** * Test adding to map */ @Test public void whenTwoUsersWithTheSameFieldsAddedToMapThenSecondKeyReplacesFirst() { Map<UserEqualsAndHashCode, String> map = new HashMap<>(); UserEqualsAndHashCode first = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); UserEqualsAndHashCode second = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); assertThat(map.put(first, "first"), is((String) null)); assertThat(map.put(second, "second"), is("first")); } /** * Test toString() */ @Test public void whenToStringThenStringWithValues() { UserEqualsAndHashCode user = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); String result = user.toString(); String expected = "[name: Ivan, children: 12, birthday: 1961-04-12]"; assertThat(result, is(expected)); } /** * Test equals() */ @Test public void whenObjectsWithTheSameFieldsThenEqualsTrue() { UserEqualsAndHashCode first = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); UserEqualsAndHashCode second = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); assertThat(first.equals(second), is(true)); } @Test public void whenSomeFieldIsNotTheSameThenFalse() { UserEqualsAndHashCode origin = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); UserEqualsAndHashCode otherName = new UserEqualsAndHashCode("Alena", 12, LocalDate.of(1961, 4, 12)); UserEqualsAndHashCode otherChlidren = new UserEqualsAndHashCode("Ivan", 5, LocalDate.of(1961, 4, 12)); UserEqualsAndHashCode otherBirthday = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(2008, 7, 1)); assertThat(origin.equals(otherName), is(false)); assertThat(origin.equals(otherChlidren), is(false)); assertThat(origin.equals(otherBirthday), is(false)); } @Test public void whenOtherObjectOfAnotherClassThenEqualsFalse() { UserEqualsAndHashCode first = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); String second = "I'm equal!"; assertThat(first.equals(second), is(false)); } @Test public void whenOtherObjectIsNullThenEqualsFalse() { UserEqualsAndHashCode first = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); UserEqualsAndHashCode second = null; assertThat(first.equals(second), is(false)); } @Test public void whenTheSameObjectThenEqualsTrue() { UserEqualsAndHashCode first = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); assertThat(first.equals(first), is(true)); } /** * Test hashcode() */ @Test public void whenObjectsWithTheSameFieldsThenHashCodeTheSame() { UserEqualsAndHashCode first = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); UserEqualsAndHashCode second = new UserEqualsAndHashCode("Ivan", 12, LocalDate.of(1961, 4, 12)); assertThat(first.hashCode() == second.hashCode(), is(true)); } }
38.977273
110
0.6793
bc3eda88f8f2c43fa6a884d9887973ee0c37f652
1,075
package com.migratorydata.answers; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; public class StatisticsProcessor { private final AtomicLong answers = new AtomicLong(); private final AtomicLong results = new AtomicLong(); private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); public StatisticsProcessor() { executor.scheduleAtFixedRate(() -> { long answersConsumed = answers.getAndSet(0); long resultsSent = results.getAndSet(0); System.out.println("Number of answers consumed=" + (double)(answersConsumed / 5) + "/second"); System.out.println("Number of results sent= " + (double)(resultsSent / 5) + "/second"); }, 5000, 5000, TimeUnit.MILLISECONDS); } public void addAnswers(int count) { answers.addAndGet(count); } public void incrementResults() { results.incrementAndGet(); } }
34.677419
106
0.695814
051e40438411f53e425bc762f1dbefe68ec3cb63
2,661
package com.nulp.labs_aplication.api.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.List; /** * Created by Vova0199 on 18/11/2018. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "adult", "backdrop_path", "belongs_to_collection", "budget", "genres", "homepage", "id", "imdb_id", "original_language", "original_title", "overview", "popularity", "poster_path", "production_companies", "production_countries", "release_date", "revenue", "runtime", "spoken_languages", "status", "tagline", "title", "video", "vote_average", "vote_count" }) public class Movie { @JsonProperty("adult") public boolean adult; @JsonProperty("backdrop_path") public String backdropPath; @JsonProperty("belongs_to_collection") public BelongsToCollection belongsToCollection; @JsonProperty("budget") public int budget; @JsonProperty("genres") public List<Genre> genres = null; @JsonProperty("homepage") public String homepage; @JsonProperty("id") public int id; @JsonProperty("imdb_id") public String imdbId; @JsonProperty("original_language") public String originalLanguage; @JsonProperty("original_title") public String originalTitle; @JsonProperty("overview") public String overview; @JsonProperty("popularity") public float popularity; @JsonProperty("poster_path") public String posterPath; @JsonProperty("production_companies") public List<ProductionCompany> productionCompanies = null; @JsonProperty("production_countries") public List<ProductionCountry> productionCountries = null; @JsonProperty("release_date") public String releaseDate; @JsonProperty("revenue") public int revenue; @JsonProperty("runtime") public int runtime; @JsonProperty("spoken_languages") public List<SpokenLanguage> spokenLanguages = null; @JsonProperty("status") public String status; @JsonProperty("tagline") public String tagline; @JsonProperty("title") public String title; @JsonProperty("video") public boolean video; @JsonProperty("vote_average") public float voteAverage; @JsonProperty("vote_count") public int voteCount; }
27.43299
62
0.676437