text
stringlengths
7
1.01M
package io.vrap.rmf.base.client.error; import io.vrap.rmf.base.client.ApiHttpHeaders; import io.vrap.rmf.base.client.ApiHttpRequest; import io.vrap.rmf.base.client.ApiHttpResponse; import io.vrap.rmf.base.client.ResponseSerializer; public class InternalServerErrorException extends ApiServerException { public InternalServerErrorException(final int statusCode, final String body, final ApiHttpHeaders headers, final String message, final ApiHttpResponse<byte[]> response) { super(statusCode, body, headers, message, response); } public InternalServerErrorException(final int statusCode, final String body, final ApiHttpHeaders headers, final String message, final ApiHttpResponse<byte[]> response, final ApiHttpRequest request) { super(statusCode, body, headers, message, response, request); } public InternalServerErrorException(final int statusCode, final String body, final ApiHttpHeaders headers, final String message, final ApiHttpResponse<byte[]> response, final ResponseSerializer serializer) { super(statusCode, body, headers, message, response, serializer); } public InternalServerErrorException(final int statusCode, final String body, final ApiHttpHeaders headers, final String message, final ApiHttpResponse<byte[]> response, final ApiHttpRequest request, final ResponseSerializer serializer) { super(statusCode, body, headers, message, response, request, serializer); } }
//Title: Your Product Name //Version: //Copyright: Copyright (c) 1998 //Author: Your Name //Company: Your Company //Description: Your description //!!WARNING: THIS IS A GENERATED CLASS //!!WARNING: ONLY MODIFY SECTION BETWEEN BEGIN AND END OF USER SECTION package dai.shared.businessObjs; import java.util.Calendar; import org.altaprise.vawr.utils.SessionMetaData; public class payment_voucherObj extends BusinessObject { //!!!!!!BEGIN USER SECTION!!!!!!! //Transient attributes just used to pass data accross client/server connections. static public final String _SHIP_CHARGES_ACCT_ID = "_SHIP_CHARGES_ACCT_ID"; static public final String _SHIP_CHARGES_ACCT_NAME = "_SHIP_CHARGES_ACCT_NAME"; static public final String _NUM_PAYMENTS = "_NUM_PAYMENTS"; public void clear(boolean clearImmutables) { String locality = get_locality(); for (int i=0; i < MAX_COLS; i++) { m_dbAttribs[i].setValue(null); } if (!clearImmutables) { set_locality(locality); } } public DBAttributes[] getImmutableAttribs() { DBAttributes imutables[] = new DBAttributes[1]; imutables[0] = new DBAttributes("locality", get_locality(), "VARCHAR", true); return imutables; } public void setDefaults() { //Initialize some of the attributes that should have default values. //Add the current date to the Date Created Field. Calendar now = Calendar.getInstance(); SessionMetaData sessionMeta = null; sessionMeta = SessionMetaData.getInstance(); set_date_created(now.get(Calendar.MONTH)+1 + "/" + now.get(Calendar.DAY_OF_MONTH) + "/" + now.get(Calendar.YEAR)); set_locality(sessionMeta.getLocality()); set_created_by(sessionMeta.getUserId()); } //!!!!!! END USER SECTION !!!!!!! //!!!!!! END USER SECTION !!!!!!! //STATIC DATA // static public final String TABLE_NAME = "PAYMENT_VOUCHER"; static public final String ID = "PAYMENT_VOUCHER.ID"; static public final String LOCALITY = "PAYMENT_VOUCHER.LOCALITY"; static public final String CREATED_BY = "PAYMENT_VOUCHER.CREATED_BY"; static public final String DATE_CREATED = "PAYMENT_VOUCHER.DATE_CREATED"; static public final String CHECK_NUM = "PAYMENT_VOUCHER.CHECK_NUM"; static public final String PAYMENT_METHOD = "PAYMENT_VOUCHER.PAYMENT_METHOD"; static public final String CC_NUM = "PAYMENT_VOUCHER.CC_NUM"; static public final String CC_EXP_DATE = "PAYMENT_VOUCHER.CC_EXP_DATE"; static public final String NOTE = "PAYMENT_VOUCHER.NOTE"; static public final String PAYMENT_AMT = "PAYMENT_VOUCHER.PAYMENT_AMT"; static public final String PRINT_CHECK = "PAYMENT_VOUCHER.PRINT_CHECK"; static public final String ACCTID = "PAYMENT_VOUCHER.ACCTID"; static public final String ACCTNAME = "PAYMENT_VOUCHER.ACCTNAME"; static public final String INVOICE_NUM = "PAYMENT_VOUCHER.INVOICE_NUM"; static public final String INVOICE_DATE = "PAYMENT_VOUCHER.INVOICE_DATE"; static public final String PURCH_ORDER_ID = "PAYMENT_VOUCHER.PURCH_ORDER_ID"; static public final String TOTAL_VALUE = "PAYMENT_VOUCHER.TOTAL_VALUE"; static public final String TOTAL_PAYMENTS_POSTED = "PAYMENT_VOUCHER.TOTAL_PAYMENTS_POSTED"; static public final String VENDOR_ID = "PAYMENT_VOUCHER.VENDOR_ID"; static public final String VENDOR_NAME = "PAYMENT_VOUCHER.VENDOR_NAME"; static public final String PAYMENT_DUE_DATE = "PAYMENT_VOUCHER.PAYMENT_DUE_DATE"; static public final String PAYMENT_TERMS = "PAYMENT_VOUCHER.PAYMENT_TERMS"; static public final String DATE_PAID = "PAYMENT_VOUCHER.DATE_PAID"; static public final String PAY_FROM_ACCT_ID = "PAYMENT_VOUCHER.PAY_FROM_ACCT_ID"; static public final String PAY_FROM_ACCT_NAME = "PAYMENT_VOUCHER.PAY_FROM_ACCT_NAME"; static public final String TOTAL_SHIPPING_CHARGES = "PAYMENT_VOUCHER.TOTAL_SHIPPING_CHARGES"; static public final String SUBTOTAL_AMT = "PAYMENT_VOUCHER.SUBTOTAL_AMT"; static public final String CHECK_TOT_AMT_FOR_PRINTING = "PAYMENT_VOUCHER.CHECK_TOT_AMT_FOR_PRINTING"; static public final String CHECK_TOT_AMT_TEXT_FOR_PRINTING = "PAYMENT_VOUCHER.CHECK_TOT_AMT_TEXT_FOR_PRINTING"; static public final String VENDOR_ADDR1 = "PAYMENT_VOUCHER.VENDOR_ADDR1"; static public final String VENDOR_ADDR2 = "PAYMENT_VOUCHER.VENDOR_ADDR2"; static public final String VENDOR_ADDR3 = "PAYMENT_VOUCHER.VENDOR_ADDR3"; static public final String VENDOR_ADDR4 = "PAYMENT_VOUCHER.VENDOR_ADDR4"; static public final String VENDOR_CITY = "PAYMENT_VOUCHER.VENDOR_CITY"; static public final String VENDOR_STATE_CODE = "PAYMENT_VOUCHER.VENDOR_STATE_CODE"; static public final String VENDOR_ZIP = "PAYMENT_VOUCHER.VENDOR_ZIP"; static public final String VENDOR_COUNTRY_CODE = "PAYMENT_VOUCHER.VENDOR_COUNTRY_CODE"; static public final String VENDOR_COUNTRY_NAME = "PAYMENT_VOUCHER.VENDOR_COUNTRY_NAME"; static public final String OUR_ACCT_NO_WITH_VENDOR = "PAYMENT_VOUCHER.OUR_ACCT_NO_WITH_VENDOR"; static public final String IS_VOIDED = "PAYMENT_VOUCHER.IS_VOIDED"; static public final String DATE_CHECK_SENT = "PAYMENT_VOUCHER.DATE_CHECK_SENT"; //Constructor public payment_voucherObj() { //Private Field Members. MAX_COLS = 41; TAB_NAME = "PAYMENT_VOUCHER"; m_dbAttribs = new DBAttributes[MAX_COLS]; Init(); setDefaults(); } public void Init() { m_dbAttribs[0] = new DBAttributes("ID", null, "VARCHAR", 30 ,true); m_dbAttribs[1] = new DBAttributes("LOCALITY", null, "VARCHAR", 20 ,true); m_dbAttribs[2] = new DBAttributes("CREATED_BY", null, "VARCHAR", 20 ,true); m_dbAttribs[3] = new DBAttributes("DATE_CREATED", null, "DATE", 19 ,true); m_dbAttribs[4] = new DBAttributes("CHECK_NUM", null, "VARCHAR", 20 ,true); m_dbAttribs[5] = new DBAttributes("PAYMENT_METHOD", null, "VARCHAR", 20 ,true); m_dbAttribs[6] = new DBAttributes("CC_NUM", null, "VARCHAR", 20 ,true); m_dbAttribs[7] = new DBAttributes("CC_EXP_DATE", null, "VARCHAR", 12 ,true); m_dbAttribs[8] = new DBAttributes("NOTE", null, "VARCHAR", 80 ,true); m_dbAttribs[9] = new DBAttributes("PAYMENT_AMT", null, "NUMERIC", 0 ,true); m_dbAttribs[10] = new DBAttributes("PRINT_CHECK", null, "CHAR", 1 ,true); m_dbAttribs[11] = new DBAttributes("ACCTID", null, "VARCHAR", 30 ,true); m_dbAttribs[12] = new DBAttributes("ACCTNAME", null, "VARCHAR", 50 ,true); m_dbAttribs[13] = new DBAttributes("INVOICE_NUM", null, "VARCHAR", 30 ,true); m_dbAttribs[14] = new DBAttributes("INVOICE_DATE", null, "DATE", 19 ,true); m_dbAttribs[15] = new DBAttributes("PURCH_ORDER_ID", null, "VARCHAR", 30 ,true); m_dbAttribs[16] = new DBAttributes("TOTAL_VALUE", null, "NUMERIC", 0 ,true); m_dbAttribs[17] = new DBAttributes("TOTAL_PAYMENTS_POSTED", null, "NUMERIC", 0 ,true); m_dbAttribs[18] = new DBAttributes("VENDOR_ID", null, "VARCHAR", 30 ,true); m_dbAttribs[19] = new DBAttributes("VENDOR_NAME", null, "VARCHAR", 50 ,true); m_dbAttribs[20] = new DBAttributes("PAYMENT_DUE_DATE", null, "DATE", 19 ,true); m_dbAttribs[21] = new DBAttributes("PAYMENT_TERMS", null, "VARCHAR", 30 ,true); m_dbAttribs[22] = new DBAttributes("DATE_PAID", null, "DATE", 19 ,true); m_dbAttribs[23] = new DBAttributes("PAY_FROM_ACCT_ID", null, "VARCHAR", 30 ,true); m_dbAttribs[24] = new DBAttributes("PAY_FROM_ACCT_NAME", null, "VARCHAR", 50 ,true); m_dbAttribs[25] = new DBAttributes("TOTAL_SHIPPING_CHARGES", null, "NUMERIC", 0 ,true); m_dbAttribs[26] = new DBAttributes("SUBTOTAL_AMT", null, "NUMERIC", 0 ,true); m_dbAttribs[27] = new DBAttributes("CHECK_TOT_AMT_FOR_PRINTING", null, "NUMERIC", 0 ,true); m_dbAttribs[28] = new DBAttributes("CHECK_TOT_AMT_TEXT_FOR_PRINTING", null, "VARCHAR", 132 ,true); m_dbAttribs[29] = new DBAttributes("VENDOR_ADDR1", null, "VARCHAR", 50 ,true); m_dbAttribs[30] = new DBAttributes("VENDOR_ADDR2", null, "VARCHAR", 50 ,true); m_dbAttribs[31] = new DBAttributes("VENDOR_ADDR3", null, "VARCHAR", 50 ,true); m_dbAttribs[32] = new DBAttributes("VENDOR_ADDR4", null, "VARCHAR", 50 ,true); m_dbAttribs[33] = new DBAttributes("VENDOR_CITY", null, "VARCHAR", 50 ,true); m_dbAttribs[34] = new DBAttributes("VENDOR_STATE_CODE", null, "VARCHAR", 10 ,true); m_dbAttribs[35] = new DBAttributes("VENDOR_ZIP", null, "VARCHAR", 15 ,true); m_dbAttribs[36] = new DBAttributes("VENDOR_COUNTRY_CODE", null, "VARCHAR", 2 ,true); m_dbAttribs[37] = new DBAttributes("VENDOR_COUNTRY_NAME", null, "VARCHAR", 30 ,true); m_dbAttribs[38] = new DBAttributes("OUR_ACCT_NO_WITH_VENDOR", null, "VARCHAR", 30 ,true); m_dbAttribs[39] = new DBAttributes("IS_VOIDED", null, "CHAR", 1 ,true); m_dbAttribs[40] = new DBAttributes("DATE_CHECK_SENT", null, "DATE", 19 ,true); } public String get_id() {return m_dbAttribs[0].getValue();} public String get_locality() {return m_dbAttribs[1].getValue();} public String get_created_by() {return m_dbAttribs[2].getValue();} public String get_date_created() {return m_dbAttribs[3].getValue();} public String get_check_num() {return m_dbAttribs[4].getValue();} public String get_payment_method() {return m_dbAttribs[5].getValue();} public String get_cc_num() {return m_dbAttribs[6].getValue();} public String get_cc_exp_date() {return m_dbAttribs[7].getValue();} public String get_note() {return m_dbAttribs[8].getValue();} public String get_payment_amt() {return m_dbAttribs[9].getValue();} public String get_print_check() {return m_dbAttribs[10].getValue();} public String get_acctid() {return m_dbAttribs[11].getValue();} public String get_acctname() {return m_dbAttribs[12].getValue();} public String get_invoice_num() {return m_dbAttribs[13].getValue();} public String get_invoice_date() {return m_dbAttribs[14].getValue();} public String get_purch_order_id() {return m_dbAttribs[15].getValue();} public String get_total_value() {return m_dbAttribs[16].getValue();} public String get_total_payments_posted() {return m_dbAttribs[17].getValue();} public String get_vendor_id() {return m_dbAttribs[18].getValue();} public String get_vendor_name() {return m_dbAttribs[19].getValue();} public String get_payment_due_date() {return m_dbAttribs[20].getValue();} public String get_payment_terms() {return m_dbAttribs[21].getValue();} public String get_date_paid() {return m_dbAttribs[22].getValue();} public String get_pay_from_acct_id() {return m_dbAttribs[23].getValue();} public String get_pay_from_acct_name() {return m_dbAttribs[24].getValue();} public String get_total_shipping_charges() {return m_dbAttribs[25].getValue();} public String get_subtotal_amt() {return m_dbAttribs[26].getValue();} public String get_check_tot_amt_for_printing() {return m_dbAttribs[27].getValue();} public String get_check_tot_amt_text_for_printing() {return m_dbAttribs[28].getValue();} public String get_vendor_addr1() {return m_dbAttribs[29].getValue();} public String get_vendor_addr2() {return m_dbAttribs[30].getValue();} public String get_vendor_addr3() {return m_dbAttribs[31].getValue();} public String get_vendor_addr4() {return m_dbAttribs[32].getValue();} public String get_vendor_city() {return m_dbAttribs[33].getValue();} public String get_vendor_state_code() {return m_dbAttribs[34].getValue();} public String get_vendor_zip() {return m_dbAttribs[35].getValue();} public String get_vendor_country_code() {return m_dbAttribs[36].getValue();} public String get_vendor_country_name() {return m_dbAttribs[37].getValue();} public String get_our_acct_no_with_vendor() {return m_dbAttribs[38].getValue();} public String get_is_voided() {return m_dbAttribs[39].getValue();} public String get_date_check_sent() {return m_dbAttribs[40].getValue();} public void set_id(String val) { if (val == null || val.length() == 0) m_dbAttribs[0].setValue(null); else m_dbAttribs[0].setValue(val); } public void set_locality(String val) { if (val == null || val.length() == 0) m_dbAttribs[1].setValue(null); else m_dbAttribs[1].setValue(val); } public void set_created_by(String val) { if (val == null || val.length() == 0) m_dbAttribs[2].setValue(null); else m_dbAttribs[2].setValue(val); } public void set_date_created(String val) { if (val == null || val.length() == 0) m_dbAttribs[3].setValue(null); else m_dbAttribs[3].setValue(val); } public void set_check_num(String val) { if (val == null || val.length() == 0) m_dbAttribs[4].setValue(null); else m_dbAttribs[4].setValue(val); } public void set_payment_method(String val) { if (val == null || val.length() == 0) m_dbAttribs[5].setValue(null); else m_dbAttribs[5].setValue(val); } public void set_cc_num(String val) { if (val == null || val.length() == 0) m_dbAttribs[6].setValue(null); else m_dbAttribs[6].setValue(val); } public void set_cc_exp_date(String val) { if (val == null || val.length() == 0) m_dbAttribs[7].setValue(null); else m_dbAttribs[7].setValue(val); } public void set_note(String val) { if (val == null || val.length() == 0) m_dbAttribs[8].setValue(null); else m_dbAttribs[8].setValue(val); } public void set_payment_amt(String val) { if (val == null || val.length() == 0) m_dbAttribs[9].setValue(null); else m_dbAttribs[9].setValue(val); } public void set_print_check(String val) { if (val == null || val.length() == 0) m_dbAttribs[10].setValue(null); else m_dbAttribs[10].setValue(val); } public void set_acctid(String val) { if (val == null || val.length() == 0) m_dbAttribs[11].setValue(null); else m_dbAttribs[11].setValue(val); } public void set_acctname(String val) { if (val == null || val.length() == 0) m_dbAttribs[12].setValue(null); else m_dbAttribs[12].setValue(val); } public void set_invoice_num(String val) { if (val == null || val.length() == 0) m_dbAttribs[13].setValue(null); else m_dbAttribs[13].setValue(val); } public void set_invoice_date(String val) { if (val == null || val.length() == 0) m_dbAttribs[14].setValue(null); else m_dbAttribs[14].setValue(val); } public void set_purch_order_id(String val) { if (val == null || val.length() == 0) m_dbAttribs[15].setValue(null); else m_dbAttribs[15].setValue(val); } public void set_total_value(String val) { if (val == null || val.length() == 0) m_dbAttribs[16].setValue(null); else m_dbAttribs[16].setValue(val); } public void set_total_payments_posted(String val) { if (val == null || val.length() == 0) m_dbAttribs[17].setValue(null); else m_dbAttribs[17].setValue(val); } public void set_vendor_id(String val) { if (val == null || val.length() == 0) m_dbAttribs[18].setValue(null); else m_dbAttribs[18].setValue(val); } public void set_vendor_name(String val) { if (val == null || val.length() == 0) m_dbAttribs[19].setValue(null); else m_dbAttribs[19].setValue(val); } public void set_payment_due_date(String val) { if (val == null || val.length() == 0) m_dbAttribs[20].setValue(null); else m_dbAttribs[20].setValue(val); } public void set_payment_terms(String val) { if (val == null || val.length() == 0) m_dbAttribs[21].setValue(null); else m_dbAttribs[21].setValue(val); } public void set_date_paid(String val) { if (val == null || val.length() == 0) m_dbAttribs[22].setValue(null); else m_dbAttribs[22].setValue(val); } public void set_pay_from_acct_id(String val) { if (val == null || val.length() == 0) m_dbAttribs[23].setValue(null); else m_dbAttribs[23].setValue(val); } public void set_pay_from_acct_name(String val) { if (val == null || val.length() == 0) m_dbAttribs[24].setValue(null); else m_dbAttribs[24].setValue(val); } public void set_total_shipping_charges(String val) { if (val == null || val.length() == 0) m_dbAttribs[25].setValue(null); else m_dbAttribs[25].setValue(val); } public void set_subtotal_amt(String val) { if (val == null || val.length() == 0) m_dbAttribs[26].setValue(null); else m_dbAttribs[26].setValue(val); } public void set_check_tot_amt_for_printing(String val) { if (val == null || val.length() == 0) m_dbAttribs[27].setValue(null); else m_dbAttribs[27].setValue(val); } public void set_check_tot_amt_text_for_printing(String val) { if (val == null || val.length() == 0) m_dbAttribs[28].setValue(null); else m_dbAttribs[28].setValue(val); } public void set_vendor_addr1(String val) { if (val == null || val.length() == 0) m_dbAttribs[29].setValue(null); else m_dbAttribs[29].setValue(val); } public void set_vendor_addr2(String val) { if (val == null || val.length() == 0) m_dbAttribs[30].setValue(null); else m_dbAttribs[30].setValue(val); } public void set_vendor_addr3(String val) { if (val == null || val.length() == 0) m_dbAttribs[31].setValue(null); else m_dbAttribs[31].setValue(val); } public void set_vendor_addr4(String val) { if (val == null || val.length() == 0) m_dbAttribs[32].setValue(null); else m_dbAttribs[32].setValue(val); } public void set_vendor_city(String val) { if (val == null || val.length() == 0) m_dbAttribs[33].setValue(null); else m_dbAttribs[33].setValue(val); } public void set_vendor_state_code(String val) { if (val == null || val.length() == 0) m_dbAttribs[34].setValue(null); else m_dbAttribs[34].setValue(val); } public void set_vendor_zip(String val) { if (val == null || val.length() == 0) m_dbAttribs[35].setValue(null); else m_dbAttribs[35].setValue(val); } public void set_vendor_country_code(String val) { if (val == null || val.length() == 0) m_dbAttribs[36].setValue(null); else m_dbAttribs[36].setValue(val); } public void set_vendor_country_name(String val) { if (val == null || val.length() == 0) m_dbAttribs[37].setValue(null); else m_dbAttribs[37].setValue(val); } public void set_our_acct_no_with_vendor(String val) { if (val == null || val.length() == 0) m_dbAttribs[38].setValue(null); else m_dbAttribs[38].setValue(val); } public void set_is_voided(String val) { if (val == null || val.length() == 0) m_dbAttribs[39].setValue(null); else m_dbAttribs[39].setValue(val); } public void set_date_check_sent(String val) { if (val == null || val.length() == 0) m_dbAttribs[40].setValue(null); else m_dbAttribs[40].setValue(val); } public BusinessObject getNewInstance() { return new payment_voucherObj(); } }
// // $Id$ package com.threerings.bang.gang.client; import com.threerings.presents.client.InvocationService; import com.threerings.presents.data.ClientObject; import com.threerings.bang.data.AvatarInfo; import com.threerings.bang.data.BucklePart; import com.threerings.bang.data.Handle; import com.threerings.bang.gang.data.GangGood; import com.threerings.bang.gang.data.OutfitArticle; /** * The interface through which peers make requests on the behalf of users to the peer that * currently hosts their gang object. */ public interface GangPeerService extends InvocationService<ClientObject> { /** * Grants aces to a player's gang. */ public void grantAces (Handle handle, int aces); /** * Sets the avatar of the gang's senior leader. */ public void setAvatar (int playerId, AvatarInfo info); /** * Called when a member enters the Hideout on any server. */ public void memberEnteredHideout (Handle handle, AvatarInfo info); /** * Called when a member leaves the Hideout on any server. */ public void memberLeftHideout (Handle handle); /** * Invites a user into the gang. */ public void inviteMember (Handle handle, Handle target, String message, ConfirmListener listener); /** * Handles the response to an invitation to join. */ public void handleInviteResponse (Handle handle, int playerId, Handle inviter, boolean accept, ConfirmListener listener); /** * Handles a remote member's request to speak on the gang object. */ public void sendSpeak (Handle handle, String message, byte mode); /** * Sets the gang's statement and URL. */ public void setStatement (Handle handle, String statement, String url, ConfirmListener listener); /** * Sets the gang's buckle. */ public void setBuckle (Handle handle, BucklePart[] parts, ConfirmListener listener); /** * Adds to the gang's coffers. */ public void addToCoffers (Handle handle, String coinAccount, int scrip, int coins, ConfirmListener listener); /** * Reserves scrip to be used in an exchange offer. */ public void reserveScrip (int scrip, ConfirmListener listener); /** * Grants scrip from a failed exchange offer. */ public void grantScrip (int scrip); /** * Tells a gang to update it's coin count. */ public void updateCoins (); /** * Logs a completed exchange transaction in the gang history. */ public void tradeCompleted (int price, int vol, String member); /** * Removes a player from the gang. */ public void removeFromGang (Handle handle, Handle target, ConfirmListener listener); /** * Changes a member's rank. */ public void changeMemberRank (Handle handle, Handle target, byte rank, ConfirmListener listener); /** * Changes a member's title. */ public void changeMemberTitle (Handle handle, Handle target, int title, ConfirmListener listener); /** * Gets a quote for or buys the specified gang articles. */ public void processOutfits (Handle handle, OutfitArticle[] outfit, boolean buy, boolean admin, ResultListener listener); /** * Purchases a good for the gang. */ public void buyGangGood (Handle handle, String type, Object[] args, boolean admin, ConfirmListener listener); /** * Purchases a good for the gang. */ public void rentGangGood (Handle handle, String type, Object[] args, boolean admin, ConfirmListener listener); /** * Renews a ranted gang item. */ public void renewGangItem (Handle handle, int itemId, ConfirmListener listener); /** * Broadcasts a message to all online members. */ public void broadcastToMembers (Handle handle, String message, ConfirmListener listener); /** * Gets a quote for a gang upgrade. */ public void getUpgradeQuote (Handle handle, GangGood good, ResultListener listener); }
package flounder.helpers; /** * A helper for creating a simple single type. * * @param <FIRST> The object in the single. */ public class Single<FIRST> { private FIRST single; /** * Creates a null pair. */ public Single() { this(null); } /** * Creates a filled single. * * @param single The single value. */ public Single(FIRST single) { this.single = single; } /** * Gets the single value. * * @return The single value. */ public FIRST getSingle() { return single; } /** * Sets the single value. * * @param single The single value. */ public void setSingle(FIRST single) { this.single = single; } @Override public String toString() { return "Single{" + "single=" + single + '}'; } }
package net.demilich.metastone.gui.simulationmode; import java.util.ArrayList; import java.util.List; import javafx.application.Platform; import net.demilich.metastone.GameNotification; import net.demilich.metastone.game.decks.Deck; import net.demilich.metastone.utils.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.pferdimanzug.nittygrittymvc.Mediator; import de.pferdimanzug.nittygrittymvc.interfaces.INotification; public class SimulationMediator extends Mediator<GameNotification> { public static final String NAME = "SimulationMediator"; private static Logger logger = LoggerFactory.getLogger(SimulationMediator.class); private final SimulationModeConfigView view; private final WaitForSimulationView waitView; private final SimulationResultView resultView; public SimulationMediator() { super(NAME); view = new SimulationModeConfigView(); waitView = new WaitForSimulationView(); resultView = new SimulationResultView(); } @Override @SuppressWarnings("unchecked") public void handleNotification(final INotification<GameNotification> notification) { switch (notification.getId()) { case REPLY_DECKS: List<Deck> decks = (List<Deck>) notification.getBody(); view.injectDecks(decks); break; case COMMIT_SIMULATIONMODE_CONFIG: getFacade().sendNotification(GameNotification.SHOW_MODAL_DIALOG, waitView); getFacade().sendNotification(GameNotification.SIMULATE_GAMES, notification.getBody()); break; case SIMULATION_PROGRESS_UPDATE: Tuple<Integer, Integer> progress = (Tuple<Integer, Integer>) notification.getBody(); Platform.runLater(new Runnable() { @Override public void run() { waitView.update(progress.getFirst(), progress.getSecond()); } }); break; case SIMULATION_RESULT: Platform.runLater(new Runnable() { @Override public void run() { waitView.getScene().getWindow().hide(); SimulationResult result = (SimulationResult) notification.getBody(); resultView.showSimulationResult(result); getFacade().sendNotification(GameNotification.SHOW_VIEW, resultView); } }); break; default: logger.warn("Unhandled notification {} in {}", notification, getClass().getSimpleName()); break; } } @Override public List<GameNotification> listNotificationInterests() { List<GameNotification> notificationInterests = new ArrayList<GameNotification>(); notificationInterests.add(GameNotification.REPLY_DECKS); notificationInterests.add(GameNotification.COMMIT_SIMULATIONMODE_CONFIG); notificationInterests.add(GameNotification.SIMULATION_PROGRESS_UPDATE); notificationInterests.add(GameNotification.SIMULATION_RESULT); return notificationInterests; } @Override public void onRegister() { getFacade().sendNotification(GameNotification.SHOW_VIEW, view); getFacade().sendNotification(GameNotification.REQUEST_DECKS); } }
package server.sec; import javax.net.ssl.*; import java.io.*; import java.security.KeyStore; import java.security.MessageDigest; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class InstallCert { private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); public static void main(String[] args) throws Exception { String host; int port; char[] passphrase; if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { System.out.println("Usage: java InstallCert <host>[:port] [passphrase]"); return; } File file = new File("jssecacerts"); if (!file.isFile()) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); file = new File(dir, "jssecacerts"); if (!file.isFile()) { file = new File(dir, "cacerts"); } } System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[]{tm}, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println (" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]"); String line = reader.readLine().trim(); int k; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { System.out.println("KeyStore not changed"); return; } X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println ("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'"); } private static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 3); for (int b : bytes) { b &= 0xff; sb.append(HEXDIGITS[b >> 4]); sb.append(HEXDIGITS[b & 15]); sb.append(' '); } return sb.toString(); } private static class SavingTrustManager implements X509TrustManager { private final X509TrustManager tm; private X509Certificate[] chain; SavingTrustManager(X509TrustManager tm) { this.tm = tm; } public X509Certificate[] getAcceptedIssuers() { throw new UnsupportedOperationException(); } public void checkClientTrusted(X509Certificate[] chain, String authType) { throw new UnsupportedOperationException(); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { this.chain = chain; tm.checkServerTrusted(chain, authType); } } }
package imininbi.utils.ntrc; import lombok.val; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.math.BigInteger; import static imininbi.utils.ntrc.Gender.*; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; @RunWith(Parameterized.class) public class NumberToRussianTextWithTargetNounTest { public static final Noun PENCIL = Noun .withGender(MASCULINE) .withOneText("карандаш") .withTwoToFourText("карандаша") .withZeroOrMoreThenFourText("карандашей") .build(); public static final Noun CLOUD = Noun .withGender(NEUTER) .withOneText("облако") .withTwoToFourText("облака") .withZeroOrMoreThenFourText("облаков") .build(); public static final Noun CAT = Noun .withGender(FEMININE) .withOneText("кошка") .withTwoToFourText("кошки") .withZeroOrMoreThenFourText("кошек") .build(); private final Noun noun; private final BigInteger input; private final String expected; public NumberToRussianTextWithTargetNounTest(String input, Noun noun, String expected) { this.noun = noun; this.input = new BigInteger(input); this.expected = expected; } @Test public void test() throws Exception { val actual = new NumberToRussianText().transform(input, noun); assertThat(actual, equalTo(expected)); } @Parameterized.Parameters public static Iterable<Object[]> parameters() { return asList(new Object[][]{ /*0*/ {"0", PENCIL, "ноль карандашей"}, /*1*/ {"1", PENCIL, "один карандаш"}, /*2*/ {"11", PENCIL, "одиннадцать карандашей"}, /*3*/ {"21", PENCIL, "двадцать один карандаш"}, /*4*/ {"20", PENCIL, "двадцать карандашей"}, /*5*/ {"94", PENCIL, "девяносто четыре карандаша"}, /*6*/ {"101", PENCIL, "сто один карандаш"}, /*7*/ {"2123", PENCIL, "две тысячи сто двадцать три карандаша"}, /*8*/ {"1002", PENCIL, "одна тысяча два карандаша"}, /*9*/ {"1000", PENCIL, "одна тысяча карандашей"}, /*10*/ {"01000", PENCIL, "одна тысяча карандашей"}, /*11*/ {"1000000", PENCIL, "один миллион карандашей"}, /*12*/ {"1001000", PENCIL, "один миллион одна тысяча карандашей"}, /*13*/ {"112354687", PENCIL, "сто двенадцать миллионов триста пятьдесят четыре тысячи шестьсот восемьдесят семь карандашей"}, /*14*/ {"78944965241000000005541462378", PENCIL, "семьдесят восемь октиллионов девятьсот сорок четыре септиллиона девятьсот шестьдесят пять секстиллионов двести сорок один квинтиллион пять миллиардов пятьсот сорок один миллион четыреста шестьдесят две тысячи триста семьдесят восемь карандашей"}, /*16*/ {"1", CLOUD, "одно облако"}, /*17*/ {"2", CLOUD, "два облака"}, /*18*/ {"5", CLOUD, "пять облаков"}, /*19*/ {"11", CLOUD, "одиннадцать облаков"}, /*20*/ {"1000100", CLOUD, "один миллион сто облаков"}, /*21*/ {"1", CAT, "одна кошка"}, /*22*/ {"2", CAT, "две кошки"}, /*23*/ {"5", CAT, "пять кошек"}, /*24*/ {"11", CAT, "одиннадцать кошек"}, /*25*/ {"1000100", CAT, "один миллион сто кошек"}, /*26*/ {"1000101", CAT, "один миллион сто одна кошка"}, }); } }
package org.elasticsearch.test.action.admin.cluster.snapshots.status; /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexShardStage; import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexShardStatus; import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotStatus; import org.elasticsearch.cluster.SnapshotsInProgress; import org.elasticsearch.common.UUIDs; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.snapshots.Snapshot; import org.elasticsearch.snapshots.SnapshotId; import org.elasticsearch.testframework.ESTestCase; import java.util.ArrayList; import java.util.List; public class SnapshotStatusTests extends ESTestCase { public void testToString() throws Exception { SnapshotsInProgress.State state = randomFrom(SnapshotsInProgress.State.values()); String uuid = UUIDs.randomBase64UUID(); SnapshotId id = new SnapshotId("test-snap", uuid); Snapshot snapshot = new Snapshot("test-repo", id); String indexName = randomAlphaOfLengthBetween(3, 50); int shardId = randomInt(); ShardId testShardId = ShardId.fromString("[" + indexName + "][" + shardId + "]"); SnapshotIndexShardStage shardStage = randomFrom(SnapshotIndexShardStage.values()); SnapshotIndexShardStatus snapshotIndexShardStatus = new SnapshotIndexShardStatus(testShardId, shardStage); List<SnapshotIndexShardStatus> snapshotIndexShardStatuses = new ArrayList<>(); snapshotIndexShardStatuses.add(snapshotIndexShardStatus); boolean includeGlobalState = randomBoolean(); SnapshotStatus status = new SnapshotStatus(snapshot, state, snapshotIndexShardStatuses, includeGlobalState); int initializingShards = 0; int startedShards = 0; int finalizingShards = 0; int doneShards = 0; int failedShards = 0; int totalShards = 1; switch (shardStage) { case INIT: initializingShards++; break; case STARTED: startedShards++; break; case FINALIZE: finalizingShards++; break; case DONE: doneShards++; break; case FAILURE: failedShards++; break; default: break; } String expected = "{\n" + " \"snapshot\" : \"test-snap\",\n" + " \"repository\" : \"test-repo\",\n" + " \"uuid\" : \"" + uuid + "\",\n" + " \"state\" : \"" + state.toString() + "\",\n" + " \"include_global_state\" : " + includeGlobalState + ",\n" + " \"shards_stats\" : {\n" + " \"initializing\" : " + initializingShards + ",\n" + " \"started\" : " + startedShards + ",\n" + " \"finalizing\" : " + finalizingShards + ",\n" + " \"done\" : " + doneShards + ",\n" + " \"failed\" : " + failedShards + ",\n" + " \"total\" : " + totalShards + "\n" + " },\n" + " \"stats\" : {\n" + " \"number_of_files\" : 0,\n" + " \"processed_files\" : 0,\n" + " \"total_size_in_bytes\" : 0,\n" + " \"processed_size_in_bytes\" : 0,\n" + " \"start_time_in_millis\" : 0,\n" + " \"time_in_millis\" : 0\n" + " },\n" + " \"indices\" : {\n" + " \"" + indexName + "\" : {\n" + " \"shards_stats\" : {\n" + " \"initializing\" : " + initializingShards + ",\n" + " \"started\" : " + startedShards + ",\n" + " \"finalizing\" : " + finalizingShards + ",\n" + " \"done\" : " + doneShards + ",\n" + " \"failed\" : " + failedShards + ",\n" + " \"total\" : " + totalShards + "\n" + " },\n" + " \"stats\" : {\n" + " \"number_of_files\" : 0,\n" + " \"processed_files\" : 0,\n" + " \"total_size_in_bytes\" : 0,\n" + " \"processed_size_in_bytes\" : 0,\n" + " \"start_time_in_millis\" : 0,\n" + " \"time_in_millis\" : 0\n" + " },\n" + " \"shards\" : {\n" + " \"" + shardId + "\" : {\n" + " \"stage\" : \"" + shardStage.toString() + "\",\n" + " \"stats\" : {\n" + " \"number_of_files\" : 0,\n" + " \"processed_files\" : 0,\n" + " \"total_size_in_bytes\" : 0,\n" + " \"processed_size_in_bytes\" : 0,\n" + " \"start_time_in_millis\" : 0,\n" + " \"time_in_millis\" : 0\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; assertEquals(expected, status.toString()); } }
/* * Copyright 2019, 2020 grondag * * 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 grondag.canvas.texture; import it.unimi.dsi.fastutil.Hash; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntConsumer; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.client.texture.Sprite; import net.minecraft.client.texture.SpriteAtlasTexture; import net.minecraft.client.texture.SpriteAtlasTexture.Data; import net.minecraft.util.Identifier; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.renderer.v1.model.SpriteFinder; import grondag.canvas.CanvasMod; import grondag.canvas.config.Configurator; import grondag.canvas.mixinterface.SpriteAtlasTextureDataExt; import grondag.canvas.mixinterface.SpriteAtlasTextureExt; import grondag.canvas.mixinterface.SpriteExt; @Environment(EnvType.CLIENT) public class SpriteIndex { private static final Object2ObjectOpenHashMap<Identifier, SpriteIndex> MAP = new Object2ObjectOpenHashMap<>(64, Hash.VERY_FAST_LOAD_FACTOR); public static final SpriteIndex getOrCreate(Identifier id) { return MAP.computeIfAbsent(id, SpriteIndex::new); } private ObjectArrayList<Sprite> spriteIndex = null; private final IntArrayList spriteAnimationIndex = new IntArrayList(); private SpriteAtlasTexture atlas; private IntConsumer canvas_frameAnimationConsumer; private ResourceCache<SpriteFinder> spriteFinder; private int atlasWidth; private int atlasHeight; public final Identifier id; private SpriteIndex(Identifier id) { this.id = id; spriteFinder = new ResourceCache<>(this::loadSpriteFinder); } private SpriteFinder loadSpriteFinder() { return SpriteFinder.get(atlas); } public void reset(Data dataIn, ObjectArrayList<Sprite> spriteIndexIn, SpriteAtlasTexture atlasIn) { if (Configurator.enableLifeCycleDebug || Configurator.traceTextureLoad) { CanvasMod.LOG.info("Lifecycle Event: SpriteIndex reset"); } atlas = atlasIn; canvas_frameAnimationConsumer = ((SpriteAtlasTextureExt) atlasIn).canvas_frameAnimationConsumer(); spriteIndex = spriteIndexIn; atlasWidth = ((SpriteAtlasTextureDataExt) dataIn).canvas_atlasWidth(); atlasHeight = ((SpriteAtlasTextureDataExt) dataIn).canvas_atlasHeight(); spriteAnimationIndex.clear(); for (final var sprite : spriteIndexIn) { spriteAnimationIndex.add(((SpriteExt) sprite).canvas_animationIndex()); } } public Sprite fromId(int spriteId) { return spriteIndex.get(spriteId); } public int animationIndexFromSpriteId(int spriteId) { return spriteAnimationIndex.getInt(spriteId); } public float mapU(int spriteId, float unmappedU) { final Sprite sprite = spriteIndex.get(spriteId); final float u0 = sprite.getMinU(); return u0 + unmappedU * (sprite.getMaxU() - u0); } public float mapV(int spriteId, float unmappedV) { final Sprite sprite = spriteIndex.get(spriteId); final float v0 = sprite.getMinV(); return v0 + unmappedV * (sprite.getMaxV() - v0); } public int atlasWidth() { return atlasWidth; } public int atlasHeight() { return atlasHeight; } public SpriteAtlasTexture atlas() { return atlas; } public SpriteFinder spriteFinder() { return spriteFinder.getOrLoad(); } public void trackPerFrameAnimation(int spriteId) { final int animationIndex = animationIndexFromSpriteId(spriteId); if (animationIndex >= 0) { canvas_frameAnimationConsumer.accept(animationIndex); } } }
package headfirst.combining.adapter; public class DuckSimulator { public static void main(String[] args) { DuckSimulator simulator = new DuckSimulator(); simulator.simulate(); } void simulate() { Quackable mallardDuck = new MallardDuck(); Quackable redheadDuck = new RedheadDuck(); Quackable duckCall = new DuckCall(); Quackable rubberDuck = new RubberDuck(); Quackable gooseDuck = new GooseAdapter(new Goose()); System.out.println("\nDuck Simulator: With Goose Adapter"); simulate(mallardDuck); simulate(redheadDuck); simulate(duckCall); simulate(rubberDuck); simulate(gooseDuck); } void simulate(Quackable duck) { duck.quack(); } }
package com.bxtel.security5.filter; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import javax.annotation.Resource; import javax.servlet.*; import javax.servlet.http.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RegexRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; import com.bxtel.security5.auth.*; import com.bxtel.security5.auth.exceiption.AccessDeniedException; import com.bxtel.security5.auth.exceiption.AccountIsNotAuthenticatedException; import com.bxtel.security5.auth.exceiption.UserNotLogin; //public boolean supports(Class<?> clazz) { //return FilterInvocation.class.isAssignableFrom(clazz); //} public class FilterSecurityInterceptorFilter extends GenericFilterBean { private static final Log logger = LogFactory.getLog(FilterSecurityInterceptorFilter.class); //需要保护的资源 @Resource private ISecurityMetadataSource securityMetadataSource; @Resource MySecurityContextHolder mySecurityContextHolder; private boolean checkRole=true; public boolean isCheckRole() { return checkRole; } public void setCheckRole(boolean checkRole) { this.checkRole = checkRole; } private String pathtype="ant"; public String getPathtype() { return pathtype; } public void setPathtype(String pathtype) { this.pathtype = pathtype; } public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) throws IOException, ServletException { HttpServletRequest servletRequest = (HttpServletRequest) request; HttpServletResponse servletResponse = (HttpServletResponse) response; logger.debug("request url :"+servletRequest.getRequestURI()); //只检查需要角色的资源 Collection<IConfigAttribute> roles = securityMetadataSource.getAttributes(servletRequest); if(roles!=null) { IAuthenticationResponse auth =mySecurityContextHolder.getSecurityContext(servletRequest); if(auth==null) { throw new AccountIsNotAuthenticatedException("user is not Authenticated"); } if(isCheckRole()) { Collection<? extends IGrantedAuthority> authorities = auth.getAuthorities(); if(authorities==null) { throw new AccessDeniedException("Access is denied : user have no privilege in path "+servletRequest.getRequestURI()); } if(!decide(roles,authorities)) { throw new AccessDeniedException("Access is denied"); } } } else{ logger.debug("url need not sercurity :"+servletRequest.getRequestURI()); } filterChain.doFilter(request, response); } public boolean decide(Collection<IConfigAttribute> configroles,Collection<? extends IGrantedAuthority> authorities) { for(IConfigAttribute config:configroles) { Iterator<? extends IGrantedAuthority> it = authorities.iterator(); while(it.hasNext()) { IGrantedAuthority ga = it.next(); if(config.getAttribute().equals(ga.getAuthority())) { return true; } } } return false; } } /* Spring security防用户重复登录 使用Spring security如何防止用户的重复登录呢?如果用户账号已登录,这时再进行第二次或多次登录,需要阻止这样的多次登录。 一.在web.xml中配置listener <listener> <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class> </listener> 二.在security.xml中配置Hibernate ORM提供了三种继承映射策略 <session-management> <concurrency-control max-sessions="1" error-if-maximum-exceeded="true"/> </session-management> max-sessions表示最多允许多少次重复登录。如果没有配置error-if-maximum-exceeded,那么用户账号的第二次登录会使第一次登录失效,而配置了的话,那么第二次登录会被阻止。通常的做法是阻止第二次登录。 */
package com.aliyun.roompaas.app.activity; import android.os.Bundle; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import com.aliyun.roompaas.app.Const; import com.aliyun.roompaas.app.R; import com.aliyun.roompaas.app.activity.base.BaseActivity; import com.aliyun.roompaas.app.helper.DoubleTripleClick; import com.aliyun.roompaas.app.helper.RoomHelper; import com.aliyun.roompaas.app.helper.Router; import com.aliyun.roompaas.app.helper.UserHelper; import com.aliyun.roompaas.app.sensitive.AllSensitive; import com.aliyun.roompaas.app.sp.SpHelper; import com.aliyun.roompaas.app.sp.UserSp; import com.aliyun.roompaas.app.util.DialogUtil; import com.aliyun.roompaas.base.exposable.Callback; import com.aliyun.roompaas.biz.RoomEngine; import com.aliyun.roompaas.uibase.util.ViewUtil; import java.util.concurrent.atomic.AtomicBoolean; /** * @author puke * @version 2021/5/13 */ public class CreateRoomActivity extends BaseActivity { private static final String TAG = CreateRoomActivity.class.getSimpleName(); private EditText userIdInput; private RoomEngine roomEngine; private View loginButton; private UserSp userSp; private String userId; private AtomicBoolean loginRequestFlowFinish = new AtomicBoolean(false); @Override protected void onCreate(Bundle savedInstanceState) { loadParamsFromCache(); roomEngine = RoomEngine.getInstance(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_room); userIdInput = findViewById(R.id.form_user_id); if (!TextUtils.isEmpty(userId)) { userIdInput.setText(userId); } loginButton = findViewById(R.id.loginButton); ViewUtil.bindClickActionWithClickCheck(loginButton, this::onLogin); AllSensitive.switchEnv(findViewById(R.id.env), this); DoubleTripleClick.addClickCallback(findViewById(R.id.roomTypeSwitch), new DoubleTripleClick.SimpleCallback() { @Override public void onTripleClick() { boolean isBusiness = RoomHelper.isTypeBusiness(); String title = "房间类型环境"; DialogUtil.doAction(context, title, getSwitchRoomTypeAction(isBusiness, "直播", Const.BIZ_TYPE.BUSINESS), getSwitchRoomTypeAction(!isBusiness, "课堂", Const.BIZ_TYPE.CLASSROOM)); } }); } @NonNull private DialogUtil.Action getSwitchRoomTypeAction(boolean isChecked, String itemText, String rooType) { return new DialogUtil.Action(itemText, () -> updateTypeSelected(rooType), isChecked); } private void updateTypeSelected(@Const.BIZ_TYPE String bizType) { AllSensitive.showRelaunchAppConfirmDialog(context, RoomHelper.isTypeSameWithCurrent(bizType) , () -> RoomHelper.updateTypeSelected(bizType)); } private void loadParamsFromCache() { userSp = SpHelper.getInstance(UserSp.class); userId = UserHelper.parseUserId(userSp); } public void onLogin() { if (!roomEngine.isInit()) { showToast("当前未初始化成功, 请稍等"); return; } if (roomEngine.isLogin()) { guideToListPage(); return; } this.userId = userIdInput.getText().toString().trim(); if (TextUtils.isEmpty(userId)) { showToast("输入有效id"); return; } disableInput(); loginRequestFlowFinish.set(false); roomEngine.auth(userId, new Callback<Void>() { @Override public void onSuccess(Void data) { if (loginRequestFlowFinish.get()) { return; } loginSuccessProcess(); enableInput(); loginRequestFlowFinish.set(true); } @Override public void onError(String errorMsg) { if (loginRequestFlowFinish.get()) { return; } showToast("登录失败: " + errorMsg); enableInput(); loginRequestFlowFinish.set(true); } }); } private void disableInput() { ViewUtil.disableView(userIdInput, loginButton); } private void enableInput() { ViewUtil.enableView(userIdInput, loginButton); } private void loginSuccessProcess() { Const.currentUserId = userId; userSp.setUserId(userId); showToast("登录成功"); guideToListPage(); } private void guideToListPage() { Router.openRoomListPage(context); } }
package me.jingbin.bymvvm.utils; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import androidx.core.content.ContextCompat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import me.jingbin.bymvvm.base.RootApplication; /** * 获取原生资源 */ public class CommonUtils { /** * 随机颜色 */ public static int randomColor() { Random random = new Random(); int red = random.nextInt(150) + 50;//50-199 int green = random.nextInt(150) + 50;//50-199 int blue = random.nextInt(150) + 50;//50-199 return Color.rgb(red, green, blue); } /** * 得到年月日的"日" */ private String getDate() { Date date = new Date(); SimpleDateFormat dateFm = new SimpleDateFormat("dd"); return dateFm.format(date); } public static Drawable getDrawable(int resid) { return ContextCompat.getDrawable(RootApplication.getContext(), resid); // return getResoure().getDrawable(resid); } public static int getColor(int resid) { return getResoure().getColor(resid); } public static Resources getResoure() { return RootApplication.getContext().getResources(); } public static String[] getStringArray(int resid) { return getResoure().getStringArray(resid); } public static String getString(int resid) { return getResoure().getString(resid); } public static float getDimens(int resId) { return getResoure().getDimension(resId); } public static void removeSelfFromParent(View child) { if (child != null) { ViewParent parent = child.getParent(); if (parent instanceof ViewGroup) { ViewGroup group = (ViewGroup) parent; group.removeView(child); } } } }
/* * Copyright 2018 Confluent Inc. * * Licensed under the Confluent Community License (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.confluent.io/confluent-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package io.confluent.ksql.datagen; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import io.confluent.avro.random.generator.Generator; import io.confluent.connect.avro.AvroData; import io.confluent.ksql.GenericRow; import io.confluent.ksql.util.Pair; import java.io.File; import java.io.IOException; import java.util.Properties; import java.util.Random; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.Schema.Type; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import org.junit.Test; public class RowGeneratorTest { @Test public void shouldGenerateCorrectRow() throws IOException { final Generator generator = new Generator(new File("./src/main/resources/orders_schema.avro"), new Random()); final Schema addressSchema = SchemaBuilder.struct() .field("city", Schema.OPTIONAL_STRING_SCHEMA) .field("state", Schema.OPTIONAL_STRING_SCHEMA) .field("zipcode", Schema.OPTIONAL_INT64_SCHEMA) .optional().build(); final Schema ordersSchema = SchemaBuilder.struct() .field("ordertime", Schema.OPTIONAL_INT64_SCHEMA) .field("orderid", Schema.OPTIONAL_INT32_SCHEMA) .field("itemid", Schema.OPTIONAL_STRING_SCHEMA) .field("orderunits", Schema.OPTIONAL_FLOAT64_SCHEMA) .field("address", addressSchema) .optional().build(); final RowGenerator rowGenerator = new RowGenerator( generator, new AvroData(1), generator.schema(), ordersSchema, new SessionManager(), "orderid"); final Pair<String, GenericRow> rowPair = rowGenerator.generateRow(); assertThat(rowPair.getLeft(), instanceOf(String.class)); assertThat(rowPair.getRight().getColumns().size(), equalTo(5)); assertThat(rowPair.getRight().getColumns().get(4), instanceOf(Struct.class)); final Struct struct = (Struct) rowPair.getRight().getColumns().get(4); assertThat(struct.schema().fields().size(), equalTo(3)); assertThat(struct.schema().field("city").schema().type(), equalTo(Type.STRING)); assertThat(struct.schema().field("state").schema().type(), equalTo(Type.STRING)); assertThat(struct.schema().field("zipcode").schema().type(), equalTo(Type.INT64)); } }
/* * Copyright (c) 2020 Thomas Neidhart * * 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.netomi.tictactoe.model; import io.reactivex.Observable; import io.reactivex.subjects.PublishSubject; public class Game { private final Board board; private Player currentPlayer; private int numberOfMoves; private GameResult gameResult; private Player winner; private final PublishSubject<GameEvent> gameEvents; public Game() { board = new Board(); currentPlayer = Player.PLAYER_1; numberOfMoves = 0; gameResult = GameResult.UNDECIDED; winner = null; gameEvents = PublishSubject.create(); } public Observable<GameEvent> getGameEvents() { return gameEvents.hide(); } public Board getBoard() { return board.copy(); } public boolean isCellEmpty(int row, int column) { return board.isCellEmpty(row, column); } public Player getCurrentPlayer() { return currentPlayer; } public boolean hasFinished() { return gameResult != GameResult.UNDECIDED; } public void makeMove(int row, int column) { if (gameResult.isGameFinished()) { throw new IllegalArgumentException(String.format("game is already finished")); } // make move board.makeMove(row, column, currentPlayer); gameEvents.onNext(GameEvent.newMadeMoveEvent(currentPlayer, row, column)); // check game result status numberOfMoves++; updateGameResult(); if (gameResult.isGameFinished()) { gameEvents.onNext(GameEvent.newGameFinishedEvent(gameResult, winner)); } else { // switch players currentPlayer = currentPlayer.nextPlayer(); gameEvents.onNext(GameEvent.newPlayerSwitchedEvent(currentPlayer)); } } private void updateGameResult() { Board.EvaluationResult result = board.evaluate(); Player winningPlayer = result.hasWinner() ? Player.of(result.getSymbol()) : null; if (winningPlayer != null) { gameResult = GameResult.GAME_WON; winner = winningPlayer; } else if (numberOfMoves == board.getCellCount()) { gameResult = GameResult.GAME_DRAWN; winner = null; } else { gameResult = GameResult.UNDECIDED; winner = null; } } public GameResult getGameResult() { return gameResult; } public Player getWinner() { return winner; } public void reset() { board.reset(); numberOfMoves = 0; gameResult = GameResult.UNDECIDED; winner = null; gameEvents.onNext(GameEvent.newBoardClearedEvent()); currentPlayer = Player.PLAYER_1; gameEvents.onNext(GameEvent.newPlayerSwitchedEvent(currentPlayer)); } @Override public String toString() { return board.toString(); } }
import nhlstats.NHLStatistics; public class Main { public static void main(String[] args) { System.out.println("Top ten by points: "); NHLStatistics.sortByGoals(); NHLStatistics.top(10); System.out.println("Top 25 by penalties: "); NHLStatistics.sortByPenalties(); NHLStatistics.top(25); System.out.println("Statistics of Sidney Crosby: "); NHLStatistics.sortByGoals(); NHLStatistics.searchByPlayer("Sidney Crosby"); System.out.println("Statistics for Philadelphia Flyers: "); NHLStatistics.teamStatistics("PHI"); System.out.println("The players of Anaheim Ducks: "); NHLStatistics.sortByPoints(); NHLStatistics.teamStatistics("ANA"); } }
package unipi.di.socc.ramp.cli.parser.wrappers; import java.util.ArrayList; import java.util.List; import java.util.Map; public class PlanOrSequenceWrapper { private final Map<String, ActionWrapper> actions; private List<ConstraintWrapper> partialOrder; public PlanOrSequenceWrapper( Map<String, ActionWrapper> actions, List<ConstraintWrapper> partialOrder ){ this.actions = actions; this.partialOrder = partialOrder; } public void initializePartialOrdering(){ this.partialOrder = new ArrayList<>(); } public Map<String, ActionWrapper> getActions() { return actions; } public List<ConstraintWrapper> getPartialOrderWrap() { return partialOrder; } }
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.transport.http.netty.contractimpl.common.states; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2CodecUtil; import io.netty.handler.codec.http2.Http2Connection; import io.netty.handler.codec.http2.Http2ConnectionEncoder; import io.netty.handler.codec.http2.Http2Error; import io.netty.handler.codec.http2.Http2Exception; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.HttpConversionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wso2.transport.http.netty.contract.Constants; import org.wso2.transport.http.netty.contract.HttpResponseFuture; import org.wso2.transport.http.netty.contract.ServerConnectorFuture; import org.wso2.transport.http.netty.contract.exceptions.ServerConnectorException; import org.wso2.transport.http.netty.contractimpl.Http2OutboundRespListener; import org.wso2.transport.http.netty.contractimpl.common.Util; import org.wso2.transport.http.netty.contractimpl.listener.http2.Http2SourceHandler; import org.wso2.transport.http.netty.contractimpl.listener.http2.InboundMessageHolder; import org.wso2.transport.http.netty.contractimpl.listener.states.http2.Response100ContinueSent; import org.wso2.transport.http.netty.contractimpl.listener.states.http2.SendingHeaders; import org.wso2.transport.http.netty.contractimpl.sender.http2.Http2ClientChannel; import org.wso2.transport.http.netty.contractimpl.sender.http2.Http2DataEventListener; import org.wso2.transport.http.netty.contractimpl.sender.http2.Http2TargetHandler; import org.wso2.transport.http.netty.contractimpl.sender.http2.OutboundMsgHolder; import org.wso2.transport.http.netty.contractimpl.sender.states.http2.RequestCompleted; import org.wso2.transport.http.netty.message.Http2DataFrame; import org.wso2.transport.http.netty.message.Http2InboundContentListener; import org.wso2.transport.http.netty.message.Http2PushPromise; import org.wso2.transport.http.netty.message.HttpCarbonMessage; import org.wso2.transport.http.netty.message.HttpCarbonRequest; import org.wso2.transport.http.netty.message.PooledDataStreamerFactory; import java.net.InetSocketAddress; import static org.wso2.transport.http.netty.contract.Constants.BASE_64_ENCODED_CERT; import static org.wso2.transport.http.netty.contract.Constants.CHNL_HNDLR_CTX; import static org.wso2.transport.http.netty.contract.Constants.HTTP_SCHEME; import static org.wso2.transport.http.netty.contract.Constants.IDLE_TIMEOUT_TRIGGERED_WHILE_READING_INBOUND_REQUEST_BODY; import static org.wso2.transport.http.netty.contract.Constants.IDLE_TIMEOUT_TRIGGERED_WHILE_READING_INBOUND_REQUEST_HEADERS; import static org.wso2.transport.http.netty.contract.Constants.INBOUND_REQUEST; import static org.wso2.transport.http.netty.contract.Constants.LISTENER_INTERFACE_ID; import static org.wso2.transport.http.netty.contract.Constants.LISTENER_PORT; import static org.wso2.transport.http.netty.contract.Constants.LOCAL_ADDRESS; import static org.wso2.transport.http.netty.contract.Constants.MUTUAL_SSL_HANDSHAKE_RESULT; import static org.wso2.transport.http.netty.contract.Constants.POOLED_BYTE_BUFFER_FACTORY; import static org.wso2.transport.http.netty.contract.Constants.PROMISED_STREAM_REJECTED_ERROR; import static org.wso2.transport.http.netty.contract.Constants.PROTOCOL; import static org.wso2.transport.http.netty.contract.Constants.TO; import static org.wso2.transport.http.netty.contractimpl.common.states.StateUtil.handleIncompleteInboundMessage; /** * HTTP/2 utility functions for states. * * @since 6.0.241 */ public class Http2StateUtil { private static final Logger LOG = LoggerFactory.getLogger(Http2StateUtil.class); /** * Notifies the registered listeners which listen for the incoming carbon messages. * * @param http2SourceHandler the HTTP2 source handler * @param inboundMessageHolder the inbound http request holder * @param streamId the id of the stream */ public static void notifyRequestListener(Http2SourceHandler http2SourceHandler, InboundMessageHolder inboundMessageHolder, int streamId) { HttpCarbonMessage httpRequestMsg = inboundMessageHolder.getInboundMsg(); if (http2SourceHandler.getServerConnectorFuture() != null) { try { ServerConnectorFuture outboundRespFuture = httpRequestMsg.getHttpResponseFuture(); Http2OutboundRespListener http2OutboundRespListener = new Http2OutboundRespListener( http2SourceHandler.getServerChannelInitializer(), httpRequestMsg, http2SourceHandler.getChannelHandlerContext(), http2SourceHandler.getConnection(), http2SourceHandler.getEncoder(), streamId, http2SourceHandler.getServerName(), http2SourceHandler.getRemoteAddress(), http2SourceHandler.getServerRemoteFlowControlListener(), http2SourceHandler.getHttp2ServerChannel()); outboundRespFuture.setHttpConnectorListener(http2OutboundRespListener); http2SourceHandler.getServerConnectorFuture().notifyHttpListener(httpRequestMsg); inboundMessageHolder.setHttp2OutboundRespListener(http2OutboundRespListener); } catch (Exception e) { LOG.error("Error while notifying listeners", e); } } else { LOG.error("Cannot find registered listener to forward the message"); } } /** * Creates a {@code HttpCarbonRequest} from HttpRequest. * * @param httpRequest the HTTPRequest message * @param http2SourceHandler the HTTP/2 source handler * @param streamId the stream id * @return the CarbonRequest Message created from given HttpRequest */ public static HttpCarbonRequest setupCarbonRequest(HttpRequest httpRequest, Http2SourceHandler http2SourceHandler, int streamId) { ChannelHandlerContext ctx = http2SourceHandler.getChannelHandlerContext(); HttpCarbonRequest sourceReqCMsg = new HttpCarbonRequest(httpRequest, new Http2InboundContentListener( streamId, ctx, http2SourceHandler.getConnection(), INBOUND_REQUEST)); sourceReqCMsg.setProperty(POOLED_BYTE_BUFFER_FACTORY, new PooledDataStreamerFactory(ctx.alloc())); sourceReqCMsg.setProperty(CHNL_HNDLR_CTX, ctx); sourceReqCMsg.setProperty(Constants.SRC_HANDLER, http2SourceHandler); HttpVersion protocolVersion = httpRequest.protocolVersion(); sourceReqCMsg.setHttpVersion(protocolVersion.majorVersion() + "." + protocolVersion.minorVersion()); sourceReqCMsg.setHttpMethod(httpRequest.method().name()); InetSocketAddress localAddress = null; //This check was added because in case of netty embedded channel, this could be of type 'EmbeddedSocketAddress'. if (ctx.channel().localAddress() instanceof InetSocketAddress) { localAddress = (InetSocketAddress) ctx.channel().localAddress(); } sourceReqCMsg.setProperty(LOCAL_ADDRESS, localAddress); sourceReqCMsg.setProperty(LISTENER_PORT, localAddress != null ? localAddress.getPort() : null); sourceReqCMsg.setProperty(LISTENER_INTERFACE_ID, http2SourceHandler.getInterfaceId()); sourceReqCMsg.setProperty(PROTOCOL, HTTP_SCHEME); sourceReqCMsg.setProperty(MUTUAL_SSL_HANDSHAKE_RESULT, ctx.channel().attr(Constants.MUTUAL_SSL_RESULT_ATTRIBUTE).get()); sourceReqCMsg.setProperty(BASE_64_ENCODED_CERT, ctx.channel().attr(Constants.BASE_64_ENCODED_CERT_ATTRIBUTE).get()); String uri = httpRequest.uri(); sourceReqCMsg.setRequestUrl(uri); sourceReqCMsg.setProperty(TO, uri); return sourceReqCMsg; } /** * Writes HTTP2 headers to outbound response. * * @param ctx the channel handler context * @param encoder the HTTP2 connection encoder * @param outboundRespStatusFuture the future of outbound response write operation * @param streamId the id of the stream * @param http2Headers the Http2Headers received over a HTTP/2 stream * @param endStream is this the end of stream * @param respListener http/2 outbound response listener * @throws Http2Exception throws if a protocol-related error occurred */ public static void writeHttp2ResponseHeaders(ChannelHandlerContext ctx, Http2ConnectionEncoder encoder, HttpResponseFuture outboundRespStatusFuture, int streamId, Http2Headers http2Headers, boolean endStream, Http2OutboundRespListener respListener) throws Http2Exception { for (Http2DataEventListener dataEventListener : respListener.getHttp2ServerChannel().getDataEventListeners()) { if (!dataEventListener.onHeadersWrite(ctx, streamId, http2Headers, endStream)) { break; } } if (endStream) { respListener.getHttp2ServerChannel().getStreamIdRequestMap().remove(streamId); } ChannelFuture channelFuture = encoder.writeHeaders( ctx, streamId, http2Headers, 0, endStream, ctx.newPromise()); encoder.flowController().writePendingBytes(); ctx.flush(); Util.addResponseWriteFailureListener(outboundRespStatusFuture, channelFuture, respListener); } /** * Writes an HTTP2 promise. * * @param pushPromise HTTP/2 promise message * @param ctx the channel handler context * @param conn HTTP2 connection * @param encoder the HTTP2 connection encoder * @param inboundRequestMsg request message received from the client * @param outboundRespStatusFuture the future of outbound response write operation * @param originalStreamId the original id of the stream * @throws Http2Exception throws if a protocol-related error occurred */ public static void writeHttp2Promise(Http2PushPromise pushPromise, ChannelHandlerContext ctx, Http2Connection conn, Http2ConnectionEncoder encoder, HttpCarbonMessage inboundRequestMsg, HttpResponseFuture outboundRespStatusFuture, int originalStreamId) throws Http2Exception { int promisedStreamId = getNextStreamId(conn); // Update streamIds pushPromise.setPromisedStreamId(promisedStreamId); pushPromise.setStreamId(originalStreamId); // Construct http request HttpRequest httpRequest = pushPromise.getHttpRequest(); httpRequest.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HTTP_SCHEME); // A push promise is a server initiated request, hence it should contain request headers Http2Headers http2Headers = HttpConversionUtil.toHttp2Headers(httpRequest, true); // Write the push promise to the wire ChannelFuture channelFuture = encoder.writePushPromise( ctx, originalStreamId, promisedStreamId, http2Headers, 0, ctx.newPromise()); encoder.flowController().writePendingBytes(); ctx.flush(); Util.checkForResponseWriteStatus(inboundRequestMsg, outboundRespStatusFuture, channelFuture); } /** * Validates the state of promised stream with the original stream id and given stream id. * * @param originalStreamId the original id of the stream * @param streamId the id of the stream to be validated * @param conn HTTP2 connection * @param inboundRequestMsg request message received from the client * @throws Http2Exception throws if stream id is not valid for given connection */ public static void validatePromisedStreamState(int originalStreamId, int streamId, Http2Connection conn, HttpCarbonMessage inboundRequestMsg) throws Http2Exception { if (streamId == originalStreamId) { // Not a promised stream, no need to validate return; } if (!isValidStreamId(streamId, conn)) { inboundRequestMsg.getHttpOutboundRespStatusFuture(). notifyHttpListener(new ServerConnectorException(PROMISED_STREAM_REJECTED_ERROR)); throw new Http2Exception(Http2Error.REFUSED_STREAM, PROMISED_STREAM_REJECTED_ERROR); } } /** * Checks for the validity of stream id. * * @param streamId the id of the stream * @param conn HTTP2 connection * @return whether the stream id is valid or not */ public static boolean isValidStreamId(int streamId, Http2Connection conn) { return conn.stream(streamId) != null; } /** * Releases the {@link io.netty.buffer.ByteBuf} content. * * @param http2SourceHandler the HTTP2 source handler * @param dataFrame the HTTP2 data frame to be released */ public static void releaseDataFrame(Http2SourceHandler http2SourceHandler, Http2DataFrame dataFrame) { int streamId = dataFrame.getStreamId(); HttpCarbonMessage sourceReqCMsg = http2SourceHandler.getStreamIdRequestMap().get(streamId).getInboundMsg(); if (sourceReqCMsg != null) { sourceReqCMsg.addHttpContent(new DefaultLastHttpContent()); http2SourceHandler.getStreamIdRequestMap().remove(streamId); } dataFrame.getData().release(); } /** * Sends {@link org.wso2.transport.http.netty.message.Http2Reset} frame with `NO_ERROR` error code. * * @param ctx the channel handler context * @param encoder the HTTP2 connection encoder * @param streamId id of the stream need to be send RST_FRAME * @throws Http2Exception if a protocol-related error occurred */ public static void sendRstFrame(ChannelHandlerContext ctx, Http2ConnectionEncoder encoder, int streamId) throws Http2Exception { encoder.writeRstStream(ctx, streamId, Http2Error.NO_ERROR.code(), ctx.newPromise()); encoder.flowController().writePendingBytes(); ctx.flush(); } /** * Writes HTTP2 headers. * * @param ctx the channel handler context * @param outboundMsgHolder the outbound message holder * @param http2ClientChannel the client channel related to the handler * @param encoder the HTTP2 connection encoder * @param streamId the id of the stream * @param headers the HTTP headers * @param http2Headers the HTTP2 headers * @param endStream is this the end of stream * @throws Http2Exception if a protocol-related error occurred */ public static void writeHttp2Headers(ChannelHandlerContext ctx, OutboundMsgHolder outboundMsgHolder, Http2ClientChannel http2ClientChannel, Http2ConnectionEncoder encoder, int streamId, HttpHeaders headers, Http2Headers http2Headers, boolean endStream) throws Http2Exception { int dependencyId = headers.getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_DEPENDENCY_ID.text(), 0); short weight = headers.getShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT); for (Http2DataEventListener dataEventListener : http2ClientChannel.getDataEventListeners()) { if (!dataEventListener.onHeadersWrite(ctx, streamId, http2Headers, endStream)) { return; } } encoder.writeHeaders(ctx, streamId, http2Headers, dependencyId, weight, false, 0, endStream, ctx.newPromise()); encoder.flowController().writePendingBytes(); ctx.flush(); if (endStream) { outboundMsgHolder.setRequestWritten(true); } } /** * Initiates a HTTP2 stream. * * @param ctx the channel handler context * @param connection the HTTP2 connection * @param http2ClientChannel the client channel related to the handler * @param outboundMsgHolder the outbound message holder * @return stream id of next stream * @throws Http2Exception if a protocol-related error occurred */ public static int initiateStream(ChannelHandlerContext ctx, Http2Connection connection, Http2ClientChannel http2ClientChannel, OutboundMsgHolder outboundMsgHolder) throws Http2Exception { int streamId = getNextStreamId(connection); createStream(connection, streamId); http2ClientChannel.putInFlightMessage(streamId, outboundMsgHolder); http2ClientChannel.getDataEventListeners() .forEach(dataEventListener -> dataEventListener.onStreamInit(ctx, streamId)); return streamId; } /** * Returns the stream id of next stream. This method should only be called from an io thread. * * @param conn the HTTP2 connection * @return the next stream id */ private static int getNextStreamId(Http2Connection conn) { return conn.local().incrementAndGetNextStreamId(); } /** * Creates a stream with given stream id. This method should only be called from an io thread. * * @param conn the HTTP2 connection * @param streamId the id of the stream * @throws Http2Exception if a protocol-related error occurred */ private static void createStream(Http2Connection conn, int streamId) throws Http2Exception { conn.local().createStream(streamId, false); if (LOG.isDebugEnabled()) { LOG.debug("Stream created streamId: {}", streamId); } } /** * Adds a push promise message. * * @param ctx the channel handler context * @param http2PushPromise the HTTP2 push promise * @param http2ClientChannel the client channel related to the handler * @param outboundMsgHolder the outbound message holder */ public static void onPushPromiseRead(ChannelHandlerContext ctx, Http2PushPromise http2PushPromise, Http2ClientChannel http2ClientChannel, OutboundMsgHolder outboundMsgHolder) { int streamId = http2PushPromise.getStreamId(); int promisedStreamId = http2PushPromise.getPromisedStreamId(); if (LOG.isDebugEnabled()) { LOG.debug("Received a push promise on channel: {} over stream id: {}, promisedStreamId: {}", http2ClientChannel, streamId, promisedStreamId); } if (outboundMsgHolder == null) { LOG.warn("Push promise received in channel: {} over invalid stream id : {}", http2ClientChannel, streamId); return; } http2ClientChannel.putPromisedMessage(promisedStreamId, outboundMsgHolder); http2PushPromise.setOutboundMsgHolder(outboundMsgHolder); outboundMsgHolder.addPromise(http2PushPromise); for (Http2DataEventListener listener : http2ClientChannel.getDataEventListeners()) { if (!listener.onStreamInit(ctx, promisedStreamId)) { return; } } } /** * Releases the {@link io.netty.buffer.ByteBuf} content. * * @param httpContent the HTTP2 content */ public static void releaseContent(HttpContent httpContent) { httpContent.release(); } public static void sendRequestTimeoutResponse(ChannelHandlerContext ctx, Http2OutboundRespListener http2OutboundRespListener, int streamId, HttpResponseStatus httpResponseStatus, ByteBuf content, boolean handleIncompleteRequest, boolean whileReceivingHeader) { try { Http2Headers headers = new DefaultHttp2Headers(); headers.status(httpResponseStatus.codeAsText()); Http2ConnectionEncoder encoder = http2OutboundRespListener.getEncoder(); encoder.writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise()); ChannelFuture dataFuture = encoder.writeData(ctx, streamId, content, 0, true, ctx.newPromise()); handleFuture(dataFuture, handleIncompleteRequest, whileReceivingHeader, http2OutboundRespListener.getInboundRequestMsg()); encoder.flowController().writePendingBytes(); ctx.flush(); } catch (Http2Exception e) { LOG.error("Error in sending timeout response:" + e.getMessage()); } } private static void handleFuture(ChannelFuture outboundRespFuture, boolean handleIncompleteRequest, boolean whileReceivingHeader, HttpCarbonMessage inboundRequestMsg) { outboundRespFuture.addListener((ChannelFutureListener) channelFuture -> { Throwable cause = channelFuture.cause(); if (cause != null) { LOG.warn("Failed to send: {}", cause.getMessage()); } if (handleIncompleteRequest) { if (whileReceivingHeader) { handleIncompleteInboundMessage(inboundRequestMsg, IDLE_TIMEOUT_TRIGGERED_WHILE_READING_INBOUND_REQUEST_HEADERS); } else { handleIncompleteInboundMessage(inboundRequestMsg, IDLE_TIMEOUT_TRIGGERED_WHILE_READING_INBOUND_REQUEST_BODY); } } }); } public static void initHttp2MessageContext(HttpCarbonMessage outboundRequest, Http2TargetHandler http2TargetHandler) { Http2MessageStateContext http2MessageStateContext = outboundRequest.getHttp2MessageStateContext(); if (http2MessageStateContext == null) { http2MessageStateContext = new Http2MessageStateContext(); http2MessageStateContext.setSenderState(new RequestCompleted(http2TargetHandler, null)); outboundRequest.setHttp2MessageStateContext(http2MessageStateContext); } else if (http2MessageStateContext.getSenderState() == null) { http2MessageStateContext.setSenderState(new RequestCompleted(http2TargetHandler, null)); } } public static void beginResponseWrite(Http2MessageStateContext http2MessageStateContext, Http2OutboundRespListener http2OutboundRespListener, HttpCarbonMessage outboundResponseMsg, HttpContent httpContent, int streamId) throws Http2Exception { // In HTTP/2, 100-continue response and the final response must use the same stream. If the 100-continue // response is sent as a normal response then end stream flag will be sent with it erroneously. if (Util.getHttpResponseStatus(outboundResponseMsg).code() == HttpResponseStatus.CONTINUE.code()) { http2MessageStateContext.setListenerState(new Response100ContinueSent(http2MessageStateContext)); http2MessageStateContext.getListenerState() .writeOutboundResponseBody(http2OutboundRespListener, outboundResponseMsg, httpContent, streamId); } else { // When the initial frames of the response is to be sent. http2MessageStateContext.setListenerState( new SendingHeaders(http2OutboundRespListener, http2MessageStateContext)); http2MessageStateContext.getListenerState() .writeOutboundResponseHeaders(http2OutboundRespListener, outboundResponseMsg, httpContent, streamId); } } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int_max_square_42.java Label Definition File: CWE190_Integer_Overflow__int.label.xml Template File: sources-sinks-42.tmpl.java */ /* * @description * CWE: 190 Integer Overflow * BadSource: max Set data to the maximum value for int * GoodSource: A hardcoded non-zero, non-min, non-max, even number * Sinks: square * GoodSink: Ensure there will not be an overflow before squaring data * BadSink : Square data, which can lead to overflow * Flow Variant: 42 Data flow: data returned from one method to another in the same class * * */ package testcases.CWE190_Integer_Overflow.s03; import testcasesupport.*; import javax.servlet.http.*; public class CWE190_Integer_Overflow__int_max_square_42 extends AbstractTestCase { private int badSource() throws Throwable { int data; /* POTENTIAL FLAW: Use the maximum value for this type */ data = Integer.MAX_VALUE; return data; } public void bad() throws Throwable { int data = badSource(); /* POTENTIAL FLAW: if (data*data) > Integer.MAX_VALUE, this will overflow */ int result = (int)(data * data); IO.writeLine("result: " + result); } /* goodG2B() - use goodsource and badsink */ private int goodG2BSource() throws Throwable { int data; /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; return data; } private void goodG2B() throws Throwable { int data = goodG2BSource(); /* POTENTIAL FLAW: if (data*data) > Integer.MAX_VALUE, this will overflow */ int result = (int)(data * data); IO.writeLine("result: " + result); } /* goodB2G() - use badsource and goodsink */ private int goodB2GSource() throws Throwable { int data; /* POTENTIAL FLAW: Use the maximum value for this type */ data = Integer.MAX_VALUE; return data; } private void goodB2G() throws Throwable { int data = goodB2GSource(); /* FIX: Add a check to prevent an overflow from occurring */ /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */ if ((data != Integer.MIN_VALUE) && (data != Long.MIN_VALUE) && (Math.abs(data) <= (long)Math.sqrt(Integer.MAX_VALUE))) { int result = (int)(data * data); IO.writeLine("result: " + result); } else { IO.writeLine("data value is too large to perform squaring."); } } public void good() throws Throwable { goodG2B(); goodB2G(); } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
package com.cgs.kerberos.exception; public class AesSecurityException extends SecurityException{ /** * */ private static final long serialVersionUID = -821066350673940923L; public AesSecurityException(String msg) { super(msg); } public AesSecurityException(String msg, Throwable cause) { super(msg, cause); } }
package pages; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import java.util.ArrayList; import java.util.List; import java.util.Set; import static java.lang.Thread.*; public class AdminPageMain { private WebDriver driver; private By menuLink = By.cssSelector("#app- >a"); private By nestedLink = By.cssSelector(".docs a"); private By menuLinkConstuctor(String link){ return By.cssSelector("a[href*=\"http://localhost/litecart/admin/?app=" + link); } private By title = By.tagName("h1"); public AdminPageMain (WebDriver driver) {this.driver= driver;} public void checkLinks() throws InterruptedException { List<WebElement> menuLinks =driver.findElements(menuLink); for (int i = 0; i < menuLinks.size(); i++) { sleep(40); menuLinks.get(i).click(); driver.findElement(title).isDisplayed(); List<WebElement> nestedLinks =driver.findElements(nestedLink); for (int j = 0; j < nestedLinks.size(); j++) { nestedLinks.get(j).click(); driver.findElement(title).isDisplayed(); nestedLinks =driver.findElements(nestedLink); } menuLinks =driver.findElements(menuLink); } } public void clickMenuLink(String link) throws InterruptedException { Thread.sleep(500); driver.findElement(menuLinkConstuctor(link)).click(); } }
package com.google.android.gms.internal; import android.location.Location; import com.google.android.gms.ads.mediation.MediationAdRequest; import java.util.Date; import java.util.Set; @C1507ey /* renamed from: com.google.android.gms.internal.db */ public final class C1413db implements MediationAdRequest { /* renamed from: d */ private final Date f2865d; /* renamed from: f */ private final Set<String> f2866f; /* renamed from: g */ private final boolean f2867g; /* renamed from: h */ private final Location f2868h; /* renamed from: ow */ private final int f2869ow; /* renamed from: qU */ private final int f2870qU; public C1413db(Date date, int i, Set<String> set, Location location, boolean z, int i2) { this.f2865d = date; this.f2869ow = i; this.f2866f = set; this.f2868h = location; this.f2867g = z; this.f2870qU = i2; } public Date getBirthday() { return this.f2865d; } public int getGender() { return this.f2869ow; } public Set<String> getKeywords() { return this.f2866f; } public Location getLocation() { return this.f2868h; } public boolean isTesting() { return this.f2867g; } public int taggedForChildDirectedTreatment() { return this.f2870qU; } }
/* * Copyright 2018-2021 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.s3.transfer; import com.amazonaws.services.s3.model.PresignedUrlDownloadConfig; import com.amazonaws.services.s3.model.PresignedUrlDownloadRequest; import java.io.File; import java.net.URL; /** * Interface to represent the output for the asynchronous download operation using presigned url in {@link TransferManager}. * * @see TransferManager#download(PresignedUrlDownloadRequest, File, PresignedUrlDownloadConfig). */ public interface PresignedUrlDownload extends AbortableTransfer { /** * @return The presigned url from which the object is being downloaded */ URL getPresignedUrl(); }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.framework.autoproxy; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.aopalliance.aop.Advice; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aop.Advisor; import org.springframework.aop.Pointcut; import org.springframework.aop.TargetSource; import org.springframework.aop.framework.AopInfrastructureBean; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.framework.ProxyProcessorSupport; import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry; import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry; import org.springframework.aop.target.SingletonTargetSource; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation * that wraps each eligible bean with an AOP proxy, delegating to specified interceptors * before invoking the bean itself. * * <p>This class distinguishes between "common" interceptors: shared for all proxies it * creates, and "specific" interceptors: unique per bean instance. There need not be any * common interceptors. If there are, they are set using the interceptorNames property. * As with {@link org.springframework.aop.framework.ProxyFactoryBean}, interceptors names * in the current factory are used rather than bean references to allow correct handling * of prototype advisors and interceptors: for example, to support stateful mixins. * Any advice type is supported for {@link #setInterceptorNames "interceptorNames"} entries. * * <p>Such auto-proxying is particularly useful if there's a large number of beans that * need to be wrapped with similar proxies, i.e. delegating to the same interceptors. * Instead of x repetitive proxy definitions for x target beans, you can register * one single such post processor with the bean factory to achieve the same effect. * * <p>Subclasses can apply any strategy to decide if a bean is to be proxied, e.g. by type, * by name, by definition details, etc. They can also return additional interceptors that * should just be applied to the specific bean instance. A simple concrete implementation is * {@link BeanNameAutoProxyCreator}, identifying the beans to be proxied via given names. * * <p>Any number of {@link TargetSourceCreator} implementations can be used to create * a custom target source: for example, to pool prototype objects. Auto-proxying will * occur even if there is no advice, as long as a TargetSourceCreator specifies a custom * {@link org.springframework.aop.TargetSource}. If there are no TargetSourceCreators set, * or if none matches, a {@link org.springframework.aop.target.SingletonTargetSource} * will be used by default to wrap the target bean instance. * * @author Juergen Hoeller * @author Rod Johnson * @author Rob Harrop * @since 13.10.2003 * @see #setInterceptorNames * @see #getAdvicesAndAdvisorsForBean * @see BeanNameAutoProxyCreator * @see DefaultAdvisorAutoProxyCreator */ @SuppressWarnings("serial") public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware { /** * Convenience constant for subclasses: Return value for "do not proxy". * @see #getAdvicesAndAdvisorsForBean */ @Nullable protected static final Object[] DO_NOT_PROXY = null; /** * Convenience constant for subclasses: Return value for * "proxy without additional interceptors, just the common ones". * @see #getAdvicesAndAdvisorsForBean */ protected static final Object[] PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS = new Object[0]; /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); /** Default is global AdvisorAdapterRegistry. */ private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance(); /** * Indicates whether or not the proxy should be frozen. Overridden from super * to prevent the configuration from becoming frozen too early. */ private boolean freezeProxy = false; /** Default is no common interceptors. */ private String[] interceptorNames = new String[0]; private boolean applyCommonInterceptorsFirst = true; @Nullable private TargetSourceCreator[] customTargetSourceCreators; @Nullable private BeanFactory beanFactory; private final Set<String> targetSourcedBeans = Collections.newSetFromMap(new ConcurrentHashMap<>(16)); private final Map<Object, Object> earlyProxyReferences = new ConcurrentHashMap<>(16); private final Map<Object, Class<?>> proxyTypes = new ConcurrentHashMap<>(16); private final Map<Object, Boolean> advisedBeans = new ConcurrentHashMap<>(256); /** * Set whether or not the proxy should be frozen, preventing advice * from being added to it once it is created. * <p>Overridden from the super class to prevent the proxy configuration * from being frozen before the proxy is created. */ @Override public void setFrozen(boolean frozen) { this.freezeProxy = frozen; } @Override public boolean isFrozen() { return this.freezeProxy; } /** * Specify the {@link AdvisorAdapterRegistry} to use. * <p>Default is the global {@link AdvisorAdapterRegistry}. * @see org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry */ public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) { this.advisorAdapterRegistry = advisorAdapterRegistry; } /** * Set custom {@code TargetSourceCreators} to be applied in this order. * If the list is empty, or they all return null, a {@link SingletonTargetSource} * will be created for each bean. * <p>Note that TargetSourceCreators will kick in even for target beans * where no advices or advisors have been found. If a {@code TargetSourceCreator} * returns a {@link TargetSource} for a specific bean, that bean will be proxied * in any case. * <p>{@code TargetSourceCreators} can only be invoked if this post processor is used * in a {@link BeanFactory} and its {@link BeanFactoryAware} callback is triggered. * @param targetSourceCreators the list of {@code TargetSourceCreators}. * Ordering is significant: The {@code TargetSource} returned from the first matching * {@code TargetSourceCreator} (that is, the first that returns non-null) will be used. */ public void setCustomTargetSourceCreators(TargetSourceCreator... targetSourceCreators) { this.customTargetSourceCreators = targetSourceCreators; } /** * Set the common interceptors. These must be bean names in the current factory. * They can be of any advice or advisor type Spring supports. * <p>If this property isn't set, there will be zero common interceptors. * This is perfectly valid, if "specific" interceptors such as matching * Advisors are all we want. */ public void setInterceptorNames(String... interceptorNames) { this.interceptorNames = interceptorNames; } /** * Set whether the common interceptors should be applied before bean-specific ones. * Default is "true"; else, bean-specific interceptors will get applied first. */ public void setApplyCommonInterceptorsFirst(boolean applyCommonInterceptorsFirst) { this.applyCommonInterceptorsFirst = applyCommonInterceptorsFirst; } @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } /** * Return the owning {@link BeanFactory}. * May be {@code null}, as this post-processor doesn't need to belong to a bean factory. */ @Nullable protected BeanFactory getBeanFactory() { return this.beanFactory; } @Override @Nullable public Class<?> predictBeanType(Class<?> beanClass, String beanName) { if (this.proxyTypes.isEmpty()) { return null; } Object cacheKey = getCacheKey(beanClass, beanName); return this.proxyTypes.get(cacheKey); } @Override @Nullable public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) { return null; } @Override public Object getEarlyBeanReference(Object bean, String beanName) { Object cacheKey = getCacheKey(bean.getClass(), beanName); this.earlyProxyReferences.put(cacheKey, bean); return wrapIfNecessary(bean, beanName, cacheKey); } @Override public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) { Object cacheKey = getCacheKey(beanClass, beanName); if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) { if (this.advisedBeans.containsKey(cacheKey)) { return null; } if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { this.advisedBeans.put(cacheKey, Boolean.FALSE); return null; } } // 如果我们有一个自定义的TargetSource,在这里创建代理。 // 抑制不必要的目标bean的缺省实例化:TargetSource将以自定义方式处理目标实例。 TargetSource targetSource = getCustomTargetSource(beanClass, beanName); if (targetSource != null) { if (StringUtils.hasLength(beanName)) { this.targetSourcedBeans.add(beanName); } Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource); Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource); this.proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } return null; } @Override public boolean postProcessAfterInstantiation(Object bean, String beanName) { return true; } @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { return pvs; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } /** * Create a proxy with the configured interceptors if the bean is * identified as one to proxy by the subclass. * @see #getAdvicesAndAdvisorsForBean */ @Override public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) { if (bean != null) { Object cacheKey = getCacheKey(bean.getClass(), beanName); if (this.earlyProxyReferences.remove(cacheKey) != bean) { return wrapIfNecessary(bean, beanName, cacheKey); } } return bean; } /** * Build a cache key for the given bean class and bean name. * <p>Note: As of 4.2.3, this implementation does not return a concatenated * class/name String anymore but rather the most efficient cache key possible: * a plain bean name, prepended with {@link BeanFactory#FACTORY_BEAN_PREFIX} * in case of a {@code FactoryBean}; or if no bean name specified, then the * given bean {@code Class} as-is. * @param beanClass the bean class * @param beanName the bean name * @return the cache key for the given class and name */ protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) { if (StringUtils.hasLength(beanName)) { return (FactoryBean.class.isAssignableFrom(beanClass) ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName); } else { return beanClass; } } /** * Wrap the given bean if necessary, i.e. if it is eligible for being proxied. * @param bean the raw bean instance * @param beanName the name of the bean * @param cacheKey the cache key for metadata access * @return a proxy wrapping the bean, or the raw bean instance as-is */ protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) { return bean; } if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { return bean; } if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { this.advisedBeans.put(cacheKey, Boolean.FALSE); return bean; } // Create proxy if we have advice. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); if (specificInterceptors != DO_NOT_PROXY) { this.advisedBeans.put(cacheKey, Boolean.TRUE); Object proxy = createProxy( bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); this.proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } this.advisedBeans.put(cacheKey, Boolean.FALSE); return bean; } /** * Return whether the given bean class represents an infrastructure class * that should never be proxied. * <p>The default implementation considers Advices, Advisors and * AopInfrastructureBeans as infrastructure classes. * @param beanClass the class of the bean * @return whether the bean represents an infrastructure class * @see org.aopalliance.aop.Advice * @see org.springframework.aop.Advisor * @see org.springframework.aop.framework.AopInfrastructureBean * @see #shouldSkip */ protected boolean isInfrastructureClass(Class<?> beanClass) { boolean retVal = Advice.class.isAssignableFrom(beanClass) || Pointcut.class.isAssignableFrom(beanClass) || Advisor.class.isAssignableFrom(beanClass) || AopInfrastructureBean.class.isAssignableFrom(beanClass); if (retVal && logger.isTraceEnabled()) { logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]"); } return retVal; } /** * Subclasses should override this method to return {@code true} if the * given bean should not be considered for auto-proxying by this post-processor. * <p>Sometimes we need to be able to avoid this happening, e.g. if it will lead to * a circular reference or if the existing target instance needs to be preserved. * This implementation returns {@code false} unless the bean name indicates an * "original instance" according to {@code AutowireCapableBeanFactory} conventions. * @param beanClass the class of the bean * @param beanName the name of the bean * @return whether to skip the given bean * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#ORIGINAL_INSTANCE_SUFFIX */ protected boolean shouldSkip(Class<?> beanClass, String beanName) { return AutoProxyUtils.isOriginalInstance(beanName, beanClass); } /** * Create a target source for bean instances. Uses any TargetSourceCreators if set. * Returns {@code null} if no custom TargetSource should be used. * <p>This implementation uses the "customTargetSourceCreators" property. * Subclasses can override this method to use a different mechanism. * @param beanClass the class of the bean to create a TargetSource for * @param beanName the name of the bean * @return a TargetSource for this bean * @see #setCustomTargetSourceCreators */ @Nullable protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) { // We can't create fancy target sources for directly registered singletons. if (this.customTargetSourceCreators != null && this.beanFactory != null && this.beanFactory.containsBean(beanName)) { for (TargetSourceCreator tsc : this.customTargetSourceCreators) { TargetSource ts = tsc.getTargetSource(beanClass, beanName); if (ts != null) { // Found a matching TargetSource. if (logger.isTraceEnabled()) { logger.trace("TargetSourceCreator [" + tsc + "] found custom TargetSource for bean with name '" + beanName + "'"); } return ts; } } } // No custom TargetSource found. return null; } /** * Create an AOP proxy for the given bean. * @param beanClass the class of the bean * @param beanName the name of the bean * @param specificInterceptors the set of interceptors that is * specific to this bean (may be empty, but not null) * @param targetSource the TargetSource for the proxy, * already pre-configured to access the bean * @return the AOP proxy for the bean * @see #buildAdvisors */ protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) { if (this.beanFactory instanceof ConfigurableListableBeanFactory) { AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass); } ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.copyFrom(this); if (!proxyFactory.isProxyTargetClass()) { if (shouldProxyTargetClass(beanClass, beanName)) { proxyFactory.setProxyTargetClass(true); } else { evaluateProxyInterfaces(beanClass, proxyFactory); } } Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); proxyFactory.addAdvisors(advisors); proxyFactory.setTargetSource(targetSource); customizeProxyFactory(proxyFactory); proxyFactory.setFrozen(this.freezeProxy); if (advisorsPreFiltered()) { proxyFactory.setPreFiltered(true); } return proxyFactory.getProxy(getProxyClassLoader()); } /** * Determine whether the given bean should be proxied with its target class rather than its interfaces. * <p>Checks the {@link AutoProxyUtils#PRESERVE_TARGET_CLASS_ATTRIBUTE "preserveTargetClass" attribute} * of the corresponding bean definition. * @param beanClass the class of the bean * @param beanName the name of the bean * @return whether the given bean should be proxied with its target class * @see AutoProxyUtils#shouldProxyTargetClass */ protected boolean shouldProxyTargetClass(Class<?> beanClass, @Nullable String beanName) { return (this.beanFactory instanceof ConfigurableListableBeanFactory && AutoProxyUtils.shouldProxyTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName)); } /** * Return whether the Advisors returned by the subclass are pre-filtered * to match the bean's target class already, allowing the ClassFilter check * to be skipped when building advisors chains for AOP invocations. * <p>Default is {@code false}. Subclasses may override this if they * will always return pre-filtered Advisors. * @return whether the Advisors are pre-filtered * @see #getAdvicesAndAdvisorsForBean * @see org.springframework.aop.framework.Advised#setPreFiltered */ protected boolean advisorsPreFiltered() { return false; } /** * Determine the advisors for the given bean, including the specific interceptors * as well as the common interceptor, all adapted to the Advisor interface. * @param beanName the name of the bean * @param specificInterceptors the set of interceptors that is * specific to this bean (may be empty, but not null) * @return the list of Advisors for the given bean */ protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) { // Handle prototypes correctly... Advisor[] commonInterceptors = resolveInterceptorNames(); List<Object> allInterceptors = new ArrayList<>(); if (specificInterceptors != null) { allInterceptors.addAll(Arrays.asList(specificInterceptors)); if (commonInterceptors.length > 0) { if (this.applyCommonInterceptorsFirst) { allInterceptors.addAll(0, Arrays.asList(commonInterceptors)); } else { allInterceptors.addAll(Arrays.asList(commonInterceptors)); } } } if (logger.isTraceEnabled()) { int nrOfCommonInterceptors = commonInterceptors.length; int nrOfSpecificInterceptors = (specificInterceptors != null ? specificInterceptors.length : 0); logger.trace("Creating implicit proxy for bean '" + beanName + "' with " + nrOfCommonInterceptors + " common interceptors and " + nrOfSpecificInterceptors + " specific interceptors"); } Advisor[] advisors = new Advisor[allInterceptors.size()]; for (int i = 0; i < allInterceptors.size(); i++) { advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i)); } return advisors; } /** * Resolves the specified interceptor names to Advisor objects. * @see #setInterceptorNames */ private Advisor[] resolveInterceptorNames() { BeanFactory bf = this.beanFactory; ConfigurableBeanFactory cbf = (bf instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) bf : null); List<Advisor> advisors = new ArrayList<>(); for (String beanName : this.interceptorNames) { if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) { Assert.state(bf != null, "BeanFactory required for resolving interceptor names"); Object next = bf.getBean(beanName); advisors.add(this.advisorAdapterRegistry.wrap(next)); } } return advisors.toArray(new Advisor[0]); } /** * Subclasses may choose to implement this: for example, * to change the interfaces exposed. * <p>The default implementation is empty. * @param proxyFactory a ProxyFactory that is already configured with * TargetSource and interfaces and will be used to create the proxy * immediately after this method returns */ protected void customizeProxyFactory(ProxyFactory proxyFactory) { } /** * Return whether the given bean is to be proxied, what additional * advices (e.g. AOP Alliance interceptors) and advisors to apply. * @param beanClass the class of the bean to advise * @param beanName the name of the bean * @param customTargetSource the TargetSource returned by the * {@link #getCustomTargetSource} method: may be ignored. * Will be {@code null} if no custom target source is in use. * @return an array of additional interceptors for the particular bean; * or an empty array if no additional interceptors but just the common ones; * or {@code null} if no proxy at all, not even with the common interceptors. * See constants DO_NOT_PROXY and PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS. * @throws BeansException in case of errors * @see #DO_NOT_PROXY * @see #PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS */ @Nullable protected abstract Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, @Nullable TargetSource customTargetSource) throws BeansException; }
package com.lee.shiro.service.impl; import com.lee.shiro.entity.Role; import com.lee.shiro.service.RoleService; import org.springframework.stereotype.Service; /** * @author Created by pangkunkun on 2017/11/16. */ @Service public class RoleServiceImpl implements RoleService { // @Override // public Set<String> findAllRolesByUserId(String userId){ // Set<String> roles=new HashSet<>(); // roles.add("admin"); // roles.add("user"); // return roles; // } @Override public void save(Role role) { } }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.0. You may not use this file * except in compliance with the Zeebe Community License 1.0. */ package io.zeebe.gateway.api.job; import static io.zeebe.util.buffer.BufferUtil.wrapString; import static org.assertj.core.api.Assertions.assertThat; import io.zeebe.gateway.api.util.GatewayTest; import io.zeebe.gateway.impl.broker.request.BrokerFailJobRequest; import io.zeebe.gateway.protocol.GatewayOuterClass.FailJobRequest; import io.zeebe.gateway.protocol.GatewayOuterClass.FailJobResponse; import io.zeebe.protocol.impl.record.value.job.JobRecord; import io.zeebe.protocol.record.ValueType; import io.zeebe.protocol.record.intent.JobIntent; import org.junit.Test; public class FailJobTest extends GatewayTest { @Test public void shouldMapRequestAndResponse() { // given final FailJobStub stub = new FailJobStub(); stub.registerWith(gateway); final int retries = 123; final FailJobRequest request = FailJobRequest.newBuilder() .setJobKey(stub.getKey()) .setRetries(retries) .setErrorMessage("failed") .build(); // when final FailJobResponse response = client.failJob(request); // then assertThat(response).isNotNull(); final BrokerFailJobRequest brokerRequest = gateway.getSingleBrokerRequest(); assertThat(brokerRequest.getKey()).isEqualTo(stub.getKey()); assertThat(brokerRequest.getIntent()).isEqualTo(JobIntent.FAIL); assertThat(brokerRequest.getValueType()).isEqualTo(ValueType.JOB); final JobRecord brokerRequestValue = brokerRequest.getRequestWriter(); assertThat(brokerRequestValue.getRetries()).isEqualTo(retries); assertThat(brokerRequestValue.getErrorMessageBuffer()).isEqualTo(wrapString("failed")); } }
/* * 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 todayTag; import java.util.Date; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.JspFragment; import javax.servlet.jsp.tagext.SimpleTagSupport; /** * * @author c3 */ public class TodayTag extends SimpleTagSupport { /** * Called by the container to invoke this tag. The implementation of this * method is provided by the tag library developer, and handles all tag * processing, body iteration, etc. */ @Override public void doTag() throws JspException { JspWriter out = getJspContext().getOut(); try { // TODO: insert code to write html before writing the body content. // e.g.: // // out.println("<strong>" + attribute_1 + "</strong>"); // out.println(" <blockquote>"); out.println(new Date()); JspFragment f = getJspBody(); if (f != null) { f.invoke(out); } // TODO: insert code to write html after writing the body content. // e.g.: // // out.println(" </blockquote>"); } catch (java.io.IOException ex) { throw new JspException("Error in TodayTag tag", ex); } } }
package snownee.cuisine.plugins.top; import mcjty.theoneprobe.Tools; import mcjty.theoneprobe.api.IProbeHitData; import mcjty.theoneprobe.api.IProbeInfo; import mcjty.theoneprobe.api.IProbeInfoProvider; import mcjty.theoneprobe.api.ProbeMode; import mcjty.theoneprobe.api.TextStyleClass; import mcjty.theoneprobe.config.Config; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import snownee.cuisine.Cuisine; import snownee.cuisine.blocks.BlockCuisineCrops; import snownee.cuisine.blocks.BlockModLeaves; import snownee.cuisine.blocks.BlockShearedLeaves; import snownee.cuisine.util.I18nUtil; public class CuisineCropProvider implements IProbeInfoProvider { @Override public String getID() { return Cuisine.MODID + ":crop"; } @Override public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { if (blockState.getBlock() instanceof BlockCuisineCrops) { if (Tools.show(mode, Config.getRealConfig().getShowCropPercentage())) { BlockCuisineCrops crops = (BlockCuisineCrops) blockState.getBlock(); int age = crops.getAge(blockState, world, data.getPos()); int maxAge = crops.getMaxAge(); if (age == maxAge) { probeInfo.text(TextStyleClass.OK + I18nUtil.translate("gui.fully_grown")); } else { probeInfo.text(TextStyleClass.LABEL + I18nUtil.translate("gui.grown", TextStyleClass.WARNING + "" + (age * 100) / maxAge)); } } } else if (blockState.getBlock() instanceof BlockModLeaves) { if (Tools.show(mode, Config.getRealConfig().getShowCropPercentage())) { probeInfo.text(I18nUtil.translate( "gui.leaves." + blockState.getValue(BlockModLeaves.AGE))); } } else if (blockState.getBlock() instanceof BlockShearedLeaves) { if (Tools.show(mode, Config.getRealConfig().getShowCropPercentage())) { probeInfo.text(I18nUtil.translate( "gui.leaves.0")); } } } }
/** * Automatically generated file. DO NOT MODIFY */ package com.mag.codepath.simpletweet; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.mag.codepath.simpletweet"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = 1; public static final String VERSION_NAME = "1.0"; }
/* * Trident - A Multithreaded Server Alternative * Copyright 2014 The TridentSDK Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tridentsdk.server.threads; import net.tridentsdk.concurrent.TaskExecutor; /** * World handling threads, which there are by default 4 * * @author The TridentSDK Team */ public final class WorldThreads { private WorldThreads() { } /** * Used when the server ticks, to tell this thing to tick */ protected static void notifyTick() { for (TaskExecutor executor : ThreadsManager.worlds.threadList()) { executor.addTask(new Runnable() { @Override public void run() { // TODO: maybe move this somewhere else? // TODO: tick the chunk } }); } } /** * Notifies the server to tick redstone activities */ public static void notifyRedstoneTick() { for (TaskExecutor executor : ThreadsManager.worlds.threadList()) { executor.addTask(new Runnable() { @Override public void run() { // TODO: maybe move this somewhere else? // TODO: tick the world's redstone } }); } } }
package com.example.rest; import com.codahale.metrics.annotation.Timed; import com.example.metrics.MetricsCounterService; import com.example.metrics.TimerMetricWriter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.GET; @RestController public class TaskController { private static final Logger LOG = LogManager.getLogger(TaskController.class); @Autowired private TimerMetricWriter timerMetricWriter; @Autowired private MetricsCounterService metricsCounterService; @Timed(absolute = true, name = "tasks") @ResponseStatus(OK) @RequestMapping(value = "/tasks", method = GET, produces = APPLICATION_JSON_VALUE) public Map<String, String> getTasks() { Map<String, String> tasks = new HashMap<>(); tasks.put("task1", "Build project"); tasks.put("task2", "Deploy app to environment"); // timer metric writer that accepts lambda as parameter timerMetricWriter.time("test.timer.create.hashmap", () -> new HashMap<>()); // sample of a count service metricsCounterService.exampleMethod(); return tasks; } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.firebase.crashlytics.internal.common; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.google.firebase.crashlytics.internal.unity.UnityVersionProvider; /** Carries static information about the app. */ public class AppData { public final String googleAppId; public final String buildId; public final String installerPackageName; public final String packageName; public final String versionCode; public final String versionName; public final UnityVersionProvider unityVersionProvider; public static AppData create( Context context, IdManager idManager, String googleAppId, String buildId, UnityVersionProvider unityVersionProvider) throws PackageManager.NameNotFoundException { final String packageName = context.getPackageName(); final String installerPackageName = idManager.getInstallerPackageName(); final PackageManager packageManager = context.getPackageManager(); final PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0); final String versionCode = Integer.toString(packageInfo.versionCode); final String versionName = packageInfo.versionName == null ? IdManager.DEFAULT_VERSION_NAME : packageInfo.versionName; return new AppData( googleAppId, buildId, installerPackageName, packageName, versionCode, versionName, unityVersionProvider); } public AppData( String googleAppId, String buildId, String installerPackageName, String packageName, String versionCode, String versionName, UnityVersionProvider unityVersionProvider) { this.googleAppId = googleAppId; this.buildId = buildId; this.installerPackageName = installerPackageName; this.packageName = packageName; this.versionCode = versionCode; this.versionName = versionName; this.unityVersionProvider = unityVersionProvider; } }
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.openecomp.sdc.be.model; import java.util.List; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement, IPropertyInputCommon { /** * The unique id of the property value on graph */ private String valueUniqueUid; private List<String> path = null; private List<PropertyRule> rules = null; private String componentInstanceName; private String componentInstanceId; public ComponentInstanceInput() { super(); } public ComponentInstanceInput(PropertyDataDefinition curPropertyDef, String inputId, String value, String valueUniqueUid) { super(curPropertyDef); setInputId(inputId); setValue(value); this.valueUniqueUid = valueUniqueUid; } public ComponentInstanceInput(InputDefinition pd, String value, String valueUniqueUid) { super(pd); setValue(value); this.valueUniqueUid = valueUniqueUid; } public ComponentInstanceInput(PropertyDataDefinition propertyDefinition) { super(propertyDefinition); if (propertyDefinition.getGetInputValues() != null && !propertyDefinition.getGetInputValues().isEmpty()) { setInputId(propertyDefinition.getGetInputValues().get(0).getInputId()); } } public String getComponentInstanceName() { return componentInstanceName; } public void setComponentInstanceName(String componentInstanceName) { this.componentInstanceName = componentInstanceName; } public String getComponentInstanceId() { return componentInstanceId; } public void setComponentInstanceId(String componentInstanceId) { this.componentInstanceId = componentInstanceId; } public String getValueUniqueUid() { return valueUniqueUid; } public void setValueUniqueUid(String valueUniqueUid) { this.valueUniqueUid = valueUniqueUid; } public List<String> getPath() { return path; } public void setPath(List<String> path) { this.path = path; } public List<PropertyRule> getRules() { return rules; } public void setRules(List<PropertyRule> rules) { this.rules = rules; } @Override public String toString() { return "ComponentInstanceInput [ " + super.toString() + " , value=" + getValue() + ", valueUniqueUid = " + valueUniqueUid + " , rules=" + rules + " , path=" + path + " ]"; } }
package com.groupb.DAO; import java.util.List; import java.util.Map; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.groupb.models.Product; @Repository public interface ProductDAO extends JpaRepository<Product, Integer>{ @Query("select p.title, p.minimumlimit, sum(quantity) as quantity from product_stock ps join products p on" + "ps.product_ref_id = p.productid group by p.title, p.minimumlimit having sum(quantity) < p.minimumlimit") public List<Map<String, Object>>getDemand(); }
/* * 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.ignite.internal.processors.query.calcite.schema; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import com.google.common.collect.ImmutableList; import org.apache.calcite.plan.Convention; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.RelCollation; import org.apache.calcite.rel.RelReferentialConstraint; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.schema.Statistic; import org.apache.calcite.schema.impl.AbstractTable; import org.apache.calcite.util.ImmutableBitSet; import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext; import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup; import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext; import org.apache.ignite.internal.processors.query.calcite.rel.logical.IgniteLogicalIndexScan; import org.apache.ignite.internal.processors.query.calcite.rel.logical.IgniteLogicalTableScan; import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution; import org.apache.ignite.internal.processors.query.calcite.trait.RewindabilityTrait; import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.internal.processors.query.calcite.Stubs.resultSetGenerator; /** * Ignite table implementation. */ public class IgniteTableImpl extends AbstractTable implements IgniteTable { /** */ private final TableDescriptor desc; /** */ private final Statistic statistic; /** */ private volatile Collection<Object[]> rows; /** */ private final Map<String, IgniteIndex> indexes = new ConcurrentHashMap<>(); /** * @param desc Table descriptor. */ public IgniteTableImpl(TableDescriptor desc) { this.desc = desc; statistic = new StatisticsImpl(); } /** {@inheritDoc} */ @Override public RelDataType getRowType(RelDataTypeFactory typeFactory, ImmutableBitSet requiredColumns) { return desc.rowType((IgniteTypeFactory)typeFactory, requiredColumns); } /** {@inheritDoc} */ @Override public Statistic getStatistic() { return statistic; } /** {@inheritDoc} */ @Override public TableDescriptor descriptor() { return desc; } /** {@inheritDoc} */ @Override public IgniteLogicalTableScan toRel(RelOptCluster cluster, RelOptTable relOptTbl) { RelTraitSet traitSet = cluster.traitSetOf(distribution()) .replace(RewindabilityTrait.REWINDABLE); return IgniteLogicalTableScan.create(cluster, traitSet, relOptTbl, null, null, null); } /** {@inheritDoc} */ @Override public IgniteLogicalIndexScan toRel(RelOptCluster cluster, RelOptTable relOptTbl, String idxName) { RelTraitSet traitSet = cluster.traitSetOf(Convention.Impl.NONE) .replace(distribution()) .replace(RewindabilityTrait.REWINDABLE) .replace(getIndex(idxName).collation()); return IgniteLogicalIndexScan.create(cluster, traitSet, relOptTbl, idxName, null, null, null); } /** {@inheritDoc} */ @Override public <Row> Iterable<Row> scan( ExecutionContext<Row> execCtx, ColocationGroup group, Predicate<Row> filter, Function<Row, Row> rowTransformer, @Nullable ImmutableBitSet usedColumns ) { String locNodeId = execCtx.planningContext().localNodeId(); if (group.nodeIds().contains(locNodeId)) return (Iterable<Row>) rows(execCtx.getTypeFactory()); return Collections.emptyList(); } /** {@inheritDoc} */ @Override public IgniteDistribution distribution() { return desc.distribution(); } /** {@inheritDoc} */ @Override public ColocationGroup colocationGroup(PlanningContext ctx) { return desc.colocationGroup(ctx); } /** {@inheritDoc} */ @Override public Map<String, IgniteIndex> indexes() { return Collections.unmodifiableMap(indexes); } /** {@inheritDoc} */ @Override public void addIndex(IgniteIndex idxTbl) { indexes.put(idxTbl.name(), idxTbl); } /** {@inheritDoc} */ @Override public IgniteIndex getIndex(String idxName) { return indexes.get(idxName); } /** {@inheritDoc} */ @Override public void removeIndex(String idxName) { indexes.remove(idxName); } /** {@inheritDoc} */ @Override public <C> C unwrap(Class<C> aCls) { if (aCls.isInstance(desc)) return aCls.cast(desc); return super.unwrap(aCls); } private Collection<Object[]> rows(IgniteTypeFactory typeFactory) { if (rows == null) { synchronized (this) { if (rows == null) rows = resultSetGenerator(10, typeFactory, getRowType(typeFactory)); } } return rows; } /** */ private class StatisticsImpl implements Statistic { /** {@inheritDoc} */ @Override public Double getRowCount() { return (double)rows(new IgniteTypeFactory()).size(); } /** {@inheritDoc} */ @Override public boolean isKey(ImmutableBitSet cols) { return false; // TODO } /** {@inheritDoc} */ @Override public List<ImmutableBitSet> getKeys() { return null; // TODO } /** {@inheritDoc} */ @Override public List<RelReferentialConstraint> getReferentialConstraints() { return ImmutableList.of(); } /** {@inheritDoc} */ @Override public List<RelCollation> getCollations() { return ImmutableList.of(); // The method isn't used } /** {@inheritDoc} */ @Override public IgniteDistribution getDistribution() { return distribution(); } } }
/* * Copyright (c) 2020. Inyiama Kossy */ package com.github.kossy18.karta.mapping; public class MappingNotFoundException extends MappingException { public MappingNotFoundException(String message, Throwable cause) { super(message, cause); } }
/* * Copyright (C) 2013 salesforce.com, 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 org.auraframework.integration.test.caching; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.auraframework.adapter.ConfigAdapter; import org.auraframework.def.ComponentDef; import org.auraframework.def.DefDescriptor; import org.auraframework.http.AuraBaseServlet; import org.auraframework.integration.test.util.AuraHttpTestCase; import org.auraframework.system.AuraContext.Authentication; import org.auraframework.system.AuraContext.Format; import org.auraframework.system.AuraContext.Mode; import org.auraframework.util.json.JsonEncoder; import org.auraframework.util.json.JsonReader; import org.auraframework.util.test.annotation.AuraTestLabels; import org.auraframework.util.test.annotation.ThreadHostileTest; import org.junit.Test; import javax.inject.Inject; /** * Test class to verify that clientside cache is invalidated by Aura Servlet. */ @ThreadHostileTest("relies on getLastMod") public class AuraServletCacheInvalidationHttpTest extends AuraHttpTestCase { @Inject private ConfigAdapter configAdapter; /** * Verify that AuraServlet returns an error code in the response body when * an expired lastmod timestamp is used in a POST request. * * @throws Exception */ @Test public void testPostRequestWithDifferentUID() throws Exception { HttpPost post = getPostMethod("aura:component", true); HttpResponse httpResponse = perform(post); // days int statusCode = getStatusCode(httpResponse); String response = getResponseBody(httpResponse); post.releaseConnection(); assertTrue("Aura servlet should return 200.", statusCode == HttpStatus.SC_OK); assertOutdated(response); } /** * Verify that AuraServlet returns usable content in the response body when * valid lastmod timestamp is used in a POST request. * * @throws Exception */ @AuraTestLabels("auraSanity") @Test public void testPostRequestWithValidUID() throws Exception { HttpPost post = getPostMethod("aura:component", false); HttpResponse httpResponse = perform(post); int statusCode = getStatusCode(httpResponse); String response = getResponseBody(httpResponse); post.releaseConnection(); if (HttpStatus.SC_OK != statusCode) { fail(String.format("Unexpected status code <%s>, expected <%s>, response:%n%s", statusCode, HttpStatus.SC_OK, response)); } assertTrue("AuraServlet did not accept lastMod param.", response.startsWith(AuraBaseServlet.CSRF_PROTECT)); } /** * Convenience method to create a POST object to invoke a server side action. * * This method is very specific to this test, please do not use it for any * other purpose. * * @param name the name of the component to load. * @param modified should the UID be modified to force a out of sync. * @return response * @throws Exception */ private HttpPost getPostMethod(String name, boolean modified) throws Exception { Map<String, Object> message = new HashMap<>(); Map<String, Object> actionInstance = new HashMap<>(); actionInstance.put("descriptor", "java://org.auraframework.components.test.java.controller.JavaTestController/ACTION$getString"); Map<String, Object> actionParams = new HashMap<>(); actionParams.put("param", "some string"); actionInstance.put("params", actionParams); @SuppressWarnings("rawtypes") Map[] actions = { actionInstance }; message.put("actions", actions); String jsonMessage = JsonEncoder.serialize(message); Map<String, String> params = new HashMap<>(); params.put("message", jsonMessage); params.put("aura.token", configAdapter.getCSRFToken()); String serContext; contextService.startContext(Mode.PROD, Format.JSON, Authentication.AUTHENTICATED, definitionService.getDefDescriptor(name, ComponentDef.class)); DefDescriptor<ComponentDef> desc = definitionService.getDefDescriptor(name, ComponentDef.class); String uid = definitionService.getUid(null, desc); if (modified) { uid = getAuraTestingUtil().modifyUID(uid); } serContext = getAuraTestingUtil().buildContextForPost(Mode.DEV, desc, uid, configAdapter.getAuraFrameworkNonce(), null, null); params.put("aura.context", serContext); return obtainPostMethod("/aura", params); } @SuppressWarnings("unchecked") private void assertOutdated(String response) { if (!response.endsWith("/*ERROR*/")) { fail("response should end with /*ERROR*/ but got: "+response); } String jsonString = "/*" + response; Map<String, Object> json = (Map<String, Object>) new JsonReader().read(jsonString); Map<String, Object> event = (Map<String, Object>) json.get("event"); if (event != null) { String descriptor = (String) event.get("descriptor"); if (descriptor != null && descriptor.equals("markup://aura:clientOutOfSync")) { return; } } fail("unexpected response: " + response); } }
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.assetowner.metadataelements; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import org.odpi.openmetadata.accessservices.assetowner.properties.SchemaTypeProperties; import java.io.Serializable; import java.util.Objects; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * SchemaTypeElement contains the properties and header for a reference data asset retrieved from the metadata repository. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class SchemaTypeElement implements MetadataElement, Serializable { private static final long serialVersionUID = 1L; private SchemaTypeProperties schemaTypeProperties = null; private ElementHeader elementHeader = null; /** * Default constructor */ public SchemaTypeElement() { super(); } /** * Copy/clone constructor * * @param template object to copy */ public SchemaTypeElement(SchemaTypeElement template) { if (template != null) { elementHeader = template.getElementHeader(); schemaTypeProperties = template.getSchemaTypeProperties(); } } /** * Return the element header associated with the properties. * * @return element header object */ @Override public ElementHeader getElementHeader() { return elementHeader; } /** * Set up the element header associated with the properties. * * @param elementHeader element header object */ @Override public void setElementHeader(ElementHeader elementHeader) { this.elementHeader = elementHeader; } /** * Return the properties for the schema. * * @return schema properties (using appropriate subclass) */ public SchemaTypeProperties getSchemaTypeProperties() { return schemaTypeProperties; } /** * Set up the properties for the schema. * * @param schemaTypeProperties schema properties */ public void setSchemaTypeProperties(SchemaTypeProperties schemaTypeProperties) { this.schemaTypeProperties = schemaTypeProperties; } /** * JSON-style toString * * @return return string containing the property names and values */ @Override public String toString() { return "SchemaTypeElement{" + "elementHeader=" + elementHeader + ", properties='" + getSchemaTypeProperties() + '\'' + '}'; } /** * Return comparison result based on the content of the properties. * * @param objectToCompare test object * @return result of comparison */ @Override public boolean equals(Object objectToCompare) { if (this == objectToCompare) { return true; } if (objectToCompare == null || getClass() != objectToCompare.getClass()) { return false; } SchemaTypeElement that = (SchemaTypeElement) objectToCompare; return Objects.equals(schemaTypeProperties, that.schemaTypeProperties) && Objects.equals(elementHeader, that.elementHeader); } /** * Return hash code for this object * * @return int hash code */ @Override public int hashCode() { return Objects.hash(super.hashCode(), elementHeader, schemaTypeProperties); } }
package com.xieyao.movies; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.xieyao.movies", appContext.getPackageName()); } }
/* * Copyright 2007 Yusuke Yamamoto * * 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 twitter4j.internal.json; import twitter4j.PagableResponseList; import twitter4j.RateLimitStatus; import twitter4j.internal.http.HttpResponse; import twitter4j.internal.org.json.JSONObject; import twitter4j.internal.util.z_T4JInternalParseUtil; /** * @author Yusuke Yamamoto - yusuke at mac.com * @since Twitter4J 2.1.3 */ class PagableResponseListImpl<T> extends ResponseListImpl implements PagableResponseList { private final long previousCursor; private final long nextCursor; private static final long serialVersionUID = 1531950333538983361L; PagableResponseListImpl(RateLimitStatus rateLimitStatus, RateLimitStatus featureSpecificRateLimitStatus, int accessLevel) { super(rateLimitStatus, featureSpecificRateLimitStatus, accessLevel); previousCursor = 0; nextCursor = 0; } PagableResponseListImpl(int size, JSONObject json, HttpResponse res) { super(size, res); this.previousCursor = z_T4JInternalParseUtil.getLong("previous_cursor", json); this.nextCursor = z_T4JInternalParseUtil.getLong("next_cursor", json); } /** * {@inheritDoc} */ public boolean hasPrevious() { return 0 != previousCursor; } /** * {@inheritDoc} */ public long getPreviousCursor() { return previousCursor; } /** * {@inheritDoc} */ public boolean hasNext() { return 0 != nextCursor; } /** * {@inheritDoc} */ public long getNextCursor() { return nextCursor; } }
/* * * Copyright (c) 2021-2015, wuyanshen All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 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. * Neither the name of the lvcoding.com developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: wuyanshen * */ package com.lvcoding.service; import com.lvcoding.entity.vo.DeploymentVO; import com.lvcoding.entity.vo.PageVO; import com.lvcoding.entity.vo.ProcessDefinitionVO; import com.lvcoding.entity.vo.TaskVO; import org.springframework.web.multipart.MultipartFile; import java.util.List; public interface ActivityService { /** * 查询待办任务 * * @param username */ List<TaskVO> findTasks(String username); /** * 查询部署列表 * * @param */ PageVO<ProcessDefinitionVO> getDeployList(PageVO<ProcessDefinitionVO> pageVO); /** * 发布流程 * * @param */ void publish(); /** * 挂起/激活流程 * * @param processKey */ void suspendProcess(String processKey); /** * 根据xml发布流程 * * @param deploymentVO */ void publishByXml(DeploymentVO deploymentVO); /** * 处理任务 * * @param taskVO */ void completeTask(TaskVO taskVO); void publishByZip(MultipartFile multipartFile); /** * 查询历史已办理任务 * @param username * @param pageVO * @return */ PageVO<TaskVO> findHistoryTasks(String username, PageVO<TaskVO> pageVO); }
// ===================================================== // Project: profil-server // (c) Heike Winkelvoß // ===================================================== package de.egladil.web.profil_server.filter; import java.io.IOException; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import de.egladil.web.profil_server.ProfilServerApp; import de.egladil.web.profil_server.config.ConfigService; /** * SecureHeadersFilter */ @ApplicationScoped @Provider public class SecureHeadersFilter implements ContainerResponseFilter { private static final String CONTENT_SECURITY_POLICY = "Content-Security-Policy"; @Inject ConfigService config; @Override public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) throws IOException { final MultivaluedMap<String, Object> headers = responseContext.getHeaders(); addCORSHeaders(headers); if (headers.get("Cache-Control") == null) { headers.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"); } if (headers.get("X-Content-Type-Options") == null) { headers.add("X-Content-Type-Options", "nosniff"); } if (headers.get("X-Frame-Options") == null) { headers.add("X-Frame-Options", "DENY"); } if (headers.get("Server") == null) { headers.add("Server", "Hex"); } if (headers.get("X-Powered-By") == null) { headers.add("X-Powered-By", "Ponder Stibbons"); } if (headers.get("Vary") == null) { headers.add("Vary", "Origin"); } if (headers.get(CONTENT_SECURITY_POLICY) == null) { responseContext.getHeaders().add(CONTENT_SECURITY_POLICY, "default-src 'self'; "); } if (!ProfilServerApp.STAGE_DEV.equals(config.getStage()) && headers.get("Strict-Transport-Security") == null) { headers.add("Strict-Transport-Security", "max-age=63072000; includeSubdomains"); } if (headers.get("X-XSS-Protection") == null) { headers.add("X-XSS-Protection", "1; mode=block"); } if (headers.get("X-Frame-Options") == null) { headers.add("X-Frame-Options", "deny"); } } /** * Theoretisch könnte man dies auch über die Quarkus-Konfigurationsprameter machen. Es hat sich aber herausgestellt, dass dies * zu * volatil ist und die Browser mit den Konstanten nicht gut zurecht kommen und CORS-Blockaden erzeugen. Daher bitte nicht in * application.properties mit den Quarkus-CORS-Parametern konfigurieren, sondern hier. * * @param headers */ private void addCORSHeaders(final MultivaluedMap<String, Object> headers) { if (headers.get("Access-Control-Allow-Origin") == null) { headers.add("Access-Control-Allow-Origin", config.getAllowedOrigin()); } if (headers.get("Access-Control-Allow-Credentials") == null) { headers.add("Access-Control-Allow-Credentials", "true"); } // Achtung: mod-security verbietet standardmäßig PUT und DELETE. // Daher parallel in /etc/apache2/sites-available/opa-wetterwachs.conf die rule 911100 für profil-server entfernen, // sonst bekommt man 403 if (headers.get("Access-Control-Allow-Methods") == null) { headers.add("Access-Control-Allow-Methods", "POST, PUT, GET, HEAD, OPTIONS, DELETE"); } if (headers.get("Access-Control-Max-Age") == null) { headers.add("Access-Control-Max-Age", "" + config.getAccessControlMaxAge()); } if (headers.get("Access-Control-Allow-Headers") == null) { headers.add("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, Authorization,X-SESSIONID,X-XSRF-TOKEN"); } } }
/* * Copyright (c) 2010-2019 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_ws.framing; import org.java_ws.enums.Opcode; import org.java_ws.exceptions.InvalidDataException; import org.java_ws.exceptions.InvalidFrameException; import org.java_ws.util.ByteBufferUtils; import org.java_ws.util.Charsetfunctions; import java.nio.ByteBuffer; /** * Class to represent a close frame */ public class CloseFrame extends ControlFrame { /** * indicates a normal closure, meaning whatever purpose the * connection was established for has been fulfilled. */ public static final int NORMAL = 1000; /** * 1001 indicates that an endpoint is "going away", such as a server * going down, or a browser having navigated away from a page. */ public static final int GOING_AWAY = 1001; /** * 1002 indicates that an endpoint is terminating the connection due * to a protocol error. */ public static final int PROTOCOL_ERROR = 1002; /** * 1003 indicates that an endpoint is terminating the connection * because it has received a type of data it cannot accept (e.g. an * endpoint that understands only text data MAY send this if it * receives a binary message). */ public static final int REFUSE = 1003; /*1004: Reserved. The specific meaning might be defined in the future.*/ /** * 1005 is a reserved value and MUST NOT be set as a status code in a * Close control frame by an endpoint. It is designated for use in * applications expecting a status code to indicate that no status * code was actually present. */ public static final int NOCODE = 1005; /** * 1006 is a reserved value and MUST NOT be set as a status code in a * Close control frame by an endpoint. It is designated for use in * applications expecting a status code to indicate that the * connection was closed abnormally, e.g. without sending or * receiving a Close control frame. */ public static final int ABNORMAL_CLOSE = 1006; /** * 1007 indicates that an endpoint is terminating the connection * because it has received data within a message that was not * consistent with the type of the message (e.g., non-UTF-8 [RFC3629] * data within a text message). */ public static final int NO_UTF8 = 1007; /** * 1008 indicates that an endpoint is terminating the connection * because it has received a message that violates its policy. This * is a generic status code that can be returned when there is no * other more suitable status code (e.g. 1003 or 1009), or if there * is a need to hide specific details about the policy. */ public static final int POLICY_VALIDATION = 1008; /** * 1009 indicates that an endpoint is terminating the connection * because it has received a message which is too big for it to * process. */ public static final int TOOBIG = 1009; /** * 1010 indicates that an endpoint (client) is terminating the * connection because it has expected the server to negotiate one or * more extension, but the server didn't return them in the response * message of the WebSocket handshake. The list of extensions which * are needed SHOULD appear in the /reason/ part of the Close frame. * Note that this status code is not used by the server, because it * can fail the WebSocket handshake instead. */ public static final int EXTENSION = 1010; /** * 1011 indicates that a server is terminating the connection because * it encountered an unexpected condition that prevented it from * fulfilling the request. **/ public static final int UNEXPECTED_CONDITION = 1011; /** * 1012 indicates that the service is restarted. * A client may reconnect, and if it choses to do, should reconnect using a randomized delay of 5 - 30s. * See https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html for more information. * * @since 1.3.8 **/ public static final int SERVICE_RESTART = 1012; /** * 1013 indicates that the service is experiencing overload. * A client should only connect to a different IP (when there are multiple for the target) * or reconnect to the same IP upon user action. * See https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html for more information. * * @since 1.3.8 **/ public static final int TRY_AGAIN_LATER = 1013; /** * 1014 indicates that the server was acting as a gateway or proxy and received an * invalid response from the upstream server. This is similar to 502 HTTP Status Code * See https://www.ietf.org/mail-archive/web/hybi/current/msg10748.html fore more information. * * @since 1.3.8 **/ public static final int BAD_GATEWAY = 1014; /** * 1015 is a reserved value and MUST NOT be set as a status code in a * Close control frame by an endpoint. It is designated for use in * applications expecting a status code to indicate that the * connection was closed due to a failure to perform a TLS handshake * (e.g., the server certificate can't be verified). **/ public static final int TLS_ERROR = 1015; /** * The connection had never been established */ public static final int NEVER_CONNECTED = -1; /** * The connection had a buggy close (this should not happen) */ public static final int BUGGYCLOSE = -2; /** * The connection was flushed and closed */ public static final int FLASHPOLICY = -3; /** * The close code used in this close frame */ private int code; /** * The close message used in this close frame */ private String reason; /** * Constructor for a close frame * <p> * Using opcode closing and fin = true */ public CloseFrame() { super(Opcode.CLOSING); setReason(""); setCode(CloseFrame.NORMAL); } /** * Set the close code for this close frame * @param code the close code */ public void setCode(int code) { this.code = code; // CloseFrame.TLS_ERROR is not allowed to be transfered over the wire if (code == CloseFrame.TLS_ERROR) { this.code = CloseFrame.NOCODE; this.reason = ""; } updatePayload(); } /** * Set the close reason for this close frame * @param reason the reason code */ public void setReason(String reason) { if (reason == null) { reason = ""; } this.reason = reason; updatePayload(); } /** * Get the used close code * * @return the used close code */ public int getCloseCode() { return code; } /** * Get the message that closeframe is containing * * @return the message in this frame */ public String getMessage() { return reason; } @Override public String toString() { return super.toString() + "code: " + code; } @Override public void isValid() throws InvalidDataException { super.isValid(); if (code == CloseFrame.NO_UTF8 && reason.isEmpty()) { throw new InvalidDataException( CloseFrame.NO_UTF8, "Received text is no valid utf8 string!"); } if (code == CloseFrame.NOCODE && 0 < reason.length()) { throw new InvalidDataException(PROTOCOL_ERROR, "A close frame must have a closecode if it has a reason"); } //Intentional check for code != CloseFrame.TLS_ERROR just to make sure even if the code earlier changes if ((code > CloseFrame.TLS_ERROR && code < 3000)) { throw new InvalidDataException(PROTOCOL_ERROR, "Trying to send an illegal close code!"); } if (code == CloseFrame.ABNORMAL_CLOSE || code == CloseFrame.TLS_ERROR || code == CloseFrame.NOCODE || code > 4999 || code < 1000 || code == 1004) { throw new InvalidFrameException("closecode must not be sent over the wire: " + code); } } @Override public void setPayload(ByteBuffer payload) { code = CloseFrame.NOCODE; reason = ""; payload.mark(); if( payload.remaining() == 0 ) { code = CloseFrame.NORMAL; } else if( payload.remaining() == 1 ) { code = CloseFrame.PROTOCOL_ERROR; } else { if( payload.remaining() >= 2 ) { ByteBuffer bb = ByteBuffer.allocate( 4 ); bb.position( 2 ); bb.putShort( payload.getShort() ); bb.position( 0 ); code = bb.getInt(); } payload.reset(); try { int mark = payload.position();// because stringUtf8 also creates a mark validateUtf8(payload, mark); } catch ( InvalidDataException e ) { code = CloseFrame.NO_UTF8; reason = null; } } } /** * Validate the payload to valid utf8 * @param mark the current mark * @param payload the current payload * @throws InvalidDataException the current payload is not a valid utf8 */ private void validateUtf8(ByteBuffer payload, int mark) throws InvalidDataException { try { payload.position( payload.position() + 2 ); reason = Charsetfunctions.stringUtf8( payload ); } catch ( IllegalArgumentException e ) { throw new InvalidDataException( CloseFrame.NO_UTF8 ); } finally { payload.position( mark ); } } /** * Update the payload to represent the close code and the reason */ private void updatePayload() { byte[] by = Charsetfunctions.utf8Bytes(reason); ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(code); buf.position(2); ByteBuffer pay = ByteBuffer.allocate(2 + by.length); pay.put(buf); pay.put(by); pay.rewind(); super.setPayload(pay); } @Override public ByteBuffer getPayloadData() { if (code == NOCODE) return ByteBufferUtils.getEmptyByteBuffer(); return super.getPayloadData(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; CloseFrame that = (CloseFrame) o; if (code != that.code) return false; return reason != null ? reason.equals(that.reason) : that.reason == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + code; result = 31 * result + (reason != null ? reason.hashCode() : 0); return result; } }
package org.wso2.carbon.sample.service; public class OrgData { private String orgID;; private String orgName; OrgData() {} OrgData(String orgID, String orgName) { this.orgID = orgID; this.orgName = orgName; } public void setOrgID(String orgID) { this.orgID = orgID; } public void setOrgName(String orgName) { this.orgName = orgName; } public String getOrgID() { return orgID; } public String getOrgName() { return orgName; } }
/** * 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.apex.malhar.lib.window.sample.pi; import org.joda.time.Duration; import org.apache.apex.malhar.lib.window.Accumulation; import org.apache.apex.malhar.lib.window.TriggerOption; import org.apache.apex.malhar.lib.window.Tuple; import org.apache.apex.malhar.lib.window.WindowOption; import org.apache.apex.malhar.lib.window.WindowState; import org.apache.apex.malhar.lib.window.impl.InMemoryWindowedStorage; import org.apache.apex.malhar.lib.window.impl.WindowedOperatorImpl; import org.apache.commons.lang3.mutable.MutableLong; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.hadoop.conf.Configuration; import com.datatorrent.api.DAG; import com.datatorrent.api.DefaultOutputPort; import com.datatorrent.api.InputOperator; import com.datatorrent.api.LocalMode; import com.datatorrent.api.StreamingApplication; import com.datatorrent.common.util.BaseOperator; import com.datatorrent.lib.io.ConsoleOutputOperator; /** * This is an example of using the WindowedOperator concepts to calculate the value of pi. */ public class Application implements StreamingApplication { public static class RandomNumberPairGenerator extends BaseOperator implements InputOperator { public final transient DefaultOutputPort<Tuple<MutablePair<Double, Double>>> output = new DefaultOutputPort<>(); @Override public void emitTuples() { Tuple.PlainTuple<MutablePair<Double, Double>> tuple = new Tuple.PlainTuple<>(new MutablePair<>(Math.random(), Math.random())); this.output.emit(tuple); } } public static class PiAccumulation implements Accumulation<MutablePair<Double, Double>, MutablePair<MutableLong, MutableLong>, Double> { @Override public MutablePair<MutableLong, MutableLong> defaultAccumulatedValue() { return new MutablePair<>(new MutableLong(0), new MutableLong(0)); } @Override public MutablePair<MutableLong, MutableLong> accumulate(MutablePair<MutableLong, MutableLong> accumulatedValue, MutablePair<Double, Double> input) { if (input.getLeft() * input.getLeft() + input.getRight() * input.getRight() < 1) { accumulatedValue.getLeft().increment(); } accumulatedValue.getRight().increment(); return accumulatedValue; } @Override public MutablePair<MutableLong, MutableLong> merge(MutablePair<MutableLong, MutableLong> accumulatedValue1, MutablePair<MutableLong, MutableLong> accumulatedValue2) { accumulatedValue1.getLeft().add(accumulatedValue2.getLeft()); accumulatedValue1.getRight().add(accumulatedValue2.getRight()); return accumulatedValue1; } @Override public Double getOutput(MutablePair<MutableLong, MutableLong> accumulatedValue) { return accumulatedValue.getRight().longValue() == 0 ? 0.0 : (((double)accumulatedValue.getLeft().longValue()) * 4 / accumulatedValue.getRight().longValue()); } @Override public Double getRetraction(Double value) { return -value; } } @Override public void populateDAG(DAG dag, Configuration configuration) { RandomNumberPairGenerator inputOperator = new RandomNumberPairGenerator(); WindowedOperatorImpl<MutablePair<Double, Double>, MutablePair<MutableLong, MutableLong>, Double> windowedOperator = new WindowedOperatorImpl<>(); Accumulation<MutablePair<Double, Double>, MutablePair<MutableLong, MutableLong>, Double> piAccumulation = new PiAccumulation(); windowedOperator.setAccumulation(piAccumulation); windowedOperator.setDataStorage(new InMemoryWindowedStorage<MutablePair<MutableLong, MutableLong>>()); windowedOperator.setWindowStateStorage(new InMemoryWindowedStorage<WindowState>()); windowedOperator.setWindowOption(new WindowOption.GlobalWindow()); windowedOperator.setTriggerOption(TriggerOption.AtWatermark().withEarlyFiringsAtEvery(Duration.millis(1000)).accumulatingFiredPanes()); ConsoleOutputOperator outputOperator = new ConsoleOutputOperator(); dag.addOperator("inputOperator", inputOperator); dag.addOperator("windowedOperator", windowedOperator); dag.addOperator("outputOperator", outputOperator); dag.addStream("input_windowed", inputOperator.output, windowedOperator.input); dag.addStream("windowed_output", windowedOperator.output, outputOperator.input); } public static void main(String[] args) throws Exception { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); lma.prepareDAG(new Application(), conf); LocalMode.Controller lc = lma.getController(); lc.run(); } }
/* * Copyright DataStax, 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.datastax.dse.driver.internal.core.graph.binary; import com.datastax.dse.driver.internal.core.graph.TinkerpopBufferUtil; import com.datastax.dse.driver.internal.core.graph.binary.buffer.DseNettyBufferFactory; import com.datastax.dse.driver.internal.core.protocol.TinkerpopBufferPrimitiveCodec; import com.datastax.oss.driver.api.core.data.GettableByIndex; import com.datastax.oss.driver.api.core.data.SettableByIndex; import com.datastax.oss.driver.api.core.type.CustomType; import com.datastax.oss.driver.api.core.type.DataType; import com.datastax.oss.driver.api.core.type.ListType; import com.datastax.oss.driver.api.core.type.MapType; import com.datastax.oss.driver.api.core.type.SetType; import com.datastax.oss.driver.api.core.type.TupleType; import com.datastax.oss.driver.api.core.type.UserDefinedType; import com.datastax.oss.driver.internal.core.context.DefaultDriverContext; import com.datastax.oss.driver.internal.core.type.DataTypeHelper; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.datastax.oss.protocol.internal.PrimitiveCodec; import com.datastax.oss.protocol.internal.ProtocolConstants; import com.datastax.oss.protocol.internal.response.result.RawType; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.Objects; import org.apache.tinkerpop.gremlin.structure.io.Buffer; class ComplexTypeSerializerUtil { private static final PrimitiveCodec<Buffer> codec = new TinkerpopBufferPrimitiveCodec(new DseNettyBufferFactory()); static void encodeTypeDefinition( DataType type, Buffer buffer, DefaultDriverContext driverContext) { RawType protocolType = toProtocolSpec(type); protocolType.encode(buffer, codec, driverContext.getProtocolVersion().getCode()); } static DataType decodeTypeDefinition(Buffer buffer, DefaultDriverContext driverContext) { RawType type = RawType.decode(buffer, codec, driverContext.getProtocolVersion().getCode()); return DataTypeHelper.fromProtocolSpec(type, driverContext); } /* Tinkerpop-based encoding of UDT values, based on the UdtCoded.encode() method, but using Tinkerpop buffers directly to avoid unnecessary NIO ByteBuffer copies. */ static void encodeValue(@Nullable GettableByIndex value, Buffer tinkerBuff) { if (value == null) { return; } for (int i = 0; i < value.size(); i++) { ByteBuffer fieldBuffer = value.getBytesUnsafe(i); if (fieldBuffer == null) { tinkerBuff.writeInt(-1); } else { tinkerBuff.writeInt(fieldBuffer.remaining()); tinkerBuff.writeBytes(fieldBuffer.duplicate()); } } } /* This method will move forward the Tinkerpop buffer given in parameter based on the UDT value read. Content of the method is roughly equivalent to UdtCodec.decode(), but using Tinkerpop buffers directly to avoid unnecessary NIO ByteBuffer copies. */ static <T extends SettableByIndex<T>> T decodeValue(Buffer tinkerBuff, T val, int size) { try { for (int i = 0; i < size; i++) { int fieldSize = tinkerBuff.readInt(); if (fieldSize >= 0) { // the reassignment is to shut down the error-prone warning about ignoring return values. val = val.setBytesUnsafe(i, TinkerpopBufferUtil.readBytes(tinkerBuff, fieldSize)); } } return val; } catch (BufferUnderflowException e) { throw new IllegalArgumentException("Not enough bytes to deserialize a UDT value", e); } } private static RawType toProtocolSpec(DataType dataType) { int id = dataType.getProtocolCode(); RawType type = RawType.PRIMITIVES.get(id); if (type != null) { return type; } switch (id) { case ProtocolConstants.DataType.CUSTOM: CustomType customType = ((CustomType) dataType); type = new RawType.RawCustom(customType.getClassName()); break; case ProtocolConstants.DataType.LIST: ListType listType = ((ListType) dataType); type = new RawType.RawList(toProtocolSpec(listType.getElementType())); break; case ProtocolConstants.DataType.SET: SetType setType = ((SetType) dataType); type = new RawType.RawSet(toProtocolSpec(setType.getElementType())); break; case ProtocolConstants.DataType.MAP: MapType mapType = ((MapType) dataType); type = new RawType.RawMap( toProtocolSpec(mapType.getKeyType()), toProtocolSpec(mapType.getValueType())); break; case ProtocolConstants.DataType.TUPLE: TupleType tupleType = ((TupleType) dataType); ImmutableList.Builder<RawType> subTypesList = ImmutableList.builderWithExpectedSize(tupleType.getComponentTypes().size()); for (int i = 0; i < tupleType.getComponentTypes().size(); i++) { subTypesList.add(toProtocolSpec(tupleType.getComponentTypes().get(i))); } type = new RawType.RawTuple(subTypesList.build()); break; case ProtocolConstants.DataType.UDT: UserDefinedType userDefinedType = ((UserDefinedType) dataType); ImmutableMap.Builder<String, RawType> subTypesMap = ImmutableMap.builderWithExpectedSize(userDefinedType.getFieldNames().size()); for (int i = 0; i < userDefinedType.getFieldTypes().size(); i++) { subTypesMap.put( userDefinedType.getFieldNames().get(i).asInternal(), toProtocolSpec(userDefinedType.getFieldTypes().get(i))); } type = new RawType.RawUdt( Objects.requireNonNull(userDefinedType.getKeyspace()).asInternal(), userDefinedType.getName().asInternal(), subTypesMap.build()); break; default: throw new IllegalArgumentException("Unsupported type: " + dataType.asCql(true, true)); } return type; } }
/* * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Nick Santos * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package com.google.javascript.rhino; import static com.google.javascript.rhino.JSDocInfo.Visibility.PRIVATE; import static com.google.javascript.rhino.JSDocInfo.Visibility.PROTECTED; import static com.google.javascript.rhino.JSDocInfo.Visibility.PUBLIC; import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE; import com.google.common.collect.Sets; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.testing.Asserts; import com.google.javascript.rhino.testing.TestErrorReporter; import junit.framework.TestCase; public class JSDocInfoTest extends TestCase { private TestErrorReporter errorReporter = new TestErrorReporter(null, null); private JSTypeRegistry registry = new JSTypeRegistry(errorReporter); private JSType getNativeType(JSTypeNative typeId) { return registry.getNativeType(typeId); } /** * Tests the assigned ordinal of the elements of the * {@link JSDocInfo.Visibility} enum. */ public void testVisibilityOrdinal() { assertEquals(0, PRIVATE.ordinal()); assertEquals(1, PROTECTED.ordinal()); assertEquals(2, PUBLIC.ordinal()); } public void testSetType() { JSDocInfo info = new JSDocInfo(); info.setType(fromString("string")); assertNull(info.getBaseType()); assertNull(info.getDescription()); assertNull(info.getEnumParameterType()); assertEquals(0, info.getParameterCount()); assertNull(info.getReturnType()); assertTypeEquals(STRING_TYPE, resolve(info.getType())); assertNull(info.getVisibility()); assertTrue(info.hasType()); assertFalse(info.isConstant()); assertFalse(info.isConstructor()); assertFalse(info.isHidden()); assertFalse(info.shouldPreserveTry()); } public void testSetTypeAndVisibility() { JSDocInfo info = new JSDocInfo(); info.setType(fromString("string")); info.setVisibility(PROTECTED); assertNull(info.getBaseType()); assertNull(info.getDescription()); assertNull(info.getEnumParameterType()); assertEquals(0, info.getParameterCount()); assertNull(info.getReturnType()); assertTypeEquals(STRING_TYPE, resolve(info.getType())); assertEquals(PROTECTED, info.getVisibility()); assertTrue(info.hasType()); assertFalse(info.isConstant()); assertFalse(info.isConstructor()); assertFalse(info.isHidden()); assertFalse(info.shouldPreserveTry()); } public void testSetReturnType() { JSDocInfo info = new JSDocInfo(); info.setReturnType(fromString("string")); assertNull(info.getBaseType()); assertNull(info.getDescription()); assertNull(info.getEnumParameterType()); assertEquals(0, info.getParameterCount()); assertTypeEquals(STRING_TYPE, resolve(info.getReturnType())); assertNull(info.getType()); assertNull(info.getVisibility()); assertFalse(info.hasType()); assertFalse(info.isConstant()); assertFalse(info.isConstructor()); assertFalse(info.isHidden()); assertFalse(info.shouldPreserveTry()); } public void testSetReturnTypeAndBaseType() { JSDocInfo info = new JSDocInfo(); info.setBaseType( new JSTypeExpression( new Node(Token.BANG, Node.newString("Number")), "")); info.setReturnType(fromString("string")); assertTypeEquals(NUMBER_OBJECT_TYPE, resolve(info.getBaseType())); assertNull(info.getDescription()); assertNull(info.getEnumParameterType()); assertEquals(0, info.getParameterCount()); assertTypeEquals(STRING_TYPE, resolve(info.getReturnType())); assertNull(info.getType()); assertNull(info.getVisibility()); assertFalse(info.hasType()); assertFalse(info.isConstant()); assertFalse(info.isConstructor()); assertFalse(info.isHidden()); assertFalse(info.shouldPreserveTry()); } public void testSetEnumParameterType() { JSDocInfo info = new JSDocInfo(); info.setEnumParameterType(fromString("string")); assertNull(info.getBaseType()); assertNull(info.getDescription()); assertTypeEquals(STRING_TYPE, resolve(info.getEnumParameterType())); assertEquals(0, info.getParameterCount()); assertNull(info.getReturnType()); assertNull(info.getType()); assertNull(info.getVisibility()); assertFalse(info.hasType()); assertFalse(info.isConstant()); assertFalse(info.isConstructor()); assertFalse(info.isHidden()); assertFalse(info.shouldPreserveTry()); } public void testMultipleSetType() { JSDocInfo info = new JSDocInfo(); info.setType(fromString("number")); try { info.setReturnType(fromString("boolean")); fail("Expected exception"); } catch (IllegalStateException e) {} try { info.setEnumParameterType(fromString("string")); fail("Expected exception"); } catch (IllegalStateException e) {} try { info.setTypedefType(fromString("string")); fail("Expected exception"); } catch (IllegalStateException e) {} assertTypeEquals(NUMBER_TYPE, resolve(info.getType())); assertNull(info.getReturnType()); assertNull(info.getEnumParameterType()); assertNull(info.getTypedefType()); assertTrue(info.hasType()); } public void testMultipleSetType2() { JSDocInfo info = new JSDocInfo(); info.setReturnType(fromString("boolean")); try { info.setType(fromString("number")); fail("Expected exception"); } catch (IllegalStateException e) {} try { info.setEnumParameterType(fromString("string")); fail("Expected exception"); } catch (IllegalStateException e) {} try { info.setTypedefType(fromString("string")); fail("Expected exception"); } catch (IllegalStateException e) {} assertTypeEquals(BOOLEAN_TYPE, resolve(info.getReturnType())); assertNull(info.getEnumParameterType()); assertNull(info.getType()); assertNull(info.getTypedefType()); assertFalse(info.hasType()); } public void testMultipleSetType3() { JSDocInfo info = new JSDocInfo(); info.setEnumParameterType(fromString("boolean")); try { info.setType(fromString("number")); fail("Expected exception"); } catch (IllegalStateException e) {} try { info.setReturnType(fromString("string")); fail("Expected exception"); } catch (IllegalStateException e) {} try { info.setTypedefType(fromString("string")); fail("Expected exception"); } catch (IllegalStateException e) {} assertNull(info.getType()); assertNull(info.getTypedefType()); assertNull(info.getReturnType()); assertTypeEquals(BOOLEAN_TYPE, resolve(info.getEnumParameterType())); } public void testSetTypedefType() { JSDocInfo info = new JSDocInfo(); info.setTypedefType(fromString("boolean")); assertTypeEquals(BOOLEAN_TYPE, resolve(info.getTypedefType())); assertTrue(info.hasTypedefType()); assertFalse(info.hasType()); assertFalse(info.hasEnumParameterType()); assertFalse(info.hasReturnType()); } public void testSetConstant() { JSDocInfo info = new JSDocInfo(); info.setConstant(true); assertFalse(info.hasType()); assertTrue(info.isConstant()); assertFalse(info.isConstructor()); assertFalse(info.isDefine()); assertFalse(info.isHidden()); assertFalse(info.shouldPreserveTry()); } public void testSetConstructor() { JSDocInfo info = new JSDocInfo(); info.setConstructor(true); assertFalse(info.isConstant()); assertTrue(info.isConstructor()); assertFalse(info.isDefine()); assertFalse(info.isHidden()); assertFalse(info.shouldPreserveTry()); } public void testSetDefine() { JSDocInfo info = new JSDocInfo(); info.setDefine(true); assertTrue(info.isConstant()); assertFalse(info.isConstructor()); assertTrue(info.isDefine()); assertFalse(info.isHidden()); assertFalse(info.shouldPreserveTry()); } public void testSetHidden() { JSDocInfo info = new JSDocInfo(); info.setHidden(true); assertFalse(info.hasType()); assertFalse(info.isConstant()); assertFalse(info.isConstructor()); assertFalse(info.isDefine()); assertTrue(info.isHidden()); assertFalse(info.shouldPreserveTry()); } public void testSetShouldPreserveTry() { JSDocInfo info = new JSDocInfo(); info.setShouldPreserveTry(true); assertFalse(info.isConstant()); assertFalse(info.isConstructor()); assertFalse(info.isDefine()); assertFalse(info.isHidden()); assertTrue(info.shouldPreserveTry()); } public void testSetNoTypeCheck() { JSDocInfo info = new JSDocInfo(); info.setNoCheck(true); assertFalse(info.isDeprecated()); assertFalse(info.isNoAlias()); assertFalse(info.isOverride()); assertTrue(info.isNoTypeCheck()); } public void testSetOverride() { JSDocInfo info = new JSDocInfo(); info.setOverride(true); assertFalse(info.isDeprecated()); assertFalse(info.isNoAlias()); assertTrue(info.isOverride()); } public void testSetExport() { JSDocInfo info = new JSDocInfo(); info.setExport(true); assertTrue(info.isExport()); } public void testSetNoAlias() { JSDocInfo info = new JSDocInfo(); info.setNoAlias(true); assertFalse(info.isDeprecated()); assertFalse(info.isOverride()); assertTrue(info.isNoAlias()); } public void testSetDeprecated() { JSDocInfo info = new JSDocInfo(); info.setDeprecated(true); assertFalse(info.isNoAlias()); assertFalse(info.isOverride()); assertTrue(info.isDeprecated()); } public void testMultipleSetFlags1() { JSDocInfo info = new JSDocInfo(); info.setConstant(true); info.setConstructor(true); info.setHidden(true); info.setShouldPreserveTry(true); assertFalse(info.hasType()); assertTrue(info.isConstant()); assertTrue(info.isConstructor()); assertFalse(info.isDefine()); assertTrue(info.isHidden()); assertTrue(info.shouldPreserveTry()); info.setHidden(false); assertTrue(info.isConstant()); assertTrue(info.isConstructor()); assertFalse(info.isDefine()); assertFalse(info.isHidden()); assertTrue(info.shouldPreserveTry()); info.setConstant(false); info.setConstructor(false); assertFalse(info.isConstant()); assertFalse(info.isConstructor()); assertFalse(info.isDefine()); assertFalse(info.isHidden()); assertTrue(info.shouldPreserveTry()); info.setConstructor(true); assertFalse(info.isConstant()); assertTrue(info.isConstructor()); assertFalse(info.isDefine()); assertFalse(info.isHidden()); assertTrue(info.shouldPreserveTry()); } public void testSetFileOverviewWithDocumentationOff() { JSDocInfo info = new JSDocInfo(); info.documentFileOverview("hi bob"); assertNull(info.getFileOverview()); } public void testSetFileOverviewWithDocumentationOn() { JSDocInfo info = new JSDocInfo(true); info.documentFileOverview("hi bob"); assertEquals("hi bob", info.getFileOverview()); } public void testSetSuppressions() { JSDocInfo info = new JSDocInfo(true); info.setSuppressions(Sets.newHashSet("sam", "bob")); assertEquals(Sets.newHashSet("bob", "sam"), info.getSuppressions()); } public void testSetModifies() { JSDocInfo info = new JSDocInfo(true); info.setModifies(Sets.newHashSet("this")); assertEquals(Sets.newHashSet("this"), info.getModifies()); info = new JSDocInfo(true); info.setModifies(Sets.newHashSet("arguments")); assertEquals(Sets.newHashSet("arguments"), info.getModifies()); } /** Gets the type expression for a simple type name. */ private JSTypeExpression fromString(String s) { return new JSTypeExpression(Node.newString(s), ""); } private JSType resolve(JSTypeExpression n, String... warnings) { errorReporter.setWarnings(warnings); return n.evaluate(null, registry); } private void assertTypeEquals(JSTypeNative a, JSType b) { assertTypeEquals(getNativeType(a), b); } private void assertTypeEquals(JSType a, JSType b) { Asserts.assertTypeEquals(a, b); } }
package com.prowidesoftware.swift.model.mx; import com.prowidesoftware.swift.model.mx.dic.*; import com.prowidesoftware.swift.model.mx.AbstractMX; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.prowidesoftware.swift.model.MxSwiftMessage; import com.prowidesoftware.swift.model.mx.MxRead; import com.prowidesoftware.swift.model.mx.MxReadConfiguration; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Class for caaa.009.001.05 ISO 20022 message. * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Document", propOrder = { "accptrRcncltnReq" }) @XmlRootElement(name = "Document", namespace = "urn:iso:std:iso:20022:tech:xsd:caaa.009.001.05") public class MxCaaa00900105 extends com.prowidesoftware.swift.model.mx.AbstractMX { @XmlElement(name = "AccptrRcncltnReq", required = true) protected AcceptorReconciliationRequestV05 accptrRcncltnReq; public final static transient String BUSINESS_PROCESS = "caaa"; public final static transient int FUNCTIONALITY = 9; public final static transient int VARIANT = 1; public final static transient int VERSION = 5; @SuppressWarnings("rawtypes") public final static transient Class[] _classes = new Class[] {AcceptorReconciliationRequest5 .class, AcceptorReconciliationRequestV05 .class, Acquirer4 .class, Algorithm11Code.class, Algorithm12Code.class, Algorithm13Code.class, Algorithm7Code.class, Algorithm8Code.class, AlgorithmIdentification11 .class, AlgorithmIdentification12 .class, AlgorithmIdentification13 .class, AlgorithmIdentification15 .class, AttributeType1Code.class, AuthenticatedData4 .class, BytePadding1Code.class, CardPaymentEnvironment50 .class, CertificateIssuer1 .class, CommunicationCharacteristics2 .class, ContentInformationType15 .class, ContentType2Code.class, EncapsulatedContent3 .class, EncryptionFormat1Code.class, GenericIdentification48 .class, GenericIdentification53 .class, GenericIdentification76 .class, GenericIdentification94 .class, Header30 .class, IssuerAndSerialNumber1 .class, KEK4 .class, KEKIdentifier2 .class, KeyTransport4 .class, MemoryCharacteristics1 .class, MemoryUnit1Code.class, MessageFunction10Code.class, MxCaaa00900105 .class, NetworkParameters4 .class, NetworkParameters5 .class, NetworkType1Code.class, POICommunicationType1Code.class, POIComponentAssessment1Code.class, POIComponentStatus1Code.class, POIComponentType4Code.class, Parameter4 .class, Parameter5 .class, Parameter6 .class, Parameter7 .class, PartyType3Code.class, PartyType4Code.class, PartyType7Code.class, PointOfInteractionComponent6 .class, PointOfInteractionComponentAssessment1 .class, PointOfInteractionComponentCharacteristics2 .class, PointOfInteractionComponentIdentification1 .class, PointOfInteractionComponentStatus3 .class, Recipient4Choice.class, Recipient5Choice.class, RelativeDistinguishedName1 .class, Traceability5 .class, TransactionIdentifier1 .class, TransactionReconciliation4 .class, TransactionTotals7 .class, TypeTransactionTotals2Code.class }; public final static transient String NAMESPACE = "urn:iso:std:iso:20022:tech:xsd:caaa.009.001.05"; public MxCaaa00900105() { super(); } /** * Creates the MX object parsing the parameter String with the XML content * */ public MxCaaa00900105(final String xml) { this(); MxCaaa00900105 tmp = parse(xml); accptrRcncltnReq = tmp.getAccptrRcncltnReq(); } /** * Creates the MX object parsing the raw content from the parameter MxSwiftMessage * */ public MxCaaa00900105(final MxSwiftMessage mxSwiftMessage) { this(mxSwiftMessage.message()); } /** * Gets the value of the accptrRcncltnReq property. * * @return * possible object is * {@link AcceptorReconciliationRequestV05 } * */ public AcceptorReconciliationRequestV05 getAccptrRcncltnReq() { return accptrRcncltnReq; } /** * Sets the value of the accptrRcncltnReq property. * * @param value * allowed object is * {@link AcceptorReconciliationRequestV05 } * */ public MxCaaa00900105 setAccptrRcncltnReq(AcceptorReconciliationRequestV05 value) { this.accptrRcncltnReq = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public String getBusinessProcess() { return BUSINESS_PROCESS; } @Override public int getFunctionality() { return FUNCTIONALITY; } @Override public int getVariant() { return VARIANT; } @Override public int getVersion() { return VERSION; } /** * Creates the MX object parsing the raw content from the parameter XML, using default unmarshalling options * */ public static MxCaaa00900105 parse(String xml) { return ((MxCaaa00900105) com.prowidesoftware.swift.model.mx.MxReadImpl.parse(MxCaaa00900105 .class, xml, _classes, new com.prowidesoftware.swift.model.mx.MxReadParams())); } /** * Creates the MX object parsing the raw content from the parameter XML, using the provided unmarshalling options * @since 9.2.6 * */ public static MxCaaa00900105 parse(String xml, MxReadConfiguration conf) { return ((MxCaaa00900105) com.prowidesoftware.swift.model.mx.MxReadImpl.parse(MxCaaa00900105 .class, xml, _classes, new com.prowidesoftware.swift.model.mx.MxReadParams(conf))); } /** * Creates the MX object parsing the raw content from the parameter XML with injected read implementation * @since 9.0.1 * * @param parserImpl an MX unmarshall implementation */ public static MxCaaa00900105 parse(String xml, MxRead parserImpl) { return ((MxCaaa00900105) parserImpl.read(MxCaaa00900105 .class, xml, _classes)); } @Override public String getNamespace() { return NAMESPACE; } @Override @SuppressWarnings("rawtypes") public Class[] getClasses() { return _classes; } /** * Creates an MxCaaa00900105 messages from its JSON representation. * <p> * For generic conversion of JSON into the corresponding MX instance * see {@link AbstractMX#fromJson(String)} * * @since 7.10.2 * * @param json a JSON representation of an MxCaaa00900105 message * @return * a new instance of MxCaaa00900105 */ public final static MxCaaa00900105 fromJson(String json) { return com.prowidesoftware.swift.model.mx.AbstractMX.fromJson(json, MxCaaa00900105 .class); } }
package com.geekbang.shengfq.week6.stream; import lombok.Data; import java.io.Serializable; import java.time.LocalDate; import java.util.Comparator; /** * 生产资料 * @author sheng * */ @Data public class Book implements Comparable, Serializable { private int id; private String name; private double price; private String type; private LocalDate publishDate; public Book(int id, String name, double price, String type, LocalDate publishDate) { this.id = id; this.name = name; this.price = price; this.type = type; this.publishDate = publishDate; } @Override public int hashCode(){ return this.name.hashCode(); } @Override public boolean equals(Object obj){ if(!(obj instanceof Book)){ return false; } Book target=(Book)obj; return this.name.equalsIgnoreCase(target.getName()); } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", price=" + price + ", type=" + type + ", publishDate=" + publishDate + "]"; } @Override public int compareTo(Object o) { return 0; } }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.0. You may not use this file * except in compliance with the Zeebe Community License 1.0. */ package io.zeebe.distributedlog; import java.io.File; /** * Represents the storage configuration of a partition. It keeps the path of the local data * directory for * * <ul> * <li>logstream segments * <li>log block index * <li>log block index snapshots * <li>stream processor state * </ul> */ public class StorageConfiguration { private final File logDirectory; private final File statesDirectory; private int partitionId; private int logSegmentSize; private int maxFragmentSize; public StorageConfiguration(final File partitionLogDir, final File statesDir) { logDirectory = partitionLogDir; statesDirectory = statesDir; } public int getPartitionId() { return partitionId; } public StorageConfiguration setPartitionId(final int partitionId) { this.partitionId = partitionId; return this; } public File getLogDirectory() { return logDirectory; } public int getLogSegmentSize() { return logSegmentSize; } public StorageConfiguration setLogSegmentSize(final int value) { logSegmentSize = value; return this; } public File getStatesDirectory() { return statesDirectory; } public int getMaxFragmentSize() { return maxFragmentSize; } public StorageConfiguration setMaxFragmentSize(final int maxFragmentSize) { this.maxFragmentSize = maxFragmentSize; return this; } }
/* * Copyright 2015 Karl Dahlgren * * 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.castlemock.core.mock.soap.model.event.domain; import com.castlemock.core.basis.model.http.domain.HttpHeader; import com.castlemock.core.basis.model.http.domain.HttpMethod; import com.castlemock.core.mock.soap.model.project.domain.SoapOperationIdentifier; import com.castlemock.core.mock.soap.model.project.domain.SoapVersion; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import java.util.Objects; /** * @author Karl Dahlgren * @since 1.0 */ @XmlRootElement public class SoapRequest { private String body; private String envelope; private String contentType; private String uri; private HttpMethod httpMethod; private String operationName; private SoapVersion soapVersion; private List<HttpHeader> httpHeaders; private SoapOperationIdentifier operationIdentifier; public SoapRequest(){ } private SoapRequest(final Builder builder){ this.body = builder.body; this.envelope = builder.envelope; this.contentType = builder.contentType; this.uri = Objects.requireNonNull(builder.uri); this.httpMethod = Objects.requireNonNull(builder.httpMethod); this.operationName = builder.operationName; this.soapVersion = Objects.requireNonNull(builder.soapVersion); this.httpHeaders = Objects.requireNonNull(builder.httpHeaders); this.operationIdentifier = Objects.requireNonNull(builder.operationIdentifier); } @XmlElement public String getBody() { return body; } public void setBody(String body) { this.body = body; } @XmlElement public String getEnvelope() { return envelope; } public void setEnvelope(String envelope) { this.envelope = envelope; } @XmlElement public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } @XmlElement public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } @XmlElement public HttpMethod getHttpMethod() { return httpMethod; } public void setHttpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; } @XmlElement public String getOperationName() { return operationName; } public void setOperationName(String operationName) { this.operationName = operationName; } @XmlElement public SoapOperationIdentifier getOperationIdentifier() { return operationIdentifier; } public void setOperationIdentifier(SoapOperationIdentifier operationIdentifier) { this.operationIdentifier = operationIdentifier; } @XmlElement public SoapVersion getSoapVersion() { return soapVersion; } public void setSoapVersion(SoapVersion soapVersion) { this.soapVersion = soapVersion; } @XmlElement public List<HttpHeader> getHttpHeaders() { return httpHeaders; } public void setHttpHeaders(List<HttpHeader> httpHeaders) { this.httpHeaders = httpHeaders; } public static Builder builder() { return new Builder(); } public static final class Builder { private String body; private String envelope; private String contentType; private String uri; private HttpMethod httpMethod; private String operationName; private SoapVersion soapVersion; private List<HttpHeader> httpHeaders; private SoapOperationIdentifier operationIdentifier; private Builder() { } public Builder body(final String body) { this.body = body; return this; } public Builder envelope(final String envelope) { this.envelope = envelope; return this; } public Builder contentType(final String contentType) { this.contentType = contentType; return this; } public Builder uri(final String uri) { this.uri = uri; return this; } public Builder httpMethod(final HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } public Builder operationName(final String operationName) { this.operationName = operationName; return this; } public Builder soapVersion(final SoapVersion soapVersion) { this.soapVersion = soapVersion; return this; } public Builder httpHeaders(final List<HttpHeader> httpHeaders) { this.httpHeaders = httpHeaders; return this; } public Builder operationIdentifier(final SoapOperationIdentifier operationIdentifier) { this.operationIdentifier = operationIdentifier; return this; } public SoapRequest build() { return new SoapRequest(this); } } }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cdb.v20170320.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeTimeWindowResponse extends AbstractModel{ /** * List of maintenance time windows on Monday. */ @SerializedName("Monday") @Expose private String [] Monday; /** * List of maintenance time windows on Tuesday. */ @SerializedName("Tuesday") @Expose private String [] Tuesday; /** * List of maintenance time windows on Wednesday. */ @SerializedName("Wednesday") @Expose private String [] Wednesday; /** * List of maintenance time windows on Thursday. */ @SerializedName("Thursday") @Expose private String [] Thursday; /** * List of maintenance time windows on Friday. */ @SerializedName("Friday") @Expose private String [] Friday; /** * List of maintenance time windows on Saturday. */ @SerializedName("Saturday") @Expose private String [] Saturday; /** * List of maintenance time windows on Sunday. */ @SerializedName("Sunday") @Expose private String [] Sunday; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get List of maintenance time windows on Monday. * @return Monday List of maintenance time windows on Monday. */ public String [] getMonday() { return this.Monday; } /** * Set List of maintenance time windows on Monday. * @param Monday List of maintenance time windows on Monday. */ public void setMonday(String [] Monday) { this.Monday = Monday; } /** * Get List of maintenance time windows on Tuesday. * @return Tuesday List of maintenance time windows on Tuesday. */ public String [] getTuesday() { return this.Tuesday; } /** * Set List of maintenance time windows on Tuesday. * @param Tuesday List of maintenance time windows on Tuesday. */ public void setTuesday(String [] Tuesday) { this.Tuesday = Tuesday; } /** * Get List of maintenance time windows on Wednesday. * @return Wednesday List of maintenance time windows on Wednesday. */ public String [] getWednesday() { return this.Wednesday; } /** * Set List of maintenance time windows on Wednesday. * @param Wednesday List of maintenance time windows on Wednesday. */ public void setWednesday(String [] Wednesday) { this.Wednesday = Wednesday; } /** * Get List of maintenance time windows on Thursday. * @return Thursday List of maintenance time windows on Thursday. */ public String [] getThursday() { return this.Thursday; } /** * Set List of maintenance time windows on Thursday. * @param Thursday List of maintenance time windows on Thursday. */ public void setThursday(String [] Thursday) { this.Thursday = Thursday; } /** * Get List of maintenance time windows on Friday. * @return Friday List of maintenance time windows on Friday. */ public String [] getFriday() { return this.Friday; } /** * Set List of maintenance time windows on Friday. * @param Friday List of maintenance time windows on Friday. */ public void setFriday(String [] Friday) { this.Friday = Friday; } /** * Get List of maintenance time windows on Saturday. * @return Saturday List of maintenance time windows on Saturday. */ public String [] getSaturday() { return this.Saturday; } /** * Set List of maintenance time windows on Saturday. * @param Saturday List of maintenance time windows on Saturday. */ public void setSaturday(String [] Saturday) { this.Saturday = Saturday; } /** * Get List of maintenance time windows on Sunday. * @return Sunday List of maintenance time windows on Sunday. */ public String [] getSunday() { return this.Sunday; } /** * Set List of maintenance time windows on Sunday. * @param Sunday List of maintenance time windows on Sunday. */ public void setSunday(String [] Sunday) { this.Sunday = Sunday; } /** * Get The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @return RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem. */ public String getRequestId() { return this.RequestId; } /** * Set The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @param RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem. */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamArraySimple(map, prefix + "Monday.", this.Monday); this.setParamArraySimple(map, prefix + "Tuesday.", this.Tuesday); this.setParamArraySimple(map, prefix + "Wednesday.", this.Wednesday); this.setParamArraySimple(map, prefix + "Thursday.", this.Thursday); this.setParamArraySimple(map, prefix + "Friday.", this.Friday); this.setParamArraySimple(map, prefix + "Saturday.", this.Saturday); this.setParamArraySimple(map, prefix + "Sunday.", this.Sunday); this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
/* This file is part of the iText (R) project. Copyright (c) 1998-2021 iText Group NV Authors: iText Software. This program is offered under a commercial and under the AGPL license. For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. AGPL licensing: This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.itextpdf.html2pdf.css.w3c.css21.backgrounds; import com.itextpdf.html2pdf.css.w3c.W3CCssTest; public class BackgroundColor077Test extends W3CCssTest { @Override protected String getHtmlFileName() { return "background-color-077.xht"; } }
package interfaces; import java.util.Random; public class RandomDoubles { private static Random rand = new Random(47); public double next() { return rand.nextDouble(); } public static void main(String [] args) { for(int i = 0; i < 7; i++) System.out.println(rand.nextDouble()); } }
/* * Copyright 2016-2017 Axioma srl. * * 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.holonplatform.datastore.jdbc.test.data; import java.io.Serializable; import com.holonplatform.core.beans.DataPath; public class TestProjectionBean implements Serializable { private static final long serialVersionUID = 7323766007354763956L; private long keycode; @DataPath("strv") private String text; public long getKeycode() { return keycode; } public void setKeycode(long keycode) { this.keycode = keycode; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
package com.provectus.kafka.ui.util; public enum JmxMetricsValueName { Count, OneMinuteRate, FifteenMinuteRate, FiveMinuteRate, MeanRate }
package com.mglj.wms.base.audits.domain; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.Min; import java.io.Serializable; import java.util.Date; /** * 的Query * * @author zsp * @date 2017-10-26 */ public class AuditLogQuery implements Serializable{ private static final long serialVersionUID = -6214696820066579697L; private static final int DEFAULT_PAGE_SIZE = 20; /** * 页索引 */ @Min(message = "page-index-min-0", value = 0) private Integer pageIndex = 0; /** * 页大小 */ @Range(message = "page-size-1-to-1000", max=1000, min=1) private Integer pageSize = DEFAULT_PAGE_SIZE; /** * 排序字段 */ private String sortColumns; /** * 返回记录的起始位置。 */ private transient Long offset; /** * 返回记录的个数。 */ private transient Integer rows; private Long warehouseId; private Date createTimeStart; private Date createTimeEnd; private String group; private String resourceCode; private String actionCode; private String billCode; private String userName; /** * 构建offset和rows * @return */ public AuditLogQuery build() { this.offset = (long)this.pageIndex * this.pageSize; this.rows = this.pageSize; return this; } /** * 构建pageIndex * @param pageIndex * @return */ public AuditLogQuery withPageIndex(Integer pageIndex) { this.pageIndex = pageIndex; if(this.pageIndex == null) { this.pageIndex = 0; } return this; } /** * 构建pageSize * @param pageSize * @return */ public AuditLogQuery withPageSize(Integer pageSize) { this.pageSize = pageSize; if(this.pageSize == null) { this.pageSize = DEFAULT_PAGE_SIZE; } return this; } /** * 获取页索引 */ public int getPageIndex() { return pageIndex; } /** * 设置页索引 */ public void setPageIndex(Integer pageIndex) { this.pageIndex = pageIndex; } /** * 获取页大小 */ public int getPageSize() { return pageSize; } /** * 设置页大小 */ public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } /** * 获取排序字段 */ public String getSortColumns() { return sortColumns; } /** * 设置排序字段 */ public void setSortColumns(String sortColumns) { this.sortColumns = sortColumns; } /** * 获取offset * @return */ public Long getOffset() { return offset; } /** * 获取rows * @return */ public Integer getRows() { return rows; } /** * 设置仓库ID */ public void setWarehouseId(Long value) { this.warehouseId = value; } /** * 获取仓库ID */ public Long getWarehouseId() { return this.warehouseId; } public Date getCreateTimeStart() { return createTimeStart; } public void setCreateTimeStart(Date createTimeStart) { this.createTimeStart = createTimeStart; } public Date getCreateTimeEnd() { return createTimeEnd; } public void setCreateTimeEnd(Date createTimeEnd) { this.createTimeEnd = createTimeEnd; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getResourceCode() { return resourceCode; } public void setResourceCode(String resourceCode) { this.resourceCode = resourceCode; } public String getActionCode() { return actionCode; } public void setActionCode(String actionCode) { this.actionCode = actionCode; } public String getBillCode() { return billCode; } public void setBillCode(String billCode) { this.billCode = billCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
package org.ent.dev.unit.local; import org.ent.dev.unit.combine.ProcProc; import org.ent.dev.unit.data.Data; /** * Special case of Pipe, where the same data object (possibly modified) * is forwarded. */ public interface Proc extends Pipe { void accept(Data data); @Override default Data apply(Data data) { accept(data); return data; } default Proc combineProc(Proc proc) { return new ProcProc(this, proc); } }
/* * Copyright 2022 ThoughtWorks, 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.thoughtworks.go.util.command; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class InMemoryConsumer implements StreamConsumer { private Queue<String> lines = new ConcurrentLinkedQueue<>(); private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(InMemoryConsumer.class); @Override public void consumeLine(String line) { try { lines.add(line); } catch (RuntimeException e) { LOG.error("Problem consuming line [{}]", line, e); } } public List<String> asList() { return new ArrayList<>(lines); } public boolean contains(String message) { return toString().contains(message); } @Override public String toString() { return StringUtils.join(asList(), "\n"); } }
package proposta.entities.card.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import proposta.configs.exception.customExceptions.ApiErrorException; import proposta.entities.card.entities.Card; import proposta.entities.card.events.eventForTravelNotice.EventsForTravelNotice; import proposta.entities.card.repositories.CardRepository; import proposta.entities.card.request.TravelNoticeReq; import javax.validation.Valid; import java.util.Optional; @RestController @RequestMapping("/api/card") public class TravelNoticeController { @Autowired private CardRepository cardRepository; @Autowired private EventsForTravelNotice eventsForTravelNotice; @PostMapping("/{idCard}/travel") public ResponseEntity<?> travelNoticeCard(@PathVariable String idCard, @RequestBody @Valid TravelNoticeReq travelNoticeCardReq) { Card card = getPossibleCard(idCard); eventsForTravelNotice.sendNotificationTravelNotice(card, travelNoticeCardReq); return ResponseEntity.ok().build(); } private Card getPossibleCard(String idCard) { Optional<Card> possibleCard = cardRepository.findById(idCard); if (possibleCard.isEmpty()) { throw new ApiErrorException(HttpStatus.NOT_FOUND, "Cartão não encontrado"); } return possibleCard.get(); } }
/* * Copyright (c) 2019 Oracle and/or its affiliates. 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 io.helidon.service.employee; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import io.helidon.config.Config; import io.helidon.webserver.Routing; import io.helidon.webserver.ServerRequest; import io.helidon.webserver.ServerResponse; import io.helidon.webserver.Service; /** * The Employee service endpoints. Get all employees: curl -X GET * http://localhost:8080/employees Get employee by id: curl -X GET * http://localhost:8080/employees/{id} Add employee curl -X POST * http://localhost:8080/employees/{id} Update employee by id curl -X PUT * http://localhost:8080/employees/{id} Delete employee by id curl -X DELETE * http://localhost:8080/employees/{id} The message is returned as a JSON object */ public class EmployeeService implements Service { private final EmployeeRepository employees; private static final Logger LOGGER = Logger.getLogger(EmployeeService.class.getName()); EmployeeService(Config config) { employees = EmployeeRepository.create(config.get("app.drivertype").asString().orElse("Array"), config); } /** * A service registers itself by updating the routine rules. * @param rules the routing rules. */ @Override public void update(Routing.Rules rules) { rules.get("/", this::getAll).get("/lastname/{name}", this::getByLastName) .get("/department/{name}", this::getByDepartment).get("/title/{name}", this::getByTitle) .post("/", this::save).get("/{id}", this::getEmployeeById).put("/{id}", this::update) .delete("/{id}", this::delete); } /** * Gets all the employees. * @param request the server request * @param response the server response */ private void getAll(final ServerRequest request, final ServerResponse response) { LOGGER.fine("getAll"); List<Employee> allEmployees = this.employees.getAll(); response.send(allEmployees); } /** * Gets the employees by the last name specified in the parameter. * @param request the server request * @param response the server response */ private void getByLastName(final ServerRequest request, final ServerResponse response) { LOGGER.fine("getByLastName"); // Invalid query strings handled in isValidQueryStr. Keeping DRY if (isValidQueryStr(response, request.path().param("name"))) { response.status(200).send(this.employees.getByLastName(request.path().param("name"))); } } /** * Gets the employees by the title specified in the parameter. * @param request the server request * @param response the server response */ private void getByTitle(final ServerRequest request, final ServerResponse response) { LOGGER.fine("getByTitle"); if (isValidQueryStr(response, request.path().param("name"))) { response.status(200).send(this.employees.getByTitle(request.path().param("name"))); } } /** * Gets the employees by the department specified in the parameter. * @param request the server request * @param response the server response */ private void getByDepartment(final ServerRequest request, final ServerResponse response) { LOGGER.fine("getByDepartment"); if (isValidQueryStr(response, request.path().param("name"))) { response.status(200).send(this.employees.getByDepartment(request.path().param("name"))); } } /** * Gets the employees by the ID specified in the parameter. * @param request the server request * @param response the server response */ private void getEmployeeById(ServerRequest request, ServerResponse response) { LOGGER.fine("getEmployeeById"); // If invalid, response handled in isValidId. Keeping DRY if (isValidId(response, request.path().param("id"))) { Employee employee = this.employees.getById(request.path().param("id")); response.status(200).send(employee); } } /** * Saves a new employee. * @param request the server request * @param response the server response */ private void save(ServerRequest request, ServerResponse response) { LOGGER.fine("save"); request.content().as(Employee.class) .thenApply(e -> Employee.of(null, e.getFirstName(), e.getLastName(), e.getEmail(), e.getPhone(), e.getBirthDate(), e.getTitle(), e.getDepartment())) .thenApply(this.employees::save).thenCompose(p -> response.status(201).send()); } /** * Updates an existing employee. * @param request the server request * @param response the server response */ private void update(ServerRequest request, ServerResponse response) { LOGGER.fine("update"); if (isValidId(response, request.path().param("id"))) { request.content().as(Employee.class).thenApply(e -> { return this.employees.update(Employee.of(e.getId(), e.getFirstName(), e.getLastName(), e.getEmail(), e.getPhone(), e.getBirthDate(), e.getTitle(), e.getDepartment()), request.path().param("id")); }).thenCompose(p -> response.status(204).send()); } } /** * Deletes an existing employee. * @param request the server request * @param response the server response */ private void delete(final ServerRequest request, final ServerResponse response) { LOGGER.fine("delete"); if (isValidId(response, request.path().param("id"))) { this.employees.deleteById(request.path().param("id")); response.status(204).send(); } } /** * Validates the parameter. * @param response the server response * @param nameStr * @return */ private boolean isValidQueryStr(ServerResponse response, String nameStr) { Map<String, String> errorMessage = new HashMap<>(); if (nameStr == null || nameStr.isEmpty() || nameStr.length() > 100) { errorMessage.put("errorMessage", "Invalid query string"); response.status(400).send(errorMessage); return false; } else { return true; } } /** * Validates if the ID of the employee exists. * @param response the server response * @param idStr * @return */ private boolean isValidId(ServerResponse response, String idStr) { Map<String, String> errorMessage = new HashMap<>(); if (idStr == null || idStr.isEmpty()) { errorMessage.put("errorMessage", "Invalid query string"); response.status(400).send(errorMessage); return false; } else if (this.employees.isIdFound(idStr)) { return true; } else { errorMessage.put("errorMessage", "ID " + idStr + " not found"); response.status(404).send(errorMessage); return false; } } }
/* * Copyright (C) 2004-2015 Volker Bergmann (volker.bergmann@bergmann-it.de). * 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.rapiddweller.common; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Tests the {@link Escalation} class. * Created at 29.04.2008 18:51:28 * * @author Volker Bergmann * @since 0.2.04 */ public class EscalationTest { @Test public void testEquals() { Escalation e1 = new Escalation("mess", "orig", "cause"); Escalation e2 = new Escalation("other message", "orig", "cause"); Escalation e3 = new Escalation("mess", "other orig", "cause"); Escalation e4 = new Escalation("mess", "orig", "other cause"); Escalation e5 = new Escalation("mess", "orig", null); assertTrue(e1.equals(e1)); assertFalse(e1.equals(null)); assertFalse(e1.equals("bla")); assertFalse(e1.equals(e2)); assertFalse(e1.equals(e3)); assertTrue(e1.equals(e4)); assertTrue(e1.equals(e5)); assertTrue(e5.equals(e1)); } }
package CH08.designpatterns.factory.pizzafm; public class NYPizzaStore extends PizzaStore { Pizza createPizza(String item) { if (item.equals("cheese")) { return new NYStyleCheesePizza(); } else if (item.equals("veggie")) { return new NYStyleVeggiePizza(); } else if (item.equals("clam")) { return new NYStyleClamPizza(); } else if (item.equals("pepperoni")) { return new NYStylePepperoniPizza(); } else return null; } }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.validation.annotation; import java.lang.annotation.Annotation; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.lang.Nullable; /** * Utility class for handling validation annotations. * Mainly for internal use within the framework. * * @author Christoph Dreis * @since 5.3.7 */ public abstract class ValidationAnnotationUtils { private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; /** * Determine any validation hints by the given annotation. * <p>This implementation checks for {@code @javax.validation.Valid}, * Spring's {@link org.springframework.validation.annotation.Validated}, * and custom annotations whose name starts with "Valid". * * @param ann the annotation (potentially a validation annotation) * @return the validation hints to apply (possibly an empty array), * or {@code null} if this annotation does not trigger any validation */ @Nullable public static Object[] determineValidationHints(Annotation ann) { Class<? extends Annotation> annotationType = ann.annotationType(); String annotationName = annotationType.getName(); if ("javax.validation.Valid".equals(annotationName)) { return EMPTY_OBJECT_ARRAY; } Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class); if (validatedAnn != null) { Object hints = validatedAnn.value(); return convertValidationHints(hints); } if (annotationType.getSimpleName().startsWith("Valid")) { Object hints = AnnotationUtils.getValue(ann); return convertValidationHints(hints); } return null; } private static Object[] convertValidationHints(@Nullable Object hints) { if (hints == null) { return EMPTY_OBJECT_ARRAY; } return (hints instanceof Object[] ? (Object[]) hints : new Object[]{hints}); } }
/* * Copyright (c) 2004-2012, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 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. * * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * 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 OWNER 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 org.hisp.dhis.patient.action.patientattribute; import java.util.ArrayList; import java.util.Collection; import org.hisp.dhis.patient.PatientAttribute; import org.hisp.dhis.patient.PatientAttributeService; import com.opensymphony.xwork2.Action; /** * @author Chau Thu Tran * * @version GetPatientAttributesWithoutGroupAction.java Sep 27, 2010 4:55:01 PM */ public class GetPatientAttributesWithoutGroupAction implements Action { // ------------------------------------------------------------------------- // Dependency // ------------------------------------------------------------------------- private PatientAttributeService patientAttributeService; public void setPatientAttributeService( PatientAttributeService patientAttributeService ) { this.patientAttributeService = patientAttributeService; } // ------------------------------------------------------------------------- // Output // ------------------------------------------------------------------------- private Collection<PatientAttribute> patientAttributes = new ArrayList<PatientAttribute>(); public Collection<PatientAttribute> getPatientAttributes() { return patientAttributes; } // ------------------------------------------------------------------------- // Action implementation // ------------------------------------------------------------------------- public String execute() throws Exception { patientAttributes = patientAttributeService.getPatientAttributesNotGroup(); return SUCCESS; } }
/** * 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.hbase.client; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Base64; import java.util.List; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.exceptions.DeserializationException; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.KeyOnlyFilter; import org.apache.hadoop.hbase.security.access.Permission; import org.apache.hadoop.hbase.security.visibility.Authorizations; import org.apache.hadoop.hbase.testclassification.ClientTests; import org.apache.hadoop.hbase.testclassification.SmallTests; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Assert; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos; // TODO: cover more test cases @Category({ClientTests.class, SmallTests.class}) public class TestGet { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestGet.class); private static final byte [] ROW = new byte [] {'r'}; private static final String PB_GET = "CgNyb3ciEwoPdGVzdC5Nb2NrRmlsdGVyEgAwATgB"; private static final String PB_GET_WITH_FILTER_LIST = "CgFyIosBCilvcmcuYXBhY2hlLmhhZG9vcC5oYmFzZS5maWx0ZXIuRmlsdGVyTGlzdBJeCAESEwoP" + "dGVzdC5Nb2NrRmlsdGVyEgASEQoNbXkuTW9ja0ZpbHRlchIAEjIKLG9yZy5hcGFjaGUuaGFkb29w" + "LmhiYXNlLmZpbHRlci5LZXlPbmx5RmlsdGVyEgIIADABOAE="; private static final String MOCK_FILTER_JAR = "UEsDBBQACAgIANWDlEMAAAAAAAAAAAAAAAAJAAQATUVUQS1JTkYv/soAAAMAUEsHCAAAAAACAAAA" + "AAAAAFBLAwQUAAgICADVg5RDAAAAAAAAAAAAAAAAFAAAAE1FVEEtSU5GL01BTklGRVNULk1G803M" + "y0xLLS7RDUstKs7Mz7NSMNQz4OVyLkpNLElN0XWqBAmY6xnEG1gqaPgXJSbnpCo45xcV5BcllgCV" + "a/Jy8XIBAFBLBwgxyqRbQwAAAEQAAABQSwMEFAAICAgAUoOUQwAAAAAAAAAAAAAAABMAAABteS9N" + "b2NrRmlsdGVyLmNsYXNzdZHPTsJAEMa/LYVCRVFQMd68gQc38YrxUJUTetGQGE7bstrVwjbbYsSn" + "0hOJJj6AD2WcFoP/4iYzX+bb32xmd9/en18B7GPLhY11BxsurEw3GUoHaqzSQ4ZCq91nsI/0UDLU" + "emoszyYjX5oL4Ufk1Hs6EFFfGJXVn6adhirJ6NGUn+rgtquiVJoOQyUWJpFdo0cMjdbAa/8hnNj3" + "pqmkbmvgMbgn94GMU6XHiYMm1ed6YgJJeDbNV+fejbgTVRRRYlj+cSZDW5trLmIRhJKHYqh1zENf" + "JJJf5QCfcx45DJ3/WLmYgx/LRNJ1I/UgMmMxIXbo9WxkywLLZqHsUMVJGWlxdwb2lG+XKZdys4kK" + "5eocgIsl0grVy0Q5+e9Y+V75BdblDIXHX/3b3/rLWEGNdJXCJmeNop7zjQ9QSwcI1kzyMToBAADs" + "AQAAUEsDBBQACAgIAFKDlEMAAAAAAAAAAAAAAAAVAAAAdGVzdC9Nb2NrRmlsdGVyLmNsYXNzdVHB" + "TsJAFJwthUJFERQx3ryBBzfxivFQlRN60ZAYTtuy2tXCNtti1K/SE4kmfoAfZXwtBg3RTd6bzOy8" + "zezux+frO4ADbLuwsemg6cLKcIuhdKgmKj1iKLQ7Awb7WI8kQ62vJvJ8OvaluRR+REqjrwMRDYRR" + "Gf8W7TRUCUO9n8ok5Wc6uOupKJWmy1CJhUlkz+gxQ7M99Dp/eJzY9x5JZrCGHoN7+hDIOFV6kjho" + "Eb/QUxNIsmeJfib3b8W9qKKIEslLpzJ0tLnhIhZBKHkoRlrHPPRFIvl1buBzn0cKQ/c/r1wk4Scy" + "kXTpSD2JTFhkxC69oY1sWWBZGuoOMU7ICIt7M7CXfLtMvZSLLVSoV+cGuFghrBBfJZeT/5GV75Xf" + "YF3NUHhemt/5NV/GGmqE61Q2KXWqRu7f+AJQSwcIrS5nKDoBAADyAQAAUEsBAhQAFAAICAgA1YOU" + "QwAAAAACAAAAAAAAAAkABAAAAAAAAAAAAAAAAAAAAE1FVEEtSU5GL/7KAABQSwECFAAUAAgICADV" + "g5RDMcqkW0MAAABEAAAAFAAAAAAAAAAAAAAAAAA9AAAATUVUQS1JTkYvTUFOSUZFU1QuTUZQSwEC" + "FAAUAAgICABSg5RD1kzyMToBAADsAQAAEwAAAAAAAAAAAAAAAADCAAAAbXkvTW9ja0ZpbHRlci5j" + "bGFzc1BLAQIUABQACAgIAFKDlEOtLmcoOgEAAPIBAAAVAAAAAAAAAAAAAAAAAD0CAAB0ZXN0L01v" + "Y2tGaWx0ZXIuY2xhc3NQSwUGAAAAAAQABAABAQAAugMAAAAA"; @Test public void testAttributesSerialization() throws IOException { Get get = new Get(Bytes.toBytes("row")); get.setAttribute("attribute1", Bytes.toBytes("value1")); get.setAttribute("attribute2", Bytes.toBytes("value2")); get.setAttribute("attribute3", Bytes.toBytes("value3")); ClientProtos.Get getProto = ProtobufUtil.toGet(get); Get get2 = ProtobufUtil.toGet(getProto); Assert.assertNull(get2.getAttribute("absent")); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value1"), get2.getAttribute("attribute1"))); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value2"), get2.getAttribute("attribute2"))); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value3"), get2.getAttribute("attribute3"))); Assert.assertEquals(3, get2.getAttributesMap().size()); } @Test public void testGetAttributes() { Get get = new Get(ROW); Assert.assertTrue(get.getAttributesMap().isEmpty()); Assert.assertNull(get.getAttribute("absent")); get.setAttribute("absent", null); Assert.assertTrue(get.getAttributesMap().isEmpty()); Assert.assertNull(get.getAttribute("absent")); // adding attribute get.setAttribute("attribute1", Bytes.toBytes("value1")); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value1"), get.getAttribute("attribute1"))); Assert.assertEquals(1, get.getAttributesMap().size()); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value1"), get.getAttributesMap().get("attribute1"))); // overriding attribute value get.setAttribute("attribute1", Bytes.toBytes("value12")); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value12"), get.getAttribute("attribute1"))); Assert.assertEquals(1, get.getAttributesMap().size()); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value12"), get.getAttributesMap().get("attribute1"))); // adding another attribute get.setAttribute("attribute2", Bytes.toBytes("value2")); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value2"), get.getAttribute("attribute2"))); Assert.assertEquals(2, get.getAttributesMap().size()); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value2"), get.getAttributesMap().get("attribute2"))); // removing attribute get.setAttribute("attribute2", null); Assert.assertNull(get.getAttribute("attribute2")); Assert.assertEquals(1, get.getAttributesMap().size()); Assert.assertNull(get.getAttributesMap().get("attribute2")); // removing non-existed attribute get.setAttribute("attribute2", null); Assert.assertNull(get.getAttribute("attribute2")); Assert.assertEquals(1, get.getAttributesMap().size()); Assert.assertNull(get.getAttributesMap().get("attribute2")); // removing another attribute get.setAttribute("attribute1", null); Assert.assertNull(get.getAttribute("attribute1")); Assert.assertTrue(get.getAttributesMap().isEmpty()); Assert.assertNull(get.getAttributesMap().get("attribute1")); } @Test public void testNullQualifier() { Get get = new Get(ROW); byte[] family = Bytes.toBytes("family"); get.addColumn(family, null); Set<byte[]> qualifiers = get.getFamilyMap().get(family); Assert.assertEquals(1, qualifiers.size()); } @Test public void TestGetRowFromGetCopyConstructor() throws Exception { Get get = new Get(ROW); get.setFilter(null); get.setAuthorizations(new Authorizations("foo")); get.setACL("u", new Permission(Permission.Action.READ)); get.setConsistency(Consistency.TIMELINE); get.setReplicaId(2); get.setIsolationLevel(IsolationLevel.READ_UNCOMMITTED); get.setCheckExistenceOnly(true); get.setTimeRange(3, 4); get.readVersions(11); get.setMaxResultsPerColumnFamily(10); get.setRowOffsetPerColumnFamily(11); get.setCacheBlocks(true); Get copyGet = new Get(get); assertEquals(0, Bytes.compareTo(get.getRow(), copyGet.getRow())); // from OperationWithAttributes assertEquals(get.getId(), copyGet.getId()); // from Query class assertEquals(get.getFilter(), copyGet.getFilter()); assertTrue(get.getAuthorizations().toString().equals(copyGet.getAuthorizations().toString())); assertTrue(Bytes.equals(get.getACL(), copyGet.getACL())); assertEquals(get.getConsistency(), copyGet.getConsistency()); assertEquals(get.getReplicaId(), copyGet.getReplicaId()); assertEquals(get.getIsolationLevel(), copyGet.getIsolationLevel()); // from Get class assertEquals(get.isCheckExistenceOnly(), copyGet.isCheckExistenceOnly()); assertTrue(get.getTimeRange().equals(copyGet.getTimeRange())); assertEquals(get.getMaxVersions(), copyGet.getMaxVersions()); assertEquals(get.getMaxResultsPerColumnFamily(), copyGet.getMaxResultsPerColumnFamily()); assertEquals(get.getRowOffsetPerColumnFamily(), copyGet.getRowOffsetPerColumnFamily()); assertEquals(get.getCacheBlocks(), copyGet.getCacheBlocks()); assertEquals(get.getId(), copyGet.getId()); } @Test public void testDynamicFilter() throws Exception { Configuration conf = HBaseConfiguration.create(); String localPath = conf.get("hbase.local.dir") + File.separator + "jars" + File.separator; File jarFile = new File(localPath, "MockFilter.jar"); jarFile.delete(); assertFalse("Should be deleted: " + jarFile.getPath(), jarFile.exists()); ClientProtos.Get getProto1 = ClientProtos.Get.parseFrom(Base64.getDecoder().decode(PB_GET)); ClientProtos.Get getProto2 = ClientProtos.Get.parseFrom(Base64.getDecoder().decode(PB_GET_WITH_FILTER_LIST)); try { ProtobufUtil.toGet(getProto1); fail("Should not be able to load the filter class"); } catch (IOException ioe) { assertTrue(ioe.getCause() instanceof ClassNotFoundException); } try { ProtobufUtil.toGet(getProto2); fail("Should not be able to load the filter class"); } catch (IOException ioe) { assertTrue(ioe.getCause() instanceof InvocationTargetException); InvocationTargetException ite = (InvocationTargetException)ioe.getCause(); assertTrue(ite.getTargetException() instanceof DeserializationException); } FileOutputStream fos = new FileOutputStream(jarFile); fos.write(Base64.getDecoder().decode(MOCK_FILTER_JAR)); fos.close(); Get get1 = ProtobufUtil.toGet(getProto1); assertEquals("test.MockFilter", get1.getFilter().getClass().getName()); Get get2 = ProtobufUtil.toGet(getProto2); assertTrue(get2.getFilter() instanceof FilterList); List<Filter> filters = ((FilterList)get2.getFilter()).getFilters(); assertEquals(3, filters.size()); assertEquals("test.MockFilter", filters.get(0).getClass().getName()); assertEquals("my.MockFilter", filters.get(1).getClass().getName()); assertTrue(filters.get(2) instanceof KeyOnlyFilter); } @Test public void testGetRowConstructor() { byte[] row1 = Bytes.toBytes("testRow"); byte[] row2 = Bytes.toBytes("testtestRow"); ByteBuffer rowBuffer = ByteBuffer.allocate(16); rowBuffer = ByteBuffer.wrap(row1); Get get1 = new Get(rowBuffer); Get get2 = new Get(row2, 4, 7); Assert.assertArrayEquals(get1.getRow(), get2.getRow()); } }
/* * * 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.o19s.es.explore; import java.util.ArrayList; public class StatisticsHelper { private final ArrayList<Float> data = new ArrayList<>(10); private float min = Float.MAX_VALUE; private float max = 0.0f; public enum AggrType { AVG("avg"), MAX("max"), MIN("min"), SUM("sum"), STDDEV("stddev"), MATCHES("matches"); private String type; AggrType(String type){ this.type = type; } public String getType() { return type; } } public StatisticsHelper() { } public void add(float val) { data.add(val); if(val < this.min) { this.min = val; } if(val > this.max) { this.max = val; } } public ArrayList<Float> getData() { return data; } public int getSize(){ return data.size(); } public float getMax() { assert !data.isEmpty(); return max; } public float getMin() { assert !data.isEmpty(); return min; } public float getMean() { assert !data.isEmpty(); return getSum() / data.size(); } public float getSum() { assert !data.isEmpty(); float sum = 0.0f; for(float a : data) { sum += a; } return sum; } public float getVariance() { assert !data.isEmpty(); float mean = getMean(); float temp = 0.0f; for(float a : data) temp += (a-mean)*(a-mean); return temp/data.size(); } public float getStdDev() { assert !data.isEmpty(); return (float) Math.sqrt(getVariance()); } public float getAggr(AggrType type) { switch(type) { case AVG: return getMean(); case MAX: return getMax(); case MIN: return getMin(); case SUM: return getSum(); case STDDEV: return getStdDev(); default: return 0.0f; } } }
package org.cucina.search.query.criterion; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Transformer; import org.springframework.util.Assert; import java.util.*; /** * SearchCriterion implementation for foreign key values, restricts by using * the id of the foreign key. * * @author $Author: $ * @version $Revision: $ */ public class ForeignKeySearchCriterion extends AbstractSearchCriterion { private Collection<Long> value; private LongTransformer transformer = new LongTransformer(); /** * Creates a new TextSearchCriterion object. * * @param property The property name to restrict * @param name Optional name to store this criterion under * @param tableAlias JAVADOC. * @param text JAVADOC. */ @SuppressWarnings("unchecked") public ForeignKeySearchCriterion(String property, String name, String rootAlias, Object value) { super(property, name, rootAlias); Assert.notNull(value, "value must be provided as a parameter"); if (value instanceof Collection) { this.value = CollectionUtils.collect((Collection<?>) value, transformer, new HashSet<Long>()); } else { this.value = Collections.singleton(transformer.transform(value)); } } /** * Constructor is used by JSON for constructing new projections. */ @SuppressWarnings("unused") private ForeignKeySearchCriterion() { super(); } /** * JAVADOC Method Level Comments * * @return JAVADOC. */ @Override public String getRestriction() { StringBuilder restriction = new StringBuilder(); for (int i = 0; i < value.size(); i++) { if (i > 0) { restriction.append(","); } restriction.append("?"); } if (restriction.length() == 1) { restriction.insert(0, ".id" + getEqualsOperator()); } else { restriction.insert(0, ".id" + getInOperator() + "("); restriction.append(")"); } return getSearchPropertyName() + restriction.toString(); } /** * JAVADOC Method Level Comments * * @return JAVADOC. */ public Collection<Long> getValue() { return value; } /** * Return text value * * @return text. */ @Override public List<Object> getValues() { return new ArrayList<Object>(value); } private static class LongTransformer implements Transformer { @Override public Long transform(Object value) { if (null == value) { return null; } if (value instanceof String) { return Long.valueOf((String) value); } else if (value instanceof Number) { return ((Number) value).longValue(); } else { throw new IllegalArgumentException("Invalid value of type " + value.getClass().getName() + ", only String, Long, Collection are supported"); } } } }
package com.cycling74.net; import com.cycling74.max.*; import java.net.*; import java.io.IOException; import java.util.*; /** * Connect to and receive from multicast groups. * An internal Callback is maintained from a specified * method name and object. The specified method must * take an array of Atoms as its only argument. When * data is received, it is translated to an array of * Atoms and passed to the specified method. When a * MultiReceiver is no longer needed its close() method * should be called. * * created on 18-May-2004 * @author Ben Nevile */ public class MultiReceiver implements Runnable { private static Class ATOM_ARRAY_CLASS = (new Atom[] {}).getClass(); private String debugString = "MultiReceiver"; private int port; private boolean active = false; private MulticastSocket mRecvSocket; private Thread mListener = null; private boolean keepRunning; private Callback callback = null; private Vector addresses = new Vector(); /** * inner class to handle joining groups */ private class MultiJoiner extends Thread { String name; MultiJoiner(String name) { this.name = name; } public void run() { try { InetAddress addr = InetAddress.getByName(name); mRecvSocket.joinGroup(addr); } catch (UnknownHostException uhe) { MaxSystem.error(debugString+": unknown host " + name + ". "+uhe); } catch (SocketException se) { MaxSystem.error(debugString+": socket error. "+se); MaxSystem.post("Have you already joined that group?"); } catch (IOException ie) { MaxSystem.error(debugString+": io error. "+ie); } } } /** * inner class to handle leaving groups */ private class MultiLeaver extends Thread { String name; MultiLeaver(String name) { this.name = name; } public void run() { try { InetAddress addr = InetAddress.getByName(name); mRecvSocket.leaveGroup(addr); } catch (UnknownHostException uhe) { MaxSystem.error(debugString+": unknown host " + name + ". "+uhe); } catch (SocketException se) { MaxSystem.error(debugString+": socket error. "+se); MaxSystem.post("Are you sure you were a member of that group?"); } catch (IOException ie) { MaxSystem.error(debugString+": io error. "+ie); } } } /** * Creates a new MultiReceiver. * To make anything happen the user will have to * connect to a port, group, and set a Callback. */ public MultiReceiver() { } /** * Creates a new MultiReceiver connected to a specified group and port, * and creates an internal callback to a given method. * @param groupName the group to join * @param port port to communicate over * @param toCallIn object that contains the method to call * @param methodName method to call */ public MultiReceiver(String groupName, int port, Object toCallIn, String methodName) { setCallback(toCallIn, methodName); addAddress(groupName); setPort(port); } /** * Creates a new MultiReceiver connected to a specified group and port. * A callback must be set with setCallback before this new MultiReceiver * will do anything. * @param groupName the group to join * @param port port to communicate over */ public MultiReceiver(String groupName, int port) { addAddress(groupName); setPort(port); } /** * Creates a new MultiReceiver connected to a specified port. * A callback must be set with setCallback and a group joined * with join before this new MultiReceiver will do anything. * @param port port to communicate over */ public MultiReceiver(int port) { setPort(port); } /** * Sets the port to listen to. * This requires closing the old * socket and creating a new one. * This method operates asynchronously. * @param port the new port */ public void setPort(int port) { this.port = port; resetListener(); } /** * @return the current port */ public int getPort() { return port; } /** * Creates and maintains a Callback for the MultiReceiver. * This Callback is what is called when data is received. * The method must take an array of Atoms as its only argument. * @param toCallIn object that contains the method * @param methodName method to call */ public void setCallback(Object toCallIn, String methodName) { callback = new Callback( toCallIn, methodName, new Object[] {new Atom[] {} } ); } private void addAddress(String name) { synchronized(addresses) { addresses.add(name); } } /** * Turn the MultiReceiver on or off. * @param b true to turn it on */ public void setActive(boolean b) { if (b) (new Thread() { public void run() { setListener(true); } }).start(); else (new Thread() { public void run() { setListener(false); } }).start(); } private void setListener(boolean b) { if (b) { if (mListener == null) { keepRunning = true; if (initRecvSocket()) { joinAllGroups(); mListener = new Thread(this); mListener.start(); active = true; } } } else { if (mListener != null) { keepRunning = false; } if (mRecvSocket != null) { mRecvSocket.close(); } mListener = null; active = false; } } private void resetListener() { (new Thread() { public void run() { setListener(false); setListener(true); } }).start(); } /** * @return an array of Strings representing the groups joined, one for each group */ public String[] getGroups() { return (String[])addresses.toArray(Atom.emptyArray); } private void joinAllGroups() { synchronized(addresses) { Iterator i = addresses.iterator(); while (i.hasNext()) { MultiJoiner jl = new MultiJoiner((String)i.next()); jl.start(); } } } /** * Join a multicast group. * @param name the name of the group to join. eg 224.74.74.74 (the maxhole group) */ public void join(String name) { addAddress(name); if (active) { MultiJoiner jl = new MultiJoiner(name); jl.start(); } } private boolean initRecvSocket() { try { mRecvSocket = new MulticastSocket(port); } catch (IOException ioe) { MaxSystem.error(debugString+": io error. "+ioe); } return true; } public void run() { byte[] buf = new byte[1024]; DatagramPacket packet = new DatagramPacket(buf, buf.length); while (keepRunning) { try { mRecvSocket.receive(packet); if (keepRunning) { if (callback != null) { String s = new String(packet.getData(), 0, packet.getLength(), "UTF-8"); callback.setArgs(new Object[] {Atom.parse(s)}); callback.execute(); } } } catch (IOException ie) { // the socket closed. this is OK. } } } /** * Close down the MultiReceiver. Should be called in your notifyDeleted method. */ public void close() { //I'm not really sure why I decided to start a new thread here. //at some point I have to go through this stuff and make sure //I'm not doing something stupid. (new Thread() { public void run() { leaveAllGroups(); } }).start(); } /** * Leave all groups. */ public void leaveAllGroups() { synchronized(addresses) { Iterator i = addresses.iterator(); while (i.hasNext()) { MultiLeaver jl = new MultiLeaver((String)i.next()); jl.start(); } addresses.clear(); } } /** * Leave one group. * @param name the group to leave */ public void leave(String name) { boolean found = false; synchronized(addresses) { int count = 0; Iterator i = addresses.iterator(); while ((i.hasNext())&&(!found)) if (((String)i.next()).equals(name)) found = true; else count++; if (found) addresses.remove(count); } if (found) { MultiLeaver jl = new MultiLeaver(name); jl.start(); } } /** * Sets the debug string * to be used for purposes of error reporting. * * @param name the debug string to use when error reporting */ public void setDebugString(String name) { this.debugString = name; } }
package com.javatest.general; import org.springframework.stereotype.Component; //@Component public class AC { }
package fi.nls.oskari.control.statistics.plugins.sotka; import org.json.JSONObject; public class SotkaConfig { private long datasourceId; private String url; // default to year as it's the time variable on sotkanet private String timeVariableId = "year"; public SotkaConfig(JSONObject json, long id) { datasourceId = id; url = json.optString("url"); // allow override with db config timeVariableId = json.optString("timeVariable", timeVariableId); } public long getId() { return datasourceId; } public String getUrl() { if(url == null) { // default return "http://www.sotkanet.fi/rest"; } return url; } public void setUrl(String url) { this.url = url; } public String getTimeVariableId() { return timeVariableId; } }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications Copyright (C) 2021 Cafe Bazaar */ package ir.cafebazaar.apksig.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.Closeable; import java.io.IOException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.junit.Test; /** * Base class for testing implementations of {@link DataSource}. This class tests the contract of * {@code DataSource}. * * <p>To subclass, provide an implementation of {@link #createDataSource(byte[])} which returns * the implementation of {@code DataSource} you want to test. */ public abstract class DataSourceTestBase { /** * Returns a new {@link DataSource} containing the provided contents. */ protected abstract CloseableWithDataSource createDataSource(byte[] contents) throws IOException; protected CloseableWithDataSource createDataSource(String contents) throws IOException { return createDataSource(contents.getBytes(StandardCharsets.UTF_8)); } @Test public void testSize() throws Exception { try (CloseableWithDataSource c = createDataSource("Hello12345")) { DataSource ds = c.getDataSource(); assertEquals(10, ds.size()); } } @Test public void testSlice() throws Exception { try (CloseableWithDataSource c = createDataSource("Hello12345")) { DataSource ds = c.getDataSource(); assertSliceEquals("123", ds, 5, 3); DataSource slice = ds.slice(3, 5); assertGetByteBufferEquals("lo123", slice, 0, 5); // Zero-length slices assertSliceEquals("", ds, 0, 0); assertSliceEquals("", ds, 1, 0); assertSliceEquals("", ds, ds.size() - 2, 0); assertSliceEquals("", ds, ds.size() - 1, 0); assertSliceEquals("", ds, ds.size(), 0); assertSliceEquals("", slice, 0, 0); assertSliceEquals("", slice, 1, 0); assertSliceEquals("", slice, slice.size() - 2, 0); assertSliceEquals("", slice, slice.size() - 1, 0); assertSliceEquals("", slice, slice.size(), 0); // Invalid slices assertSliceThrowsIOOB(ds, -1, 0); assertSliceThrowsIOOB(slice, -1, 0); assertSliceThrowsIOOB(ds, -1, 2); assertSliceThrowsIOOB(slice, -1, 2); assertSliceThrowsIOOB(ds, -1, 20); assertSliceThrowsIOOB(slice, -1, 20); assertSliceThrowsIOOB(ds, 1, 20); assertSliceThrowsIOOB(slice, 1, 20); assertSliceThrowsIOOB(ds, ds.size() + 1, 0); assertSliceThrowsIOOB(slice, slice.size() + 1, 0); assertSliceThrowsIOOB(ds, ds.size(), 1); assertSliceThrowsIOOB(slice, slice.size(), 1); assertSliceThrowsIOOB(ds, ds.size() - 1, -1); assertSliceThrowsIOOB(ds, slice.size() - 1, -1); } } @Test public void testGetByteBuffer() throws Exception { try (CloseableWithDataSource c = createDataSource("test1234")) { DataSource ds = c.getDataSource(); assertGetByteBufferEquals("s", ds, 2, 1); DataSource slice = ds.slice(3, 4); // "t123" assertGetByteBufferEquals("2", slice, 2, 1); // Zero-length chunks assertEquals(0, ds.getByteBuffer(0, 0).capacity()); assertEquals(0, ds.getByteBuffer(ds.size(), 0).capacity()); assertEquals(0, ds.getByteBuffer(ds.size() - 1, 0).capacity()); assertEquals(0, ds.getByteBuffer(ds.size() - 2, 0).capacity()); assertEquals(0, slice.getByteBuffer(0, 0).capacity()); assertEquals(0, slice.getByteBuffer(slice.size(), 0).capacity()); assertEquals(0, slice.getByteBuffer(slice.size() - 1, 0).capacity()); assertEquals(0, slice.getByteBuffer(slice.size() - 2, 0).capacity()); // Invalid chunks assertGetByteBufferThrowsIOOB(ds, -1, 0); assertGetByteBufferThrowsIOOB(slice, -1, 0); assertGetByteBufferThrowsIOOB(ds, -1, 2); assertGetByteBufferThrowsIOOB(slice, -1, 2); assertGetByteBufferThrowsIOOB(ds, -1, 20); assertGetByteBufferThrowsIOOB(slice, -1, 20); assertGetByteBufferThrowsIOOB(ds, 1, 20); assertGetByteBufferThrowsIOOB(slice, 1, 20); assertGetByteBufferThrowsIOOB(ds, ds.size() + 1, 0); assertGetByteBufferThrowsIOOB(slice, slice.size() + 1, 0); assertGetByteBufferThrowsIOOB(ds, ds.size(), 1); assertGetByteBufferThrowsIOOB(slice, slice.size(), 1); assertGetByteBufferThrowsIOOB(ds, ds.size() - 1, -1); assertGetByteBufferThrowsIOOB(ds, slice.size() - 1, -1); } } @Test public void testFeed() throws Exception { try (CloseableWithDataSource c = createDataSource("test1234")) { DataSource ds = c.getDataSource(); assertFeedEquals("23", ds, 5, 2); DataSource slice = ds.slice(1, 5); // "est12" assertFeedEquals("t", slice, 2, 1); // Zero-length chunks assertFeedEquals("", ds, 0, 0); assertFeedEquals("", ds, 1, 0); assertFeedEquals("", ds, ds.size() - 2, 0); assertFeedEquals("", ds, ds.size() - 1, 0); assertFeedEquals("", ds, ds.size(), 0); assertFeedEquals("", slice, 0, 0); assertFeedEquals("", slice, 2, 0); assertFeedEquals("", slice, slice.size() - 2, 0); assertFeedEquals("", slice, slice.size() - 1, 0); assertFeedEquals("", slice, slice.size(), 0); // Invalid chunks assertFeedThrowsIOOB(ds, -1, 0); assertFeedThrowsIOOB(slice, -1, 0); assertFeedThrowsIOOB(ds, -1, 2); assertFeedThrowsIOOB(slice, -1, 2); assertFeedThrowsIOOB(ds, -1, 10); assertFeedThrowsIOOB(slice, -1, 10); assertFeedThrowsIOOB(ds, 1, 10); assertFeedThrowsIOOB(slice, 1, 10); assertFeedThrowsIOOB(ds, ds.size() + 1, 0); assertFeedThrowsIOOB(slice, slice.size() + 1, 0); assertFeedThrowsIOOB(ds, ds.size(), 1); assertFeedThrowsIOOB(slice, slice.size(), 1); assertFeedThrowsIOOB(ds, ds.size() - 1, -1); assertFeedThrowsIOOB(ds, slice.size() - 1, -1); } } @Test public void testCopyTo() throws Exception { try (CloseableWithDataSource c = createDataSource("abcdefghijklmnop")) { DataSource ds = c.getDataSource(); assertCopyToEquals("fgh", ds, 5, 3); DataSource slice = ds.slice(2, 7); // "cdefghi" assertCopyToEquals("efgh", slice, 2, 4); // Zero-length chunks assertCopyToEquals("", ds, 0, 0); assertCopyToEquals("", ds, 1, 0); assertCopyToEquals("", ds, ds.size() - 2, 0); assertCopyToEquals("", ds, ds.size() - 1, 0); assertCopyToEquals("", ds, ds.size(), 0); assertCopyToEquals("", slice, 0, 0); assertCopyToEquals("", slice, 2, 0); assertCopyToEquals("", slice, slice.size() - 2, 0); assertCopyToEquals("", slice, slice.size() - 1, 0); assertCopyToEquals("", slice, slice.size(), 0); // Invalid chunks assertCopyToThrowsIOOB(ds, -1, 0); assertCopyToThrowsIOOB(slice, -1, 0); assertCopyToThrowsIOOB(ds, -1, 2); assertCopyToThrowsIOOB(slice, -1, 2); assertCopyToThrowsIOOB(ds, -1, 20); assertCopyToThrowsIOOB(slice, -1, 20); assertCopyToThrowsIOOB(ds, 1, 20); assertCopyToThrowsIOOB(slice, 1, 20); assertCopyToThrowsIOOB(ds, ds.size() + 1, 0); assertCopyToThrowsIOOB(slice, slice.size() + 1, 0); assertCopyToThrowsIOOB(ds, ds.size(), 1); assertCopyToThrowsIOOB(slice, slice.size(), 1); assertCopyToThrowsIOOB(ds, ds.size() - 1, -1); assertCopyToThrowsIOOB(ds, slice.size() - 1, -1); // Destination buffer too small ByteBuffer buf = ByteBuffer.allocate(5); buf.position(2); buf.limit(3); assertCopyToThrowsBufferOverflow(ds, 0, 2, buf); buf.position(2); buf.limit(3); assertCopyToThrowsBufferOverflow(slice, 1, 2, buf); // Destination buffer larger than chunk copied using copyTo buf = ByteBuffer.allocate(10); buf.position(2); assertCopyToEquals("bcd", ds, 1, 3, buf); buf = ByteBuffer.allocate(10); buf.position(2); assertCopyToEquals("fg", slice, 3, 2, buf); } } protected static void assertSliceEquals( String expectedContents, DataSource ds, long offset, int size) throws IOException { DataSource slice = ds.slice(offset, size); assertEquals(size, slice.size()); assertGetByteBufferEquals(expectedContents, slice, 0, size); } protected static void assertSliceThrowsIOOB(DataSource ds, long offset, int size) { try { ds.slice(offset, size); fail(); } catch (IndexOutOfBoundsException expected) {} } protected static void assertGetByteBufferEquals( String expectedContents, DataSource ds, long offset, int size) throws IOException { ByteBuffer buf = ds.getByteBuffer(offset, size); assertEquals(0, buf.position()); assertEquals(size, buf.limit()); assertEquals(size, buf.capacity()); assertEquals(expectedContents, toString(buf)); } protected static void assertGetByteBufferThrowsIOOB(DataSource ds, long offset, int size) throws IOException { try { ds.getByteBuffer(offset, size); fail(); } catch (IndexOutOfBoundsException expected) {} } protected static void assertFeedEquals( String expectedFedContents, DataSource ds, long offset, int size) throws IOException { ReadableDataSink out = DataSinks.newInMemoryDataSink(size); ds.feed(offset, size, out); assertEquals(size, out.size()); assertEquals(expectedFedContents, toString(out.getByteBuffer(0, size))); } protected static void assertFeedThrowsIOOB(DataSource ds, long offset, long size) throws IOException { try { ds.feed(offset, size, NullDataSink.INSTANCE); fail(); } catch (IndexOutOfBoundsException expected) {} } protected static void assertCopyToEquals( String expectedContents, DataSource ds, long offset, int size) throws IOException { // Create a ByteBuffer backed by a section of a byte array. The ByteBuffer is on purpose not // starting at offset 0 to catch issues to do with not checking ByteBuffer.arrayOffset(). byte[] arr = new byte[size + 10]; ByteBuffer buf = ByteBuffer.wrap(arr, 1, size + 5); // Use non-zero position to catch issues with not checking buf.position() buf.position(2); // Buffer contains sufficient space for the requested copyTo operation assertEquals(size + 4, buf.remaining()); assertCopyToEquals(expectedContents, ds, offset, size, buf); } private static void assertCopyToEquals( String expectedContents, DataSource ds, long offset, int size, ByteBuffer buf) throws IOException { int oldPosition = buf.position(); int oldLimit = buf.limit(); ds.copyTo(offset, size, buf); // Position should've advanced by size whereas limit should've remained unchanged assertEquals(oldPosition + size, buf.position()); assertEquals(oldLimit, buf.limit()); buf.limit(buf.position()); buf.position(oldPosition); assertEquals(expectedContents, toString(buf)); } protected static void assertCopyToThrowsIOOB(DataSource ds, long offset, int size) throws IOException { ByteBuffer buf = ByteBuffer.allocate((size < 0) ? 0 : size); try { ds.copyTo(offset, size, buf); fail(); } catch (IndexOutOfBoundsException expected) {} } private static void assertCopyToThrowsBufferOverflow( DataSource ds, long offset, int size, ByteBuffer buf) throws IOException { try { ds.copyTo(offset, size, buf); fail(); } catch (BufferOverflowException expected) {} } /** * Returns the contents of the provided buffer as a string. The buffer's position and limit * remain unchanged. */ static String toString(ByteBuffer buf) { byte[] arr; int offset; int size = buf.remaining(); if (buf.hasArray()) { arr = buf.array(); offset = buf.arrayOffset() + buf.position(); } else { arr = new byte[buf.remaining()]; offset = 0; int oldPos = buf.position(); buf.get(arr); buf.position(oldPos); } return new String(arr, offset, size, StandardCharsets.UTF_8); } public static class CloseableWithDataSource implements Closeable { private final DataSource mDataSource; private final Closeable mCloseable; private CloseableWithDataSource(DataSource dataSource, Closeable closeable) { mDataSource = dataSource; mCloseable = closeable; } public static CloseableWithDataSource of(DataSource dataSource) { return new CloseableWithDataSource(dataSource, null); } public static CloseableWithDataSource of(DataSource dataSource, Closeable closeable) { return new CloseableWithDataSource(dataSource, closeable); } public DataSource getDataSource() { return mDataSource; } public Closeable getCloseable() { return mCloseable; } @Override public void close() throws IOException { if (mCloseable != null) { mCloseable.close(); } } } private static final class NullDataSink implements DataSink { private static final NullDataSink INSTANCE = new NullDataSink(); @Override public void consume(byte[] buf, int offset, int length) {} @Override public void consume(ByteBuffer buf) {} } }
/** * Copyright 2019 The JoyQueue Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joyqueue.handler.routing.command.application; import com.jd.laf.binding.annotation.Value; import com.jd.laf.web.vertx.annotation.Body; import com.jd.laf.web.vertx.annotation.Path; import com.jd.laf.web.vertx.annotation.QueryParam; import com.jd.laf.web.vertx.response.Response; import com.jd.laf.web.vertx.response.Responses; import org.joyqueue.handler.annotation.PageQuery; import org.joyqueue.handler.error.ConfigException; import org.joyqueue.handler.error.ErrorCode; import org.joyqueue.handler.routing.command.NsrCommandSupport; import org.joyqueue.handler.Constants; import org.joyqueue.model.PageResult; import org.joyqueue.model.Pagination; import org.joyqueue.model.QPageQuery; import org.joyqueue.model.domain.Application; import org.joyqueue.model.domain.ApplicationToken; import org.joyqueue.model.domain.Identity; import org.joyqueue.model.query.QApplicationToken; import org.joyqueue.service.ApplicationTokenService; import java.util.Collections; import java.util.List; /** * Created by wangxiaofei1 on 2018/10/23. */ public class ApplicationTokenCommand extends NsrCommandSupport<ApplicationToken, ApplicationTokenService, QApplicationToken> { @Value(Constants.APPLICATION) protected Application application; @Path("search") public Response search(@PageQuery QPageQuery<QApplicationToken> qPageQuery) throws Exception { QApplicationToken query = qPageQuery.getQuery(); List<ApplicationToken> appTokens = Collections.emptyList(); if (query.getApplication() != null) { appTokens = service.findByApp(query.getApplication().getCode()); } if (application != null) { appTokens = service.findByApp(application.getCode()); } Pagination pagination = qPageQuery.getPagination(); pagination.setTotalRecord(appTokens.size()); PageResult<ApplicationToken> result = new PageResult(); result.setPagination(pagination); result.setResult(appTokens); return Responses.success(result.getPagination(), result.getResult()); } @Path("getByApp") public Response pageQuery(@PageQuery QPageQuery<QApplicationToken> qPageQuery) throws Exception { QApplicationToken query = qPageQuery.getQuery(); query.setApplication(new Identity(application.getCode())); List<ApplicationToken> appTokenList = service.findByApp(application.getId()); PageResult<ApplicationToken> result = new PageResult(); Pagination pagination = qPageQuery.getPagination(); pagination.setTotalRecord(appTokenList.size()); pagination.setSize(appTokenList.size()); result.setPagination(pagination); result.setResult(appTokenList); return Responses.success(result.getPagination(), result.getResult()); } @Path("add") public Response add(@Body ApplicationToken model) throws Exception { int tokenCount = service.countByAppId(application.getId()); if (tokenCount >= 5) { throw new ConfigException(ErrorCode.ExcessiveToken); } model.setApplication(application.identity()); service.add(model); return Responses.success(); } /** * 查询按应用id * @param appId * @return * @throws Exception */ @Path("getByAppId") public Response findByAppId(@QueryParam(Constants.APP_ID) long appId) throws Exception { return Responses.success(service.findByApp(appId)); } /** * 查询按应用id * @param id * @param model * @return * @throws Exception */ @Override @Path("update") public Response update(@QueryParam(Constants.ID) String id, @Body ApplicationToken model) throws Exception { model.initializeTime(); model.setApplication(application.identity()); return Responses.success(service.update(model)); } @Override @Path("delete") public Response delete(@QueryParam(Constants.ID) String id) throws Exception { ApplicationToken newModel = service.findById(Long.valueOf(id)); int count = service.delete(newModel); if (count <= 0) { throw new ConfigException(deleteErrorCode()); } //publish(); 暂不进行发布消息 return Responses.success(); } }
/** Copyright 2017 Andrea "Stock" Stocchero 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.pepstock.charba.client.callbacks; import java.util.List; import org.pepstock.charba.client.commons.ArrayListHelper; import org.pepstock.charba.client.commons.ArrayObject; import org.pepstock.charba.client.commons.Key; import org.pepstock.charba.client.commons.NativeObject; import org.pepstock.charba.client.items.TooltipItem; import org.pepstock.charba.client.items.TooltipModel; /** * The option context is used to give contextual information when resolving options. * * @author Andrea "Stock" Stocchero */ public final class TooltipContext extends ChartContext { /** * Name of properties of native object. */ private enum Property implements Key { TOOLTIP("tooltip"), TOOLTIP_ITEMS("tooltipItems"); // name value of property private final String value; /** * Creates with the property value to use in the native object. * * @param value value of property name */ private Property(String value) { this.value = value; } /* * (non-Javadoc) * * @see org.pepstock.charba.client.commons.Key#value() */ @Override public String value() { return value; } } // data point instance private TooltipModel model = null; // element instance private List<TooltipItem> items = null; /** * Creates the object with native object instance to be wrapped. * * @param nativeObject native object instance to be wrapped. */ public TooltipContext(NativeObject nativeObject) { super(nativeObject); } /** * Returns the model of tooltip. * * @return the model of tooltip */ public TooltipModel getModel() { // checks if model object is not already created if (model == null) { // stores model this.model = new TooltipModel(new CallbacksEnvelop<>(getValue(Property.TOOLTIP), true)); } return model; } /** * Returns the model of tooltip. * * @return the model of tooltip */ public List<TooltipItem> getItems() { // checks is items object is already created if (items == null) { // gets all objects in an array ArrayObject objects = getArrayValue(Property.TOOLTIP_ITEMS); // stores items this.items = ArrayListHelper.unmodifiableList(objects, TooltipItem.FACTORY); } return items; } /* * (non-Javadoc) * * @see org.pepstock.charba.client.callbacks.ChartContext#checkIfPropertyIsValid(org.pepstock.charba.client.commons.Key) */ @Override protected boolean checkIfPropertyIsValid(Key property) { // checks if parent provide the validation on the property if (super.checkIfPropertyIsValid(property)) { // checks if is NOT a value of defined properties return !Key.hasKeyByValue(Property.values(), property.value()); } // if here, the property is not valid // and try to override an existing one return false; } }
/** * Copyright (c) 2008-2010 Morten Silcowitz. * * This file is part of the Jinngine physics library * * Jinngine is published under the GPL license, available * at http://www.gnu.org/copyleft/gpl.html. */ package jinngine.geometry.contact; import java.util.Iterator; import java.util.List; import jinngine.collision.GJK; import jinngine.collision.RayCast; import jinngine.geometry.Geometry; import jinngine.geometry.Material; import jinngine.geometry.Sphere; import jinngine.geometry.SupportMap3; import jinngine.math.Matrix3; import jinngine.math.Vector3; import jinngine.physics.Body; /** * Contact generator for Sphere-SupportMap combinations. Insted of using a sphere support map, * we use just the sphere centre point as supprt map for the sphere. This makes GJK behave much * more regular, because the continuous shape is avoided. */ public final class SupportMapSphereContactGenerator implements ContactGenerator { // data @SuppressWarnings("unused") private final Body b1, b2; private final Geometry g1; private final SupportMap3 convex; private final SupportMap3 pointmap; private final Sphere sphere; private final Vector3 spherecentreworld = new Vector3(); private final Vector3 convexcentreworld = new Vector3(); private final ContactPoint cp = new ContactPoint(); private boolean incontact = false; private boolean invertnormal = false; // settings private static double epsilon = 1e-7; private static double envelope = 0.125*0.5; private static double shell = envelope*0.75; // algorithms private final GJK closest = new GJK(); private final RayCast raycast = new RayCast(); public SupportMapSphereContactGenerator(Body b1, Geometry g1, SupportMap3 convex, Body b2, Sphere sphere) { this.convex = convex; this.sphere = sphere; this.b1 = b1; this.b2 = b2; this.g1 = g1; // SupportMap for the sphere centre this.pointmap = new SupportMap3() { public final Vector3 supportPoint(Vector3 direction) { return new Vector3(spherecentreworld); } public final void supportFeature(Vector3 d, List<Vector3> face) {} public final double sphereSweepRadius() {return 0;} }; cp.restitution = 0.7; cp.friction = 0.5; } /** * Alternative constructor for geoemtries in reversed order * @param b2 * @param sphere * @param b1 * @param convex */ public SupportMapSphereContactGenerator( Body b2, Sphere sphere, Body b1, Geometry g1, SupportMap3 convex) { this.convex = convex; this.sphere = sphere; this.b1 = b1; this.g1 = g1; this.b2 = b2; // SupportMap for the sphere centre this.pointmap = new SupportMap3() { public final Vector3 supportPoint(Vector3 direction) { return new Vector3(spherecentreworld); } public final void supportFeature(Vector3 d, List<Vector3> face) {} public final double sphereSweepRadius() { return 0; } }; // default material settings cp.restitution = 0.7; cp.friction = 0.5; invertnormal = true; } @Override public final Iterator<ContactPoint> getContacts() { return new Iterator<ContactPoint>() { boolean done = false; @Override public boolean hasNext() { return (!done)&&incontact; } @Override public ContactPoint next() { done = true; return cp; } @Override public void remove() {} }; } @Override public final void run() { //select the smallest restitution and friction coefficients if ( g1 instanceof Material && sphere instanceof Material) { double ea = ((Material)g1).getRestitution(); double fa = ((Material)g1).getFrictionCoefficient(); double eb = ((Material)sphere).getRestitution(); double fb = ((Material)sphere).getFrictionCoefficient(); //pick smallest values cp.restitution = ea > eb ? eb : ea; cp.friction = fa > fb ? fb : fa; } else if ( g1 instanceof Material ) { cp.restitution = ((Material)g1).getRestitution(); cp.friction = ((Material)g1).getFrictionCoefficient(); } else if ( sphere instanceof Material ) { cp.restitution = ((Material)sphere).getRestitution(); cp.friction = ((Material)sphere).getFrictionCoefficient(); } else { // default values cp.restitution = 0.7; cp.friction = 0.5; } //boolean penetrating = false; // assign the centre of mass position of the sphere in world space sphere.getLocalTranslation(spherecentreworld); Matrix3.multiply(b2.state.rotation, spherecentreworld, spherecentreworld); Vector3.add(spherecentreworld, b2.state.position); // run GJK closest.run(convex, pointmap, cp.paw, cp.pbw, sphere.getRadius()+envelope, epsilon, 31); //notice the envelope size // penetration if ( closest.getState().simplexSize > 3 || cp.paw.sub(cp.pbw).norm() < 1e-7 ) { //penetrating = false; // System.out.println("SupportMap-sphere: penetration"); // we perform a raycast, that is equivalent to // finding the growth distance between Sa and Sb. // by that we obtain a contact normal at the // intersection point. g1.getLocalTranslation(convexcentreworld); // apply body rotation to local displacements (centre of mass of objects) Matrix3.multiply(g1.getBody().state.rotation, convexcentreworld, convexcentreworld); Vector3 direction = g1.getBody().getPosition().add(convexcentreworld).sub(spherecentreworld); // compute the largest possible starting lambda, based on // the support of A-B along the ray direction Vector3 sp = convex.supportPoint(direction.negate()).sub(pointmap.supportPoint(direction)); double lambda = direction.dot(sp)/direction.dot(direction)-envelope/direction.norm(); raycast.run(convex, pointmap, new Vector3(), direction, cp.paw, cp.pbw, lambda, sphere.getRadius()+envelope, epsilon, false); // cp.paw is the point on the convex shape // pb-pa is the normal direction // pa is a point on the convex shape // we project pa onto the direction to approximate real point on convex // p = (pa dot (pb-pa))(pb-pa) cp.normal.assign(cp.paw.sub(cp.pbw).normalize()); //project paw onto the normal cp.paw.assign( spherecentreworld.add( cp.normal.multiply(-cp.paw.dot(cp.normal))) ); cp.pbw.assign( spherecentreworld.add( cp.normal.multiply(sphere.getRadius())) ); } else { cp.normal.assign( cp.paw.sub(cp.pbw).normalize() ); cp.pbw.assign( spherecentreworld.add( cp.normal.multiply(sphere.getRadius())) ); } // find contact distance and interaction point cp.distance = cp.paw.sub(cp.pbw).dot(cp.normal); cp.point.assign( cp.paw.add(cp.pbw).multiply(0.5)); //invert the normal if geometries came in reverse order if (invertnormal) Vector3.multiply( cp.normal, -1); // contact within envelope if ( cp.distance >= 0 && cp.distance < envelope ) { cp.depth = shell-cp.distance; //cp.depth = depth-(envelope/2.0) > 0 ? depth-(envelope/2.0):0; incontact = true; return; // penetration } else if ( cp.distance < 0){ cp.depth = shell-cp.distance; //cp.depth = 0; incontact = true; return; // separation } else { cp.depth = 0; incontact = false; return; } } @Override public final void remove() { // TODO Auto-generated method stub } }
package grandstrat.backend.GrandStrat.Backend; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GrandStratBackendApplication { public static void main(String[] args) { SpringApplication.run(GrandStratBackendApplication.class, args); } }
package com.grydtech.msstack.modelconverter.common; import com.grydtech.msstack.modelconverter.business.Field; import com.grydtech.msstack.modelconverter.business.communication.BusinessEvent; import com.grydtech.msstack.modelconverter.business.communication.BusinessRequest; import com.grydtech.msstack.modelconverter.business.communication.BusinessResponse; import com.grydtech.msstack.modelconverter.business.contract.BusinessContract; import com.grydtech.msstack.modelconverter.business.entity.BusinessEntity; import com.grydtech.msstack.modelconverter.microservice.Attribute; import com.grydtech.msstack.modelconverter.microservice.communication.CommunicationClass; import com.grydtech.msstack.modelconverter.microservice.communication.EventClass; import com.grydtech.msstack.modelconverter.microservice.communication.RequestClass; import com.grydtech.msstack.modelconverter.microservice.communication.ResponseClass; import com.grydtech.msstack.modelconverter.microservice.entity.EntityClass; import com.grydtech.msstack.modelconverter.microservice.handler.HandlerClass; import java.util.ArrayList; import java.util.Collection; import java.util.List; public final class ModelConverterUtil { private ModelConverterUtil() { } // recursively search for entities (sub entities) and create class schemas public static Collection<BusinessEntity> extractEntities(Collection<BusinessEntity> baseEntities) { final List<BusinessEntity> entities = new ArrayList<>(baseEntities); for (int i = 0; i < entities.size(); i++) { BusinessEntity entity = entities.get(i); entity.getFields().stream().filter(field -> field.getEntity() != null).forEach(field -> entities.add(field.getEntity())); } return entities; } public static Collection<BusinessEvent> extractEvents(Collection<BusinessEntity> entities, Collection<BusinessContract> contracts) { final List<BusinessEvent> events = new ArrayList<>(); entities.forEach(businessEntity -> { events.addAll(businessEntity.getEvents()); }); contracts.forEach(businessContract -> { if (businessContract.getHandler().getType().equals(Constants.EVENT_HANDLER_TYPE)) { BusinessEvent event = (BusinessEvent) businessContract.getRequest(); events.add(event); } events.addAll(businessContract.getEvents()); }); return events; } public static EntityClass generateEntityClassSchema(BusinessEntity businessEntity, boolean mainEntity) { EntityClass entityClass = new EntityClass(); entityClass.setId(businessEntity.getId()); entityClass.setName(businessEntity.getName() + Constants.ENTITY_CLASS_SUFFIX); entityClass.setMainEntity(mainEntity); businessEntity.getFields().forEach(field -> { entityClass.addAttribute(generateClassAttribute(field)); }); businessEntity.getEvents().forEach(event -> { entityClass.addEvent(generateEventClassSchema(event)); }); return entityClass; } public static HandlerClass generateHandlerClassSchema(BusinessContract businessContract) { CommunicationClass requestClassSchema; CommunicationClass responseClassSchema; if (businessContract.getHandler().getType().equals(Constants.EVENT_HANDLER_TYPE)) { requestClassSchema = generateEventClassSchema((BusinessEvent) businessContract.getRequest()); responseClassSchema = null; } else { requestClassSchema = generateRequestClassSchema((BusinessRequest) businessContract.getRequest()); responseClassSchema = generateResponseClassSchema((BusinessResponse) businessContract.getResponse()); } HandlerClass handlerClass = new HandlerClass(); handlerClass.setId(businessContract.getId()); handlerClass.setName(businessContract.getHandler().getName() + Constants.HANDLER_CLASS_SUFFIX); handlerClass.setType(businessContract.getHandler().getType()); handlerClass.setRequestClass(requestClassSchema); handlerClass.setResponseClass(responseClassSchema); handlerClass.setEndPoint(businessContract.getEntity().getName() + "/" + businessContract.getHandler().getName()); businessContract.getEvents().forEach(event -> { handlerClass.addEvent(generateEventClassSchema(event)); }); return handlerClass; } public static RequestClass generateRequestClassSchema(BusinessRequest businessRequest) { if (businessRequest == null) return null; RequestClass requestClassSchema = new RequestClass(); requestClassSchema.setId(businessRequest.getId()); requestClassSchema.setName(businessRequest.getName() + Constants.REQUEST_CLASS_SUFFIX); businessRequest.getFields().forEach(field -> requestClassSchema.addAttribute(generateClassAttribute(field))); return requestClassSchema; } public static ResponseClass generateResponseClassSchema(BusinessResponse businessResponse) { if (businessResponse == null) return null; ResponseClass responseClassSchema = new ResponseClass(); responseClassSchema.setId(businessResponse.getId()); responseClassSchema.setName(businessResponse.getName() + Constants.RESPONSE_CLASS_SUFFIX); businessResponse.getFields().forEach(field -> responseClassSchema.addAttribute(generateClassAttribute(field))); return responseClassSchema; } public static EventClass generateEventClassSchema(BusinessEvent businessEvent) { if (businessEvent == null) return null; EventClass eventClassSchema = new EventClass(); eventClassSchema.setId(businessEvent.getId()); eventClassSchema.setName(businessEvent.getName() + Constants.EVENT_CLASS_SUFFIX); eventClassSchema.setEventGroup(businessEvent.getEventGroup()); businessEvent.getFields().forEach(field -> eventClassSchema.addAttribute(generateClassAttribute(field))); return eventClassSchema; } public static Attribute generateClassAttribute(Field field) { Attribute attribute = new Attribute(); attribute.setName(field.getName()); attribute.setArray(field.isArray()); if (field.getEntity() != null) { attribute.setType(field.getEntity().getName() + Constants.ENTITY_CLASS_SUFFIX); attribute.setEntity(true); } else { attribute.setType(field.getType()); attribute.setEntity(false); } return attribute; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.loader; /** * Load data into GemFire in batch and parallel * Should be generified in order to contribute back to Geode. */ public class Loader { }
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_8076 { }
/* * Copyright 2017-2019 Axway Software * * 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.axway.ats.uiengine; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; import org.apache.log4j.Logger; import org.openqa.selenium.WebDriver.TargetLocator; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import com.axway.ats.common.PublicAtsApi; import com.axway.ats.common.systemproperties.AtsSystemProperties; import com.axway.ats.core.utils.StringUtils; import com.axway.ats.uiengine.engine.HiddenHtmlEngine; import com.axway.ats.uiengine.exceptions.SeleniumOperationException; import com.axway.ats.uiengine.internal.driver.InternalObjectsEnum; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.IncorrectnessListener; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.RefreshHandler; import com.gargoylesoftware.htmlunit.SilentCssErrorHandler; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebResponse; import com.gargoylesoftware.htmlunit.util.Cookie; import com.gargoylesoftware.htmlunit.util.WebConnectionWrapper; /** * A non-visual Web driver operating over * <a href="http://htmlunit.sourceforge.net/">HTML Unit</a> browser. * Using Selenium <a href="https://github.com/SeleniumHQ/htmlunit-driver">htmlunit-driver</a> WebDriver. * * <br> * This is a headless (no UI) browser. */ @PublicAtsApi public class HiddenBrowserDriver extends AbstractHtmlDriver { private static Logger log = Logger.getLogger(HiddenBrowserDriver.class); public static final String ALLOW_META_REFRESH_TAG = "htmlunit.allow.meta.refresh.tag"; private String url; private BrowserVersion browserVersion; protected HtmlUnitDriver webDriver; /** * To get HiddenBrowserDriver instance use UiDriver.getHiddenBrowserDriver() * @param url application url */ protected HiddenBrowserDriver( String url ) { this.url = url; this.browserVersion = BrowserVersion.FIREFOX_60; } protected HiddenBrowserDriver( String url, BrowserVersion browserVersion ) { this.url = url; this.browserVersion = browserVersion; } @Override @PublicAtsApi public HiddenHtmlEngine getHtmlEngine() { if (webDriver == null) { throw new IllegalStateException("Browser driver in not initialized. Either start() method is not invoked or browser initialization had failed."); } return new HiddenHtmlEngine(this); } @Override @PublicAtsApi public void start() { webDriver = new HtmlUnitDriver(this.browserVersion); webDriver.setJavascriptEnabled(true); setProxyIfAvailable(); fixHtmlUnitBehaviour(); log.info("Opening URL: " + url); webDriver.get(url); } private void setProxyIfAvailable() { if (!StringUtils.isNullOrEmpty(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST) && !StringUtils.isNullOrEmpty(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT)) { webDriver.setProxy(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST, Integer.parseInt(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT)); } } @Override @PublicAtsApi public void stop() { if (webDriver == null) { log.warn("Invoked HiddenBrowserDriver.stop() before start()"); } else { webDriver.quit(); } } /** * <b>NOTE:</b> This method should not be used directly into the test scripts. * The implementation may be changed by the Automation Framework Team without notice. * @return Internal Object */ public Object getInternalObject( String objectName ) { // NOTE: we use a String argument 'objectName' not directly an InternalObjectsEnum object, because we want to // hide from the end users this method and his usage switch (InternalObjectsEnum.getEnum(objectName)) { case WebDriver: //returns current Selenium Web Driver return this.webDriver; default: break; } return null; } /** * Fixing refresh handler to skip Refresh meta tags * Allowing connections to any host, regardless of whether they have valid certificates or not * Fixing JSESSIONID cookie value * Some applications expect double quotes in the beginning and at the end of the JSESSIONID cookie value */ private void fixHtmlUnitBehaviour() { Field webClientField = null; boolean fieldAccessibleState = false; try { TargetLocator targetLocator = webDriver.switchTo(); webClientField = targetLocator.getClass().getDeclaringClass().getDeclaredField("webClient"); fieldAccessibleState = webClientField.isAccessible(); webClientField.setAccessible(true); final WebClient webClient = (WebClient) webClientField.get(targetLocator.defaultContent()); // Allowing connections to any host, regardless of whether they have valid certificates or not webClient.getOptions().setUseInsecureSSL(true); // Set Http connection timeout (in milliseconds). The default value is 90 seconds, because in Firefox >= 16 // the "network.http.connection-timeout" property is 90. But this value is not enough for some cases. // NOTE: use 0 for infinite timeout webClient.getOptions().setTimeout(5 * 60 * 1000); webClient.getOptions().setRedirectEnabled(true); webClient.getOptions().setJavaScriptEnabled(true); webClient.getOptions().setThrowExceptionOnScriptError(true); webClient.getOptions().setPrintContentOnFailingStatusCode(true); // Hide CSS Warnings webClient.setCssErrorHandler(new SilentCssErrorHandler()); // Suppress warnings like: "Expected content type ... but got ..." webClient.setIncorrectnessListener(new IncorrectnessListener() { // private final Log log = LogFactory.getLog( this.getClass() ); @Override public void notify( final String message, final Object origin ) { // log.warn( message ); } }); if (!Boolean.parseBoolean(System.getProperty(ALLOW_META_REFRESH_TAG))) { /* * Fix for refresh meta tags eg. "<meta http-equiv="refresh" content="300">" * The default refresh handler is with Thread.sleep(refreshSecondsFromMetaTag) in the main thread!!! * * Maybe we should check and test this handler: webClient.setRefreshHandler( new ThreadedRefreshHandler() ); */ webClient.setRefreshHandler(new RefreshHandler() { @Override public void handleRefresh( Page page, URL url, int seconds ) throws IOException { } }); } /* * Fix JSessionId */ // WebConnectionWrapper constructs a WebConnection object wrapping the connection of the WebClient // and places itself (in the constructor) as connection of the WebClient. new WebConnectionWrapper(webClient) { public WebResponse getResponse( WebRequest request ) throws IOException { Cookie jsCookie = webClient.getCookieManager().getCookie("JSESSIONID"); if (jsCookie != null && (!jsCookie.getValue().startsWith("\"") && !jsCookie.getValue().endsWith("\""))) { Cookie newCookie = new Cookie(jsCookie.getDomain(), jsCookie.getName(), "\"" + jsCookie.getValue() + "\"", jsCookie.getPath(), jsCookie.getExpires(), jsCookie.isSecure()); webClient.getCookieManager().removeCookie(jsCookie); webClient.getCookieManager().addCookie(newCookie); } return super.getResponse(request); } }; } catch (Exception e) { throw new SeleniumOperationException("Error retrieving internal Selenium web client", e); } finally { if (webClientField != null) { webClientField.setAccessible(fieldAccessibleState); } } } }
package com.epoint.excel.event; /** * There are multiple interceptors that execute only one of them when fired once.If you want to control which one to * execute please use {@link Order} * * @author Jiaju Zhuang **/ public interface NotRepeatExecutor { /** * To see if it's the same executor * * @return */ String uniqueValue(); }
/* * Forked from: https://github.com/gjoseph/BarbaryWatchService * Waiting to see what the license is - https://github.com/gjoseph/BarbaryWatchService/issues/6 */ package com.barbarysoftware.jna; import com.sun.jna.ptr.PointerByReference; public class FSEventStreamRef extends PointerByReference { }
/* * #%L * Detection Framework (Release) * %% * Copyright (C) 2015 - 2020 Lawrence Livermore National Laboratory (LLNL) * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ package llnl.gnem.core.signalprocessing.extended; import java.util.Vector; import org.apache.commons.math3.complex.Complex; public class FFT { // workspace for the radix-R extenders rvfftRX and irvfftRX private Vector<float[]> xr; private int m; private int R; private int M; // = 2^m // constructors public FFT(int _m, int _R) { m = _m; R = _R; M = 1; for (int i = 0; i < m; i++) M *= 2; if (R > 1) { xr = new Vector<float[]>(R); for (int r = 0; r < R; r++) { xr.addElement(new float[M]); } } else xr = null; } public int fftsize() { return R * M; } public static Complex[] realFFT(float[] realArray) { if (realArray == null) return null; int N = realArray.length; if (N < 1) return new Complex[0]; // Pad input to power of two if necessary... int n = 1; int order = 0; while (n < N) { n *= 2; ++order; } if (n > N) { float[] tmp = realArray; realArray = new float[n]; for (int j = 0; j < N; ++j) realArray[j] = tmp[j]; for (int j = N; j < n; ++j) realArray[j] = 0.0F; } // Do the forward transform on the (possibly padded) real Array rvfft(realArray, order); int M = n / 2 + 1; Complex[] result = new Complex[M]; result[0] = new Complex(realArray[0], 0.0); for (int j = 1; j < M - 1; ++j) result[j] = new Complex(realArray[j], realArray[n - j]); result[M - 1] = new Complex(realArray[n / 2], 0.0); return result; } /* CC=============================================================CC CC CC CC A real-valued, in-place, split-radix FFT program CC CC Real input and output data in arrays X CC CC Length is N=2**m CC CC Decimation-in-time, cos/sin in second loop CC CC and computed recursively CC CC Output in order: CC CC [ Re(0),Re(1),....,Re(N/2),Im(N/2-1),...Im(1)] CC CC CC CC H.V. Sorensen, Rice University, Oct. 1985 CC CC Arpa address: hvs@rice.edu CC CC Modified: CC CC F. Bonzanigo, ETH-Zurich, Sep. 1986 CC CC H.V. Sorensen, Rice University Mar. 1987 CC CC CC CC=============================================================CC */ // C++ / ANSI C conversion by D. Harris 5/20/95 // C++ to Java conversion by D. Harris 5/14/99 public static void rvfft(float[] x, int _m) { int n = 1; for (int i = 0; i < _m; i++) n *= 2; //-------Digit reverse counter----------------------------------- int j = 1; int k; float t; for (int i = 1; i < n; i++) { if (i < j) { t = x[j - 1]; x[j - 1] = x[i - 1]; x[i - 1] = t; } k = n / 2; while (k < j) { j -= k; k = k / 2; } j += k; } //-----Length Eo butterflies------------------------------------ int is = 1; int id = 4; int i0; do { for (i0 = is; i0 <= n; i0 += id) { t = x[i0 - 1]; x[i0 - 1] = t + x[i0]; x[i0] = t - x[i0]; } is = 2 * id - 1; id *= 4; } while (is < n); //-------L shaped butterflies------------------------------------ int n2 = 2; int n4; for (k = 2; k <= _m; k++) { n2 *= 2; n4 = n2 / 4; stage(n, n2, n4, x, n4, 2 * n4, 3 * n4); } } private static void stage(int N, int N2, int N4, float[] X, int OFF2, int OFF3, int OFF4) { /*C===============================================================C C Function STAGE - the work-horse of the FFT C C===============================================================C */ int N8 = N2 / 8; int IS = 0; int ID = N2 * 2; int I1, I2, I, J, JN; float T1, T2, T3, T4, T5, T6; double E; double SW1I, SS3, SD1, SD3, CW1R, CC3, CD1, CD3; double DT1, DT3; do { for (I1 = IS; I1 < N; I1 += ID) { T1 = X[OFF4 + I1] + X[OFF3 + I1]; X[OFF4 + I1] = X[OFF4 + I1] - X[OFF3 + I1]; X[OFF3 + I1] = X[I1] - T1; X[I1] = X[I1] + T1; } IS = 2 * ID - N2; ID = 4 * ID; } while (IS < N); if (N4 > 1) { IS = 0; ID = N2 * 2; do { for (I2 = IS + N8; I2 < N; I2 += ID) { T1 = (float) ((X[OFF3 + I2] + X[OFF4 + I2]) * .7071067811865475); T2 = (float) ((X[OFF3 + I2] - X[OFF4 + I2]) * .7071067811865475); X[OFF4 + I2] = X[OFF2 + I2] - T1; X[OFF3 + I2] = -X[OFF2 + I2] - T1; X[OFF2 + I2] = X[I2] - T2; X[I2] = X[I2] + T2; } IS = 2 * ID - N2; ID = 4 * ID; } while (IS < N); if (N8 > 1) { E = 2. * 3.14159265358979323 / N2; SW1I = Math.sin(E); SD1 = SW1I; SD3 = (3. - 4. * SD1 * SD1) * SD1; SS3 = SD3; CW1R = Math.cos(E); CD1 = CW1R; CD3 = (4. * CD1 * CD1 - 3.) * CD1; CC3 = CD3; for (J = 2; J <= N8; J++) { IS = 0; ID = 2 * N2; JN = N4 - 2 * J + 2; do { for (I = IS + J; I <= N; I += ID) { I1 = I - 1; I2 = I1 + JN; T1 = (float) (X[OFF3 + I1] * CW1R + X[OFF3 + I2] * SW1I); T2 = (float) (X[OFF3 + I2] * CW1R - X[OFF3 + I1] * SW1I); T3 = (float) (X[OFF4 + I1] * CC3 + X[OFF4 + I2] * SS3); T4 = (float) (X[OFF4 + I2] * CC3 - X[OFF4 + I1] * SS3); T5 = T1 + T3; T6 = T2 + T4; T3 = T1 - T3; T4 = T2 - T4; T2 = T6 + X[OFF2 + I2]; X[OFF3 + I1] = T6 - X[OFF2 + I2]; X[OFF4 + I2] = T2; T2 = X[OFF2 + I1] - T3; X[OFF3 + I2] = -X[OFF2 + I1] - T3; X[OFF4 + I1] = T2; T1 = X[I1] + T5; X[OFF2 + I2] = X[I1] - T5; X[I1] = T1; T1 = X[I2] + T4; X[I2] = X[I2] - T4; X[OFF2 + I1] = T1; } IS = 2 * ID - N2; ID = 4 * ID; } while (IS < N); DT1 = CW1R * CD1 - SW1I * SD1; SW1I = CW1R * SD1 + SW1I * CD1; CW1R = DT1; DT3 = CC3 * CD3 - SS3 * SD3; SS3 = CC3 * SD3 + SS3 * CD3; CC3 = DT3; } } } } /*CC===============================================================CC CC CC CC A real-valued, in-place, split-radix IFFT program CC CC Symmetric input and real output data in arrays X CC CC Length is N=2**m CC CC Decimation-in-frequency, cos/sin in second loop CC CC and is computed recursively CC CC Input order : CC CC [ Re(0),Re(1),....,Re(N/2),Im(N/2-1),...Im(1)] CC CC CC CC H.V. Sorensen, Rice University, Nov. 1985 CC CC Email address: hvs@rice.edu CC CC Modified: CC CC F. Bonzanigo, ETH-Zurich, Sep. 1986 CC CC H.V. Sorensen, Rice University Mar. 1987 CC CC CC CC=================================================================CC */ // Conversion to C++ / ANSI C by D. Harris 5/20/95 // Conversion from C++ to Java by D. Harris 5/14/99 public static void irvfft(float[] x, int _m) { int j = 1; int k; float t; int n = 1; for (int i = 0; i < _m; i++) n *= 2; //-------L shaped butterflies------------------------------------- int n2 = 2 * n; int n4; for (k = 1; k < _m; k++) { n2 /= 2; n4 = n2 / 4; istage(n, n2, n4, x, n4, 2 * n4, 3 * n4); } //-----Length Eo butterflies----------------------------------- int is = 1; int id = 4; int i1; do { for (i1 = is; i1 <= n; i1 += id) { t = x[i1 - 1]; x[i1 - 1] = t + x[i1]; x[i1] = t - x[i1]; } is = 2 * id - 1; id *= 4; } while (is < n); //-------Digit reverse counter----------------------------------- for (int i = 1; i < n; i++) { if (i < j) { t = x[j - 1]; x[j - 1] = x[i - 1]; x[i - 1] = t; } k = n / 2; while (k < j) { j -= k; k = k / 2; } j += k; } //-------Divide by N--------------------------------------------- for (int i = 0; i < n; i++) x[i] /= n; } private static void istage(int N, int N2, int N4, float[] X, int OFF2, int OFF3, int OFF4) { /*C===============================================================C C function istage - the work-horse of the IFFT C C===============================================================C */ int N8 = N4 / 2; int IS = 0; int ID = 2 * N2; int I1, I2, I, J, JN; float T1, T2, T3, T4, T5; double E; double SW1I, SS3, SD1, SD3, CW1R, CC3, CD1, CD3; double DT1, DT3; do { for (I1 = IS; I1 < N; I1 += ID) { T1 = X[I1] - X[OFF3 + I1]; X[I1] = X[I1] + X[OFF3 + I1]; X[OFF2 + I1] = 2 * X[OFF2 + I1]; T2 = 2 * X[OFF4 + I1]; X[OFF4 + I1] = T1 + T2; X[OFF3 + I1] = T1 - T2; } IS = 2 * ID - N2; ID = 4 * ID; } while (IS < N); if (N4 > 1) { IS = 0; ID = 2 * N2; do { for (I1 = IS + N8; I1 < N; I1 += ID) { T1 = (float) ((X[OFF2 + I1] - X[I1]) * 1.4142135623730950488); T2 = (float) ((X[OFF4 + I1] + X[OFF3 + I1]) * 1.4142135623730950488); X[I1] = X[I1] + X[OFF2 + I1]; X[OFF2 + I1] = X[OFF4 + I1] - X[OFF3 + I1]; X[OFF3 + I1] = -T2 - T1; X[OFF4 + I1] = -T2 + T1; } IS = 2 * ID - N2; ID = 4 * ID; } while (IS < N - 1); if (N8 > 1) { E = 6.283185307179586 / N2; SW1I = Math.sin(E); SD1 = SW1I; SD3 = (3.0 - 4.0 * SD1 * SD1) * SD1; SS3 = SD3; CW1R = Math.cos(E); CD1 = CW1R; CD3 = (4.0 * CD1 * CD1 - 3.0) * CD1; CC3 = CD3; for (J = 2; J <= N8; J++) { IS = 0; ID = 2 * N2; JN = N4 - 2 * J + 2; do { for (I = IS + J; I <= N; I += ID) { I1 = I - 1; I2 = I1 + JN; T1 = X[I1] - X[OFF2 + I2]; X[I1] = X[I1] + X[OFF2 + I2]; T2 = X[I2] - X[OFF2 + I1]; X[I2] = X[OFF2 + I1] + X[I2]; T3 = X[OFF4 + I2] + X[OFF3 + I1]; X[OFF2 + I2] = X[OFF4 + I2] - X[OFF3 + I1]; T4 = X[OFF4 + I1] + X[OFF3 + I2]; X[OFF2 + I1] = X[OFF4 + I1] - X[OFF3 + I2]; T5 = T1 - T4; T1 = T1 + T4; T4 = T2 - T3; T2 = T2 + T3; X[OFF3 + I1] = (float) (T5 * CW1R + T4 * SW1I); X[OFF3 + I2] = (float) (-T4 * CW1R + T5 * SW1I); X[OFF4 + I1] = (float) (T1 * CC3 - T2 * SS3); X[OFF4 + I2] = (float) (T2 * CC3 + T1 * SS3); } IS = 2 * ID - N2; ID = 4 * ID; } while (IS < N); DT1 = CW1R * CD1 - SW1I * SD1; SW1I = CW1R * SD1 + SW1I * CD1; CW1R = DT1; DT3 = CC3 * CD3 - SS3 * SD3; SS3 = CC3 * SD3 + SS3 * CD3; CC3 = DT3; } } } } public void rvfftRX(float[] x) { // degenerate case if (R == 1) { rvfft(x, m); return; } // radix-R extender for real-valued, forward, power of 2 FFT // Computes X[k] = sum(n = 0 : N-1) x[n] e^(-j*2*pi*k*n/N); k = 0, ..., N-1 // where N = M*R // and M = 2^m, R is odd and small, e.g. 3, 5, 7 // decimates x[n] into R subsequences // n = R*q + r q = 0, ..., M-1; r = 0, ..., R-1 // xr[q] = x[R*q + r] // constructs length N DFT from R length M DFTs: // Xr[i] = sum(q = 0 : M-1) xr[q] e^(-j*2*pi/M) // evaluates X[k] in bands, // k = i + p*M i = 0, ..., M-1; p = 0, ..., R-1 // X[i+p*M] = sum(r = 0 : R-1) WR^(p*r) * Xr[i] * WN^(i*r) // WR = e^(-j*2*pi/R) WN = e^(-j*2*pi/N) double twoPI = 2.0 * Math.PI; int half_M = M / 2; int N = M * R; int half_N = N / 2; int n; float[] xrptr; // decimate sequence and compute length-M DFTs for (int r = 0; r < R; r++) { xrptr = xr.elementAt(r); n = r; for (int q = 0; q < M; q++) { xrptr[q] = x[n]; n += R; } rvfft(xrptr, m); } double dWr, dWi; double ddWr, ddWi; // precompute table of powers of WR using coupled-form oscillator int nw = (R - 1) * (R - 1) + 1; double[] WRr = new double[nw]; double[] WRi = new double[nw]; double arg; WRr[0] = 1.0; WRi[0] = 0.0; arg = twoPI / R; dWr = Math.cos(arg); dWi = -Math.sin(arg); for (int j = 1; j < nw; j++) { WRr[j] = dWr * WRr[j - 1] - dWi * WRi[j - 1]; WRi[j] = dWr * WRi[j - 1] + dWi * WRr[j - 1]; } // compute partial result Xr[i] * WN^(i*r) // for // X[i+p*M] = sum(r = 0 : R-1) WR^(p*r) * Xr[i] * WN^(i*r) double tmp; float[] tmpr = new float[R]; float[] tmpi = new float[R]; int k; double WNr, WNi; float Yr, Yi; arg = twoPI / N; ddWr = Math.cos(arg); ddWi = -Math.sin(arg); dWr = 1.0; dWi = 0.0; for (int i = 0; i < M; i++) { // extract Xr[i] for each r if (i > 0 && i < half_M) { for (int r = 0; r < R; r++) { xrptr = xr.elementAt(r); tmpr[r] = xrptr[i]; tmpi[r] = xrptr[M - i]; } } else if (i > half_M) { for (int r = 0; r < R; r++) { xrptr = xr.elementAt(r); tmpr[r] = xrptr[M - i]; tmpi[r] = -xrptr[i]; } } else { for (int r = 0; r < R; r++) { xrptr = xr.elementAt(r); tmpr[r] = xrptr[i]; tmpi[r] = 0.0f; } } // scale XR[i] by (WN^i)^r WNr = dWr; WNi = dWi; for (int r = 1; r < R; r++) { tmp = WNr * tmpr[r] - WNi * tmpi[r]; tmpi[r] = (float) (WNr * tmpi[r] + WNi * tmpr[r]); tmpr[r] = (float) tmp; tmp = WNr * dWr - WNi * dWi; WNi = WNr * dWi + WNi * dWr; WNr = tmp; } tmp = dWr * ddWr - dWi * ddWi; dWi = dWr * ddWi + dWi * ddWr; dWr = tmp; // compute X[i+p*M] = sum(r = 0 : R-1) WR^(p*r) * { Xr[i] * WN^(i*r) } // for p = 0, ..., R-1 // special case p = 0 Yr = 0.0f; Yi = 0.0f; for (int r = 0; r < R; r++) { Yr += tmpr[r]; Yi += tmpi[r]; } if (i == 0) x[i] = Yr; else { x[i] = Yr; x[N - i] = Yi; } // all other cases // note that for real x[n], X[k] need be computed only through // k = N/2 due to conjugate symmetry // example: N = 12 = 3 * 2^2; R = 3; M = 4 // k 0 1 2 3 4 5 6 7 8 9 10 11 // p 0 0 0 0 1 1 1 1 2 2 2 2 // i 0 1 2 3 0 1 2 3 0 1 2 3 // samples 7 through 11 obtained by symmetry // need compute samples only through p = (R-1)/2 int pmax = (R - 1) / 2; int pr; k = i + M; for (int p = 1; p < pmax; p++) { Yr = 0.0f; Yi = 0.0f; pr = 0; for (int r = 0; r < R; r++) { Yr += (float) (WRr[pr] * tmpr[r] - WRi[pr] * tmpi[r]); Yi += (float) (WRr[pr] * tmpi[r] + WRi[pr] * tmpr[r]); pr += p; } x[k] = Yr; x[N - k] = Yi; k += M; } // special case p = (R-1)/2 k = i + pmax * M; if (k <= half_N) { Yr = 0.0f; pr = 0; for (int r = 0; r < R; r++) { Yr += (float) (WRr[pr] * tmpr[r] - WRi[pr] * tmpi[r]); pr += pmax; } x[k] = Yr; if (k < half_N) { Yi = 0.0f; pr = 0; for (int r = 0; r < R; r++) { Yi += (float) (WRr[pr] * tmpi[r] + WRi[pr] * tmpr[r]); pr += pmax; } x[N - k] = Yi; } } } } public void irvfftRX(float[] x) { // degenerate case if (R == 1) { irvfft(x, m); return; } // R-factor extender for power of two, real-valued inverse FFT // Assumes N = R*M // where M = 2^m and R is odd and small, e.g. 3, 5, 7 // computes x[n] = 1/N sum(k = 0 : N-1) X[k] e^(j*2*pi*k*n / N) // makes substitutions: // n = R*q + r q = 0, ..., M-1 r = 0, ..., R-1 // k = i + p*M i = 0, ..., M-1 p = 0, ..., R-1 // to obtain: // x_r[q] = x[ q*R + r ] = 1/M sum(i = 0 : M-1) X_r[i] e^(j*2*pi*i*q / M) // where: // X_r[i] = ( 1/R sum(p = 0 : R-1) X[i+p*M] WR^(p*r) ) WN^(i*r) // and WR = e^(2*pi/R) and WN = e^(2*pi/N) int N = M * R; int half_N = N / 2; // special case r = 0 float Yr, Yi; float[] xrptr = xr.elementAt(0); int k; for (int i = 0; i <= M / 2; i++) { Yr = 0.0f; Yi = 0.0f; k = i; for (int p = 0; p < R; p++) { if (k <= half_N) { Yr += x[k]; if (k > 0 && k < half_N) Yi += x[N - k]; } else { Yr += x[N - k]; Yi -= x[k]; } k += M; } xrptr[i] = Yr / R; if (i != 0 && i != M / 2) xrptr[M - i] = Yi / R; } irvfft(xrptr, m); // remaining cases: r = 1, ..., R-1 // X_r[i] = ( 1/R sum(p=0:R-1) X[i+p*M] WR^(p*r) ) WN^(i*r) double WNr, WNi; double dWNr, dWNi; double tmpr, tmpi; double[] WRr = new double[R]; double[] WRi = new double[R]; double dWRr, dWRi; WRr[0] = 1.0; WRi[0] = 0.0; double twoPI = 2.0 * Math.PI; for (int r = 1; r < R; r++) { xrptr = xr.elementAt(r); // precompute table of (WR^r)^p with coupled form oscillator dWRr = Math.cos((twoPI * r) / R); dWRi = Math.sin((twoPI * r) / R); for (int p = 1; p < R; p++) { WRr[p] = dWRr * WRr[p - 1] - dWRi * WRi[p - 1]; WRi[p] = dWRr * WRi[p - 1] + dWRi * WRr[p - 1]; } dWNr = Math.cos(twoPI * r / N); dWNi = Math.sin(twoPI * r / N); WNr = 1.0 / (R); WNi = 0.0; for (int i = 0; i <= M / 2; i++) { Yr = 0.0f; Yi = 0.0f; k = i; for (int p = 0; p < R; p++) { if (k > 0 && k < half_N) { tmpr = x[k]; tmpi = x[N - k]; } else if (k > half_N) { tmpr = x[N - k]; tmpi = -x[k]; } else { tmpr = x[k]; tmpi = 0.0; } Yr += WRr[p] * tmpr - WRi[p] * tmpi; Yi += WRr[p] * tmpi + WRi[p] * tmpr; k += M; } xrptr[i] = (float) (WNr * Yr - WNi * Yi); if (i != 0 && i != M / 2) xrptr[M - i] = (float) (WNr * Yi + WNi * Yr); tmpr = dWNr * WNr - dWNi * WNi; WNi = dWNr * WNi + dWNi * WNr; WNr = tmpr; } irvfft(xrptr, m); } // interleave resulting signals int n; for (int r = 0; r < R; r++) { xrptr = xr.elementAt(r); n = r; for (int q = 0; q < M; q++) { x[n] = xrptr[q]; n += R; } } } }
/* * Copyright 2016 ThoughtWorks, 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.thoughtworks.go.config; import com.thoughtworks.go.config.exceptions.ConfigFileHasChangedException; import com.thoughtworks.go.config.materials.MaterialConfigs; import com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig; import com.thoughtworks.go.config.update.ConfigUpdateCheckFailedException; import com.thoughtworks.go.domain.AgentInstance; import com.thoughtworks.go.domain.NullTask; import com.thoughtworks.go.helper.ConfigFileFixture; import com.thoughtworks.go.helper.PipelineMother; import com.thoughtworks.go.helper.StageConfigMother; import com.thoughtworks.go.i18n.Localizable; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.service.PipelineConfigService; import com.thoughtworks.go.server.service.result.LocalizedOperationResult; import com.thoughtworks.go.util.*; import movedclasses.RenameClass4; import org.apache.commons.io.FileUtils; import org.junit.Test; import org.mockito.Matchers; import java.io.File; import java.util.List; import static com.thoughtworks.go.config.PipelineConfigs.DEFAULT_GROUP; import static com.thoughtworks.go.helper.ConfigFileFixture.*; import static com.thoughtworks.go.util.DataStructureUtils.a; import static com.thoughtworks.go.util.TestUtils.assertContains; import static com.thoughtworks.go.util.TestUtils.sizeIs; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public abstract class GoConfigDaoTestBase { protected GoConfigFileHelper configHelper ; protected GoConfigDao goConfigDao ; protected CachedGoConfig cachedGoConfig; protected RenameClass4 logger; @Test public void shouldCreateCruiseConfigFromBasicConfigFile() throws Exception { CruiseConfig cruiseConfig = GoConfigFileHelper.load(WITH_3_AGENT_CONFIG); assertThat(cruiseConfig, is(notNullValue())); PipelineConfig pipelineConfig = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline1")); assertThat(pipelineConfig.size(), is(1)); StageConfig stageConfig = pipelineConfig.get(0); assertThat(stageConfig.name(), is(new CaseInsensitiveString("mingle"))); assertThat(pipelineConfig.materialConfigs(), is(notNullValue())); final JobConfig cardList = stageConfig.jobConfigByInstanceName("cardlist", true); assertThat(cardList.name(), is(new CaseInsensitiveString("cardlist"))); assertThat(stageConfig.jobConfigByInstanceName("bluemonkeybutt", true).name(), is(new CaseInsensitiveString("bluemonkeybutt"))); assertThat(cardList.tasks(), sizeIs(1)); assertThat(cardList.tasks().first(), instanceOf(NullTask.class)); } @Test public void shouldGetAgents() throws Exception { CruiseConfig cruiseConfig = GoConfigFileHelper.load(WITH_3_AGENT_CONFIG); Agents agents = cruiseConfig.agents(); assertThat(agents.size(), is(3)); final AgentConfig approvedAgentConfig = agents.getAgentByUuid("3"); assertThat(approvedAgentConfig.getHostname(), is("test3.com")); assertThat(approvedAgentConfig.getIpAddress(), is("192.168.0.3")); assertThat(approvedAgentConfig.getResources().toString(), is("jdk1.4")); final AgentConfig deniedAgentConfig = agents.getAgentByUuid("2"); assertThat(deniedAgentConfig.isDisabled(), is(true)); } @Test public void shouldThrowExceptionIfFileIsInvalid() throws Exception { try { useConfigString("invalid config file"); goConfigDao.load(); fail("Should have thrown a parse exception"); } catch (Exception expected) { assertThat(expected.getMessage(), containsString("Content is not allowed in prolog.")); } } @Test public void shouldGetArtifactsFromBuildPlan() throws Exception { CruiseConfig cruiseConfig = GoConfigFileHelper.load(WITH_3_AGENT_CONFIG); final ArtifactPlans cardListArtifacts = cruiseConfig.jobConfigByName("pipeline1", "mingle", "cardlist", true).artifactPlans(); assertThat(cardListArtifacts.size(), is(0)); assertThat(cruiseConfig.jobConfigByName("pipeline1", "mingle", "bluemonkeybutt", true).artifactPlans().size(), is(1)); } @Test public void shouldAddAgentToConfigFile() throws Exception { Resources resources = new Resources("java"); AgentConfig approvedAgentConfig = new AgentConfig("uuid", "test1", "192.168.0.1", resources); AgentConfig deniedAgentConfig = new AgentConfig("", "test2", "192.168.0.2", resources); deniedAgentConfig.disable(); goConfigDao.addAgent(approvedAgentConfig); goConfigDao.addAgent(deniedAgentConfig); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.agents().size(), is(2)); assertThat(cruiseConfig.agents().get(0), is(approvedAgentConfig)); assertThat(cruiseConfig.agents().get(0).getResources(), is(resources)); assertThat(cruiseConfig.agents().get(1), is(deniedAgentConfig)); assertThat(cruiseConfig.agents().get(1).isDisabled(), is(Boolean.TRUE)); assertThat(cruiseConfig.agents().get(1).getResources(), is(resources)); } @Test public void shouldDeleteMultipleAgents() { AgentConfig agentConfig1 = new AgentConfig("UUID1", "remote-host1", "50.40.30.21"); AgentConfig agentConfig2 = new AgentConfig("UUID2", "remote-host2", "50.40.30.22"); agentConfig1.disable(); agentConfig2.disable(); AgentInstance fromConfigFile1 = AgentInstance.createFromConfig(agentConfig1, new SystemEnvironment()); AgentInstance fromConfigFile2 = AgentInstance.createFromConfig(agentConfig2, new SystemEnvironment()); GoConfigDao.CompositeConfigCommand command = goConfigDao.commandForDeletingAgents(fromConfigFile1, fromConfigFile2); List<UpdateConfigCommand> commands = command.getCommands(); assertThat(commands.size(), is(2)); String uuid1 = (String) ReflectionUtil.getField(commands.get(0), "uuid"); String uuid2 = (String) ReflectionUtil.getField(commands.get(1), "uuid"); assertThat(uuid1, is("UUID1")); assertThat(uuid2, is("UUID2")); } @Test public void shouldDeleteAgentFromConfigFileGivenUUID() throws Exception { AgentConfig agentConfig1 = new AgentConfig("uuid1", "test1", "192.168.0.1"); AgentConfig agentConfig2 = new AgentConfig("uuid2", "test2", "192.168.0.2"); AgentInstance fromConfigFile1 = AgentInstance.createFromConfig(agentConfig1, new SystemEnvironment()); AgentInstance fromConfigFile2 = AgentInstance.createFromConfig(agentConfig2, new SystemEnvironment()); goConfigDao.addAgent(agentConfig1); goConfigDao.addAgent(agentConfig2); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.agents().size(), is(2)); goConfigDao.deleteAgents(fromConfigFile1); cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.agents().size(), is(1)); assertThat(cruiseConfig.agents().get(0), is(agentConfig2)); } @Test public void shouldRemoveAgentFromEnvironmentBeforeDeletingAgent() throws Exception { AgentConfig agentConfig1 = new AgentConfig("uuid1", "hostname", "127.0.0.1"); AgentInstance fromConfigFile1 = AgentInstance.createFromConfig(agentConfig1, new SystemEnvironment()); goConfigDao.addAgent(agentConfig1); goConfigDao.addAgent(new AgentConfig("uuid2", "hostname", "127.0.0.1")); BasicEnvironmentConfig env = new BasicEnvironmentConfig(new CaseInsensitiveString("foo-environment")); env.addAgent("uuid1"); env.addAgent("uuid2"); goConfigDao.addEnvironment(env); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.getEnvironments().get(0).getAgents().size(), is(2)); goConfigDao.deleteAgents(fromConfigFile1); cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.getEnvironments().get(0).getAgents().size(), is(1)); assertThat(cruiseConfig.getEnvironments().get(0).getAgents().get(0).getUuid(), is("uuid2")); } @Test public void shouldAddPipelineToConfigFile() throws Exception { CruiseConfig cruiseConfig = goConfigDao.load(); int oldsize = cruiseConfig.numberOfPipelines(); PipelineConfig pipelineConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("spring", "ut", "www.spring.com"); goConfigDao.addPipeline(pipelineConfig, DEFAULT_GROUP); cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.numberOfPipelines(), is(oldsize + 1)); assertThat(cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("spring")), is(pipelineConfig)); } @Test public void shouldFailToAddDuplicatePipelineToConfigFile() throws Exception { CruiseConfig cruiseConfig = goConfigDao.load(); int oldsize = cruiseConfig.numberOfPipelines(); PipelineConfig pipelineConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("spring", "ut", "www.spring.com"); goConfigDao.addPipeline(pipelineConfig, DEFAULT_GROUP); cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.numberOfPipelines(), is(oldsize + 1)); assertThat(cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("spring")), is(pipelineConfig)); PipelineConfig dupPipelineConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("spring", "ut", "www.spring.com"); try { goConfigDao.addPipeline(dupPipelineConfig, DEFAULT_GROUP); } catch (RuntimeException ex) { assertThat(ex.getMessage(),is("You have defined multiple pipelines called 'spring'. Pipeline names must be unique.")); return; } fail("Should have thrown"); } @Test public void shouldFailWhenConfigUpdateCannotBeMergedWithLatestRevision() throws Exception { final String originalMd5 = goConfigDao.load().getMd5(); goConfigDao.updateConfig(configHelper.addPipelineCommand(originalMd5, "p1", "stage1", "build1")); final String md5WhenPipelineIsAdded = goConfigDao.load().getMd5(); goConfigDao.updateConfig(configHelper.changeJobNameCommand(md5WhenPipelineIsAdded, "p1", "stage1", "build1", "new_build")); try { goConfigDao.updateConfig(new NoOverwriteUpdateConfigCommand() { public String unmodifiedMd5() { return md5WhenPipelineIsAdded; } public CruiseConfig update(CruiseConfig cruiseConfig) throws Exception { deletePipeline(cruiseConfig); return cruiseConfig; } private void deletePipeline(CruiseConfig cruiseConfig) { cruiseConfig.getGroups().get(0).remove(0); } }); fail("should not have allowed no-overwrite stale update"); } catch (RuntimeException e) { assertThat(e.getMessage(), is(ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH)); } } @Test public void shouldNotFailNoOverwriteUpdateWhenEditingUnmodifiedCopy() throws Exception { final String md5 = goConfigDao.md5OfConfigFile(); try { ConfigSaveState configSaveState = goConfigDao.updateConfig(new NoOverwriteUpdateConfigCommand() { public String unmodifiedMd5() { return md5; } public CruiseConfig update(CruiseConfig cruiseConfig) throws Exception { cruiseConfig.getEnvironments().add(new BasicEnvironmentConfig(new CaseInsensitiveString("foo"))); return cruiseConfig; } }); assertThat(configSaveState, is(ConfigSaveState.UPDATED)); } catch (RuntimeException e) { fail("should not have failed for edit on unmodified config."); } } @Test public void shouldNotFailUpdateWithOverwritePermittedWhenEditingStaleCopy() throws Exception { try { goConfigDao.updateConfig(new UpdateConfigCommand() { public CruiseConfig update(CruiseConfig cruiseConfig) throws Exception { cruiseConfig.getEnvironments().add(new BasicEnvironmentConfig(new CaseInsensitiveString("foo"))); return cruiseConfig; } }); } catch (RuntimeException e) { fail("should not have failed for edit when overwrite allowed."); } } @Test public void shouldFeedCloneOfConfigBackToCommand() throws Exception { CheckedTestUpdateCommand command = new CheckedTestUpdateCommand(cachedGoConfig.loadForEditing().getMd5(), true) { @Override public CruiseConfig update(CruiseConfig cruiseConfig) throws Exception { PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("foo"), "#{bar}-${COUNT}", null, false, new MaterialConfigs(new HgMaterialConfig("url", null)), a(StageConfigMother.custom("stage", "job"))); pipelineConfig.addParam(new ParamConfig("bar", "baz")); cruiseConfig.addPipeline("my-group", pipelineConfig); return cruiseConfig; } }; goConfigDao.updateConfig(command); assertThat(command.after.pipelineConfigByName(new CaseInsensitiveString("foo")).getLabelTemplate(), is("baz-${COUNT}")); assertThat(command.after.getEnvironments().size(), is(0)); command.after.addEnvironment("bar"); assertThat(cachedGoConfig.currentConfig().getEnvironments().size(), is(0)); } @Test public void shouldNotUpdateIfCannotContinueIfTheCommandIsPreprocessable() throws Exception { CheckedTestUpdateCommand command = new CheckedTestUpdateCommand(cachedGoConfig.loadForEditing().getMd5(), false); try { goConfigDao.updateConfig(command); fail("should have failed as check returned false"); } catch (ConfigUpdateCheckFailedException ignored) { } assertThat(command.wasUpdated, is(false)); assertThat(command.after, not(nullValue())); } @Test public void shouldPerformUpdateIfCanContinue() throws Exception { CheckedTestUpdateCommand command = new CheckedTestUpdateCommand(cachedGoConfig.loadForEditing().getMd5(), true); goConfigDao.updateConfig(command); assertThat(command.wasUpdated, is(true)); } @Test public void shouldBePassedTheLatestCruiseConfigWhileCheckingBeforeUpdate() { configHelper.addTemplate("my-template", "my-stage"); configHelper.addPipeline("pipeline", "stage"); configHelper.addPipelineWithTemplate(PipelineConfigs.DEFAULT_GROUP, "my-pipeline", "my-template"); CheckedTestUpdateCommand command = spy(new CheckedTestUpdateCommand(cachedGoConfig.loadForEditing().getMd5(), true)); goConfigDao.updateConfig(command); verify(command).canContinue(cachedGoConfig.currentConfig()); } @Test public void shouldAddEnvironmentToConfigFile() throws Exception { CruiseConfig cruiseConfig = goConfigDao.load(); int oldsize = cruiseConfig.getEnvironments().size(); goConfigDao.addEnvironment(new BasicEnvironmentConfig(new CaseInsensitiveString("foo-environment"))); cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.getEnvironments().size(), is(oldsize + 1)); } @Test public void shouldAddPipelineOnTheTopOfSameGroupWhenGivenGroupExist() throws Exception { PipelineConfig springConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("spring", "ut", "www.spring.com"); PipelineConfig mingleConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("mingle", "ut", "www.spring.com"); goConfigDao.addPipeline(springConfig, "group1"); goConfigDao.addPipeline(mingleConfig, "group1"); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.numbersOfPipeline("group1"), is(2)); assertThat(cruiseConfig.find("group1", 0), is(mingleConfig)); } @Test public void shouldAddPipelineToTheNewGroupWhenGivenGroupDoesNotExist() throws Exception { PipelineConfig springConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("spring", "ut", "www.spring.com"); PipelineConfig mingleConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("mingle", "ut", "www.spring.com"); goConfigDao.addPipeline(springConfig, "group1"); goConfigDao.addPipeline(mingleConfig, "group"); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.numbersOfPipeline("group1"), is(1)); assertThat(cruiseConfig.numbersOfPipeline("group"), is(1)); } @Test public void shouldAddPipelineToDefaultGroupWhenNoGroupNameSpecified() throws Exception { PipelineConfig springConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("spring", "ut", "www.spring.com"); goConfigDao.addPipeline(springConfig, null); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.numbersOfPipeline(DEFAULT_GROUP), is(1)); } @Test public void shouldAddPipelineToTheTopOfConfigFile() throws Exception { goConfigDao.load(); PipelineConfig pipelineConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("addedFirst", "ut", "www.spring.com"); PipelineConfig pipelineConfig2 = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("addedSecond", "ut", "www.spring.com"); goConfigDao.addPipeline(pipelineConfig, DEFAULT_GROUP); goConfigDao.addPipeline(pipelineConfig2, DEFAULT_GROUP); goConfigDao.load(); final File configFile = new File(goConfigDao.fileLocation()); final String content = FileUtils.readFileToString(configFile); final int indexOfSecond = content.indexOf("addedSecond"); final int indexOfFirst = content.indexOf("addedFirst"); assertThat(indexOfSecond, is(not(-1))); assertThat(indexOfFirst, is(not(-1))); assertTrue(indexOfSecond < indexOfFirst); } @Test public void shouldNotAddInvalidPipelineToConfigFile() throws Exception { CruiseConfig cruiseConfig = goConfigDao.load(); int oldsize = cruiseConfig.numberOfPipelines(); PipelineConfig pipelineConfig = PipelineMother.twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("", "ut", "www.spring.com"); try { goConfigDao.addPipeline(pipelineConfig, DEFAULT_GROUP); fail(); } catch (Exception ignored) { } cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.numberOfPipelines(), is(oldsize)); } @Test public void shouldUpdateAgentResourcesToConfigFile() throws Exception { AgentConfig agentConfig = new AgentConfig("uuid", "test", "127.0.0.1", new Resources("java")); goConfigDao.addAgent(agentConfig); Resources newResources = new Resources("firefox"); goConfigDao.updateAgentResources(agentConfig.getUuid(), newResources); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.agents().get(0).getResources(), is(newResources)); } @Test public void shouldUpdateAgentApprovalStatusByUuidToConfigFile() throws Exception { AgentConfig agentConfig = new AgentConfig("uuid", "test", "127.0.0.1", new Resources("java")); goConfigDao.addAgent(agentConfig); goConfigDao.updateAgentApprovalStatus(agentConfig.getUuid(), Boolean.TRUE); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.agents().get(0).isDisabled(), is(true)); } @Test public void shouldRemoveAgentResourcesInConfigFile() throws Exception { AgentConfig agentConfig = new AgentConfig("uuid", "test", "127.0.0.1", new Resources("java, resource1, resource2")); goConfigDao.addAgent(agentConfig); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.agents().get(0).getResources().size(), is(3)); goConfigDao.updateAgentResources(agentConfig.getUuid(), new Resources("java")); cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.agents().get(0).getResources().size(), is(1)); } @Test public void shouldOverwriteConfigContentAfterSave() throws Exception { useConfigString(WITH_3_AGENT_CONFIG); cachedGoConfig.save(CONFIG_WITH_ANT_BUILDER, false); CruiseConfig cruiseConfig = goConfigDao.load(); assertThat(cruiseConfig.jobConfigByName("pipeline1", "mingle", "cardlist", true).tasks().size(), is(1)); } @Test public void shouldNotChangeCurrentConfigIfInvalid() throws Exception { useConfigString(WITH_3_AGENT_CONFIG); CruiseConfig cruiseConfig = goConfigDao.load(); try { cachedGoConfig.save("This is invalid Cruise", false); fail(); } catch (Exception ignored) { } assertCurrentConfigIs(cruiseConfig); } @Test public void shouldNotAllowTypeForArtifactsBecausePolymorphismIsUsedInstead() throws Exception { try { cachedGoConfig.save(INVALID_CONFIG_WITH_TYPE_FOR_ARTIFACT, false); fail(); } catch (Exception e) { assertContains(e.toString(), "'type' is not allowed"); } } @Test public void shouldNotAllowOldXml() throws Exception { try { cachedGoConfig.save(ConfigFileFixture.VERSION_5, false); fail(); } catch (Exception e) { assertThat(e.getMessage(), containsString("Value '5' of attribute 'schemaVersion' of element 'cruise' is not valid")); } } @Test public void shouldLogAnyErrorMessageIncludingTheValidationError() throws Exception { try { cachedGoConfig.save(INVALID_CONFIG_WITH_TYPE_FOR_ARTIFACT, false); fail(); } catch (Exception e) { assertThat(logger.getLog(), containsString( "'type' is not allowed to appear in element 'test'.")); } } @Test public void should_NOT_allowUpdateOf_serverId() throws Exception { useConfigString(ConfigFileFixture.CRUISE); String oldServerId = goConfigDao.load().server().getServerId(); Exception ex = null; try { GoConfigFileHelper.withServerIdImmutability(new Procedure() { public void call() { goConfigDao.updateConfig(new UpdateConfigCommand() { public CruiseConfig update(CruiseConfig cruiseConfig) throws Exception { ReflectionUtil.setField(cruiseConfig.server(), "serverId", "new-value"); return cruiseConfig; } }); } }); fail("should not save with modified serverId"); } catch (Exception e) { ex = e; } assertThat(ex.getMessage(), is("The value of 'serverId' uniquely identifies a Go server instance. This field cannot be modified.")); CruiseConfig config = goConfigDao.load(); assertThat(config.server().getServerId(), is(oldServerId)); } @Test public void shouldNotConfigMultipleTrackingTools() throws Exception { try { useConfigString(INVALID_CONFIG_WITH_MULTIPLE_TRACKINGTOOLS); } catch (Exception e) { assertThat(e.getMessage(), containsString("One of '{materials}' is expected")); } } @Test public void shouldMergeWithLatestConfigWhenConfigUpdatedWithOlderMd5() { configHelper.addMailHost(getMailhost("mailhost.local.old")); final String oldMd5 = goConfigDao.md5OfConfigFile(); configHelper.addMailHost(getMailhost("mailhost.local")); ConfigSaveState configSaveState = goConfigDao.updateConfig(configHelper.addPipelineCommand(oldMd5, "p2", "stage1", "build1")); CruiseConfig updatedConfig = goConfigDao.load(); assertThat(updatedConfig.hasPipelineNamed(new CaseInsensitiveString("p2")), is(true)); assertThat(updatedConfig.mailHost().getHostName(), is("mailhost.local")); assertThat(configSaveState, is(ConfigSaveState.MERGED)); } @Test public void shouldNotUpdatePipelineConfigIfUserDoesNotHaveRequiredPermissionsToDoSo(){ PipelineConfig pipelineConfig = mock(PipelineConfig.class); LocalizedOperationResult result = mock(LocalizedOperationResult.class); PipelineConfigService.SaveCommand saveCommand = mock(PipelineConfigService.SaveCommand.class); when(saveCommand.hasWritePermissions()).thenReturn(false); CachedGoConfig cachedConfigService = mock(CachedGoConfig.class); goConfigDao = new GoConfigDao(cachedConfigService); goConfigDao.updatePipeline(pipelineConfig, result, new Username(new CaseInsensitiveString("user")), saveCommand); verifyZeroInteractions(cachedConfigService); } @Test public void shouldUpdateResultWithErrorCodeWhenPipelineConfigValidationFails(){ Username username = new Username(new CaseInsensitiveString("user")); PipelineConfig pipelineConfig = mock(PipelineConfig.class); LocalizedOperationResult result = mock(LocalizedOperationResult.class); PipelineConfigService.SaveCommand saveCommand = mock(PipelineConfigService.SaveCommand.class); when(saveCommand.hasWritePermissions()).thenReturn(true); CachedGoConfig cachedConfigService = mock(CachedGoConfig.class); doThrow(new ConfigUpdateCheckFailedException()).when(cachedConfigService).writePipelineWithLock(pipelineConfig, saveCommand, username); goConfigDao = new GoConfigDao(cachedConfigService); goConfigDao.updatePipeline(pipelineConfig, result, username, saveCommand); verify(result).unprocessableEntity(Matchers.<Localizable>any()); } @Test public void shouldUpdateValidPipelineConfig(){ PipelineConfig pipelineConfig = mock(PipelineConfig.class); LocalizedOperationResult result = mock(LocalizedOperationResult.class); PipelineConfigService.SaveCommand saveCommand = mock(PipelineConfigService.SaveCommand.class); when(saveCommand.hasWritePermissions()).thenReturn(true); CachedGoConfig cachedConfigService = mock(CachedGoConfig.class); goConfigDao = new GoConfigDao(cachedConfigService); Username currentUser = new Username(new CaseInsensitiveString("user")); goConfigDao.updatePipeline(pipelineConfig, result, currentUser, saveCommand); verifyZeroInteractions(result); verify(cachedConfigService).writePipelineWithLock(pipelineConfig, saveCommand, currentUser); } private void assertCurrentConfigIs(CruiseConfig cruiseConfig) throws Exception { CruiseConfig currentConfig = goConfigDao.load(); assertThat(currentConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline1")).size(), is(cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline1")).size())); } public void useConfigString(String config) throws Exception { configHelper.writeXmlToConfigFile(ConfigMigrator.migrate(config)); } class CheckedTestUpdateCommand implements NoOverwriteUpdateConfigCommand, CheckedUpdateCommand, ConfigAwareUpdate { private final String md5; private final boolean canContinue; private boolean wasUpdated; private CruiseConfig after; CheckedTestUpdateCommand(String md5, boolean canContinue) { this.md5 = md5; this.canContinue = canContinue; } public boolean canContinue(CruiseConfig cruiseConfig) { return canContinue; } public String unmodifiedMd5() { return md5; } public CruiseConfig update(CruiseConfig cruiseConfig) throws Exception { wasUpdated = true; return cruiseConfig; } public void afterUpdate(CruiseConfig cruiseConfig) { after = cruiseConfig; } public CruiseConfig configAfter() { return after; } } private MailHost getMailhost(String hostname) { return new MailHost(hostname, 9999, "user", "password", true, false, "from@local", "admin@local"); } }
/* * Copyright 2018 Paul Hagedorn (Panzer1119) * * 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 de.codemakers.mcfp.util; import de.codemakers.base.logger.Logger; import de.codemakers.base.os.OSUtil; import de.codemakers.base.util.tough.ToughSupplier; import de.codemakers.io.file.AdvancedFile; import java.io.BufferedReader; import java.io.BufferedWriter; import java.util.Base64; import java.util.Objects; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Log { public static boolean LOG_ENABLE = false; public static final Queue<String> ACTIONS = new ConcurrentLinkedQueue<>(); public static final String LOG_FORMAT_STRING = "FILE:\"%s\":OLD:%s:NEW:%s"; public static final String LOG_REGEX_STRING = "FILE:\"(.+)\":OLD:(.*):NEW:(.*)"; public static final Pattern LOG_REGEX_PATTERN = Pattern.compile(LOG_REGEX_STRING); public static AdvancedFile LOG_FILE = null; public static String actionToString(AdvancedFile advancedFile, byte[] data_old, byte[] data_new) { if (advancedFile == null) { return null; } return String.format(LOG_FORMAT_STRING, advancedFile.getAbsolutePath(), data_old == null ? "" : Base64.getEncoder().encodeToString(data_old), data_new == null ? "" : Base64.getEncoder().encodeToString(data_new)); } public static boolean reverseActions(AdvancedFile advancedFile) { if (advancedFile == null) { return false; } try { final BufferedReader bufferedReader = advancedFile.createBufferedReader(); final boolean done = bufferedReader.lines().allMatch(Log::reverseAction); bufferedReader.close(); return done; } catch (Exception ex) { Logger.handleError(ex); return false; } } public static boolean reverseAction(String action) { if (action == null || action.isEmpty()) { return false; } final Matcher matcher = LOG_REGEX_PATTERN.matcher(action); if (!matcher.matches()) { return false; } try { final AdvancedFile advancedFile = new AdvancedFile(matcher.group(1)); final byte[] data_old = (matcher.group(2) == null || matcher.group(2).isEmpty()) ? null : Base64.getDecoder().decode(matcher.group(2)); //final byte[] data_new = (matcher.group(3) == null || matcher.group(3).isEmpty()) ? null : Base64.getDecoder().decode(matcher.group(3)); //Is not needed, since we do not need this, but its good to have this in the log to see the full changes if (data_old == null) { //A file was created, so delete it return advancedFile.delete(); } //Else a file was deleted or changed, so just override it return advancedFile.writeBytes(data_old); } catch (Exception ex) { Logger.handleError(ex); return false; } } public static void addActionIfEnabled(AdvancedFile advancedFile, ToughSupplier<byte[]> data_old, ToughSupplier<byte[]> data_new) { if (LOG_ENABLE) { addAction(advancedFile, data_old.getWithoutException(), data_new.getWithoutException()); } } public static void addAction(AdvancedFile advancedFile, byte[] data_old, byte[] data_new) { final String action = actionToString(advancedFile, data_old, data_new); ACTIONS.add(action); if (LOG_FILE != null) { try { final BufferedWriter bufferedWriter = LOG_FILE.createBufferedWriter(true); bufferedWriter.write(action); bufferedWriter.newLine(); bufferedWriter.flush(); bufferedWriter.close(); } catch (Exception ex) { Logger.handleError(ex); } } } public static void saveActionsToFile(AdvancedFile advancedFile) { Objects.requireNonNull(advancedFile); advancedFile.writeBytesWithoutException(ACTIONS.stream().collect(Collectors.joining(OSUtil.CURRENT_OS_HELPER.getLineSeparator())).getBytes()); } }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.elasticmapreduce.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.elasticmapreduce.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * InstanceResizePolicy JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InstanceResizePolicyJsonUnmarshaller implements Unmarshaller<InstanceResizePolicy, JsonUnmarshallerContext> { public InstanceResizePolicy unmarshall(JsonUnmarshallerContext context) throws Exception { InstanceResizePolicy instanceResizePolicy = new InstanceResizePolicy(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("InstancesToTerminate", targetDepth)) { context.nextToken(); instanceResizePolicy.setInstancesToTerminate(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)) .unmarshall(context)); } if (context.testExpression("InstancesToProtect", targetDepth)) { context.nextToken(); instanceResizePolicy.setInstancesToProtect(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)) .unmarshall(context)); } if (context.testExpression("InstanceTerminationTimeout", targetDepth)) { context.nextToken(); instanceResizePolicy.setInstanceTerminationTimeout(context.getUnmarshaller(Integer.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return instanceResizePolicy; } private static InstanceResizePolicyJsonUnmarshaller instance; public static InstanceResizePolicyJsonUnmarshaller getInstance() { if (instance == null) instance = new InstanceResizePolicyJsonUnmarshaller(); return instance; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sysds.test.functions.io; import org.apache.sysds.parser.LanguageException; import org.apache.sysds.test.AutomatedTestBase; import org.apache.sysds.test.TestConfiguration; import org.junit.Test; /** * <p> * <b>Positive tests:</b> * </p> * <ul> * <li>text format</li> * <li>binary format</li> * </ul> * <p> * <b>Negative tests:</b> * </p> * <ul> * </ul> * * */ public class IOTest3 extends AutomatedTestBase { private final static String TEST_DIR = "functions/io/"; private final static String TEST_CLASS_DIR = TEST_DIR + IOTest3.class.getSimpleName() + "/"; private final static String TEST_NAME = "SimpleTest"; @Override public void setUp() { // positive tests // negative tests addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, "IOTest3", new String[] {"a"})); } @Test public void testSimple() { int rows = 10; int cols = 10; TestConfiguration config = getTestConfiguration(TEST_NAME); config.addVariable("rows", rows); config.addVariable("cols", cols); config.addVariable("format", "text"); loadTestConfiguration(config); double[][] a = getRandomMatrix(rows, cols, -1, 1, 0.5, -1); writeInputMatrix("a", a); writeExpectedMatrix("a", a); runTest(true, LanguageException.class); } }
/* * 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. * * Other licenses: * ----------------------------------------------------------------------------- * Commercial licenses for this work are available. These replace the above * ASL 2.0 and offer limited warranties, support, maintenance, and commercial * database integrations. * * For more information, please visit: http://www.jooq.org/licenses * * * * * * * * * * * * * * * * */ package org.jooq.impl; import org.jooq.Context; import org.jooq.DataType; import org.jooq.QueryPart; final class SQLField<T> extends AbstractField<T> { /** * Generated UID */ private static final long serialVersionUID = 6937002867156868761L; private final QueryPart delegate; SQLField(DataType<T> type, QueryPart delegate) { super(DSL.name(delegate.toString()), type); this.delegate = delegate; } // ------------------------------------------------------------------------ // Field API // ------------------------------------------------------------------------ @Override public final void accept(Context<?> ctx) { ctx.visit(delegate); } }
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.security.oauth2.resource.servlet; import java.net.MalformedURLException; import java.net.URL; import java.time.Instant; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.nimbusds.jose.JWSAlgorithm; import jakarta.servlet.Filter; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.assertj.AssertableWebApplicationContext; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtClaimValidator; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtIssuerValidator; import org.springframework.security.oauth2.jwt.JwtTimestampValidator; import org.springframework.security.oauth2.jwt.SupplierJwtDecoder; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * Tests for {@link OAuth2ResourceServerAutoConfiguration}. * * @author Madhura Bhave * @author Artsiom Yudovin * @author HaiTao Zhang * @author Mushtaq Ahmed */ class OAuth2ResourceServerAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) .withUserConfiguration(TestConfig.class); private MockWebServer server; private static final String JWK_SET = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"use\":\"sig\"," + "\"kid\":\"one\",\"n\":\"oXJ8OyOv_eRnce4akdanR4KYRfnC2zLV4uYNQpcFn6oHL0dj7D6kxQmsXoYgJV8ZVDn71KGm" + "uLvolxsDncc2UrhyMBY6DVQVgMSVYaPCTgW76iYEKGgzTEw5IBRQL9w3SRJWd3VJTZZQjkXef48Ocz06PGF3lhbz4t5UEZtd" + "F4rIe7u-977QwHuh7yRPBQ3sII-cVoOUMgaXB9SHcGF2iZCtPzL_IffDUcfhLQteGebhW8A6eUHgpD5A1PQ-JCw_G7UOzZAj" + "jDjtNM2eqm8j-Ms_gqnm4MiCZ4E-9pDN77CAAPVN7kuX6ejs9KBXpk01z48i9fORYk9u7rAkh1HuQw\"}]}"; @AfterEach void cleanup() throws Exception { if (this.server != null) { this.server.shutdown(); } } @Test void autoConfigurationShouldConfigureResourceServer() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); assertThat(getBearerTokenFilter(context)).isNotNull(); }); } @Test void autoConfigurationShouldMatchDefaultJwsAlgorithm() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); Object processor = ReflectionTestUtils.getField(jwtDecoder, "jwtProcessor"); Object keySelector = ReflectionTestUtils.getField(processor, "jwsKeySelector"); assertThat(keySelector).hasFieldOrPropertyWithValue("jwsAlgs", Collections.singleton(JWSAlgorithm.RS256)); }); } @Test void autoConfigurationShouldConfigureResourceServerWithJwsAlgorithm() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384") .run((context) -> { JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); Object processor = ReflectionTestUtils.getField(jwtDecoder, "jwtProcessor"); Object keySelector = ReflectionTestUtils.getField(processor, "jwsKeySelector"); assertThat(keySelector).hasFieldOrPropertyWithValue("jwsAlgs", Collections.singleton(JWSAlgorithm.RS384)); assertThat(getBearerTokenFilter(context)).isNotNull(); }); } @Test @SuppressWarnings("unchecked") void autoConfigurationShouldConfigureResourceServerUsingOidcIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String path = "test"; String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { assertThat(context).hasSingleBean(SupplierJwtDecoder.class); assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); Supplier<JwtDecoder> jwtDecoderSupplier = (Supplier<JwtDecoder>) ReflectionTestUtils .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); jwtDecoderSupplier.get(); }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(2); } @Test @SuppressWarnings("unchecked") void autoConfigurationShouldConfigureResourceServerUsingOidcRfc8414IssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String path = "test"; String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 1); this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { assertThat(context).hasSingleBean(SupplierJwtDecoder.class); assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); Supplier<JwtDecoder> jwtDecoderSupplier = (Supplier<JwtDecoder>) ReflectionTestUtils .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); jwtDecoderSupplier.get(); }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(3); } @Test @SuppressWarnings("unchecked") void autoConfigurationShouldConfigureResourceServerUsingOAuthIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String path = "test"; String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 2); this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { assertThat(context).hasSingleBean(SupplierJwtDecoder.class); assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); Supplier<JwtDecoder> jwtDecoderSupplier = (Supplier<JwtDecoder>) ReflectionTestUtils .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); jwtDecoderSupplier.get(); }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(4); } @Test void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); assertThat(getBearerTokenFilter(context)).isNotNull(); }); } @Test void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") .run((context) -> assertThat(context).hasFailed().getFailure() .hasMessageContaining("class path resource [does-not-exist]") .hasMessageContaining("Public key location does not exist")); } @Test void autoConfigurationShouldFailIfAlgorithmIsInvalid() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", "spring.security.oauth2.resourceserver.jwt.jws-algorithm=NOT_VALID") .run((context) -> assertThat(context).hasFailed().getFailure() .hasMessageContaining("signatureAlgorithm cannot be null")); } @Test void autoConfigurationWhenSetUriKeyLocationAndIssuerUriPresentShouldUseSetUri() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=https://issuer-uri.com", "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); assertThat(getBearerTokenFilter(context)).isNotNull(); assertThat(context.containsBean("jwtDecoderByJwkKeySetUri")).isTrue(); assertThat(context.containsBean("jwtDecoderByIssuerUri")).isFalse(); }); } @Test void autoConfigurationWhenKeyLocationAndIssuerUriPresentShouldUseIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + this.server.getPort(), "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); assertThat(getBearerTokenFilter(context)).isNotNull(); assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); }); } @Test void autoConfigurationWhenJwkSetUriNullShouldNotFail() { this.contextRunner.run((context) -> assertThat(getBearerTokenFilter(context)).isNull()); } @Test void jwtDecoderByJwkSetUriIsConditionalOnMissingBean() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test void jwtDecoderByOidcIssuerUriIsConditionalOnMissingBean() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") .withUserConfiguration(JwtDecoderConfig.class) .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test void autoConfigurationShouldBeConditionalOnResourceServerClass() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)).run((context) -> { assertThat(context).doesNotHaveBean(OAuth2ResourceServerAutoConfiguration.class); assertThat(getBearerTokenFilter(context)).isNull(); }); } @Test void autoConfigurationForJwtShouldBeConditionalOnJwtDecoderClass() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) .withClassLoader(new FilteredClassLoader(JwtDecoder.class)).run((context) -> { assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); assertThat(getBearerTokenFilter(context)).isNull(); }); } @Test void jwtSecurityFilterShouldBeConditionalOnSecurityFilterChainClass() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)).run((context) -> { assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); assertThat(getBearerTokenFilter(context)).isNull(); }); } @Test void opaqueTokenSecurityFilterShouldBeConditionalOnSecurityFilterChainClass() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)).run((context) -> { assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); assertThat(getBearerTokenFilter(context)).isNull(); }); } @Test void autoConfigurationWhenJwkSetUriAndIntrospectionUriAvailable() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") .run((context) -> { assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); assertThat(context).hasSingleBean(JwtDecoder.class); assertThat(getBearerTokenFilter(context)) .extracting("authenticationManagerResolver.arg$1.providers").asList() .hasAtLeastOneElementOfType(JwtAuthenticationProvider.class); }); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldConfigureIntrospectionClient() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") .run((context) -> { assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); assertThat(getBearerTokenFilter(context)).isNotNull(); }); } @Test void opaqueTokenIntrospectorIsConditionalOnMissingBean() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com") .withUserConfiguration(OpaqueTokenIntrospectorConfig.class) .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldBeConditionalOnClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) .withPropertyValues( "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") .run((context) -> assertThat(context).doesNotHaveBean(OpaqueTokenIntrospector.class)); } @SuppressWarnings("unchecked") @Test void autoConfigurationShouldConfigureResourceServerUsingJwkSetUriAndIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String path = "test"; String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path) .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); DelegatingOAuth2TokenValidator<Jwt> jwtValidator = (DelegatingOAuth2TokenValidator<Jwt>) ReflectionTestUtils .getField(jwtDecoder, "jwtValidator"); Collection<OAuth2TokenValidator<Jwt>> tokenValidators = (Collection<OAuth2TokenValidator<Jwt>>) ReflectionTestUtils .getField(jwtValidator, "tokenValidators"); assertThat(tokenValidators).hasAtLeastOneElementOfType(JwtIssuerValidator.class); }); } @SuppressWarnings("unchecked") @Test void autoConfigurationShouldNotConfigureIssuerUriAndAudienceJwtValidatorIfPropertyNotConfigured() throws Exception { this.server = new MockWebServer(); this.server.start(); String path = "test"; String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); DelegatingOAuth2TokenValidator<Jwt> jwtValidator = (DelegatingOAuth2TokenValidator<Jwt>) ReflectionTestUtils .getField(jwtDecoder, "jwtValidator"); Collection<OAuth2TokenValidator<Jwt>> tokenValidators = (Collection<OAuth2TokenValidator<Jwt>>) ReflectionTestUtils .getField(jwtValidator, "tokenValidators"); assertThat(tokenValidators).hasExactlyElementsOfTypes(JwtTimestampValidator.class); assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtClaimValidator.class); assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtIssuerValidator.class); }); } @Test void autoConfigurationShouldConfigureAudienceAndIssuerJwtValidatorIfPropertyProvided() throws Exception { this.server = new MockWebServer(); this.server.start(); String path = "test"; String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); String issuerUri = "http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path; this.contextRunner.withPropertyValues( "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); validate(issuerUri, jwtDecoder); }); } @SuppressWarnings("unchecked") @Test void autoConfigurationShouldConfigureAudienceValidatorIfPropertyProvidedAndIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String path = "test"; String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); String issuerUri = "http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path; this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") .run((context) -> { SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); Supplier<JwtDecoder> jwtDecoderSupplier = (Supplier<JwtDecoder>) ReflectionTestUtils .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); JwtDecoder jwtDecoder = jwtDecoderSupplier.get(); validate(issuerUri, jwtDecoder); }); } @SuppressWarnings("unchecked") private void validate(String issuerUri, JwtDecoder jwtDecoder) throws MalformedURLException { DelegatingOAuth2TokenValidator<Jwt> jwtValidator = (DelegatingOAuth2TokenValidator<Jwt>) ReflectionTestUtils .getField(jwtDecoder, "jwtValidator"); Jwt.Builder builder = jwt().claim("aud", Collections.singletonList("https://test-audience.com")); if (issuerUri != null) { builder.claim("iss", new URL(issuerUri)); } Jwt jwt = builder.build(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); Collection<OAuth2TokenValidator<Jwt>> delegates = (Collection<OAuth2TokenValidator<Jwt>>) ReflectionTestUtils .getField(jwtValidator, "tokenValidators"); validateDelegates(issuerUri, delegates); } @SuppressWarnings("unchecked") private void validateDelegates(String issuerUri, Collection<OAuth2TokenValidator<Jwt>> delegates) { assertThat(delegates).hasAtLeastOneElementOfType(JwtClaimValidator.class); OAuth2TokenValidator<Jwt> delegatingValidator = delegates.stream() .filter((v) -> v instanceof DelegatingOAuth2TokenValidator).findFirst().get(); Collection<OAuth2TokenValidator<Jwt>> nestedDelegates = (Collection<OAuth2TokenValidator<Jwt>>) ReflectionTestUtils .getField(delegatingValidator, "tokenValidators"); if (issuerUri != null) { assertThat(nestedDelegates).hasAtLeastOneElementOfType(JwtIssuerValidator.class); } } @Test void autoConfigurationShouldConfigureAudienceValidatorIfPropertyProvidedAndPublicKey() throws Exception { this.server = new MockWebServer(); this.server.start(); String path = "test"; String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner.withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,http://test-audience1.com") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); validate(null, jwtDecoder); }); } @SuppressWarnings("unchecked") @Test void audienceValidatorWhenAudienceInvalid() throws Exception { this.server = new MockWebServer(); this.server.start(); String path = "test"; String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); String issuerUri = "http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path; this.contextRunner.withPropertyValues( "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") .run((context) -> { assertThat(context).hasSingleBean(JwtDecoder.class); JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); DelegatingOAuth2TokenValidator<Jwt> jwtValidator = (DelegatingOAuth2TokenValidator<Jwt>) ReflectionTestUtils .getField(jwtDecoder, "jwtValidator"); Jwt jwt = jwt().claim("iss", new URL(issuerUri)) .claim("aud", Collections.singletonList("https://other-audience.com")).build(); assertThat(jwtValidator.validate(jwt).hasErrors()).isTrue(); }); } @Test void jwtSecurityConfigurerBacksOffWhenSecurityFilterChainBeanIsPresent() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class, TestSecurityFilterChainConfig.class) .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); } @Test void opaqueTokenSecurityConfigurerBacksOffWhenSecurityFilterChainBeanIsPresent() { this.contextRunner.withUserConfiguration(TestSecurityFilterChainConfig.class) .withPropertyValues( "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); } private Filter getBearerTokenFilter(AssertableWebApplicationContext context) { FilterChainProxy filterChain = (FilterChainProxy) context.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); List<SecurityFilterChain> filterChains = filterChain.getFilterChains(); List<Filter> filters = filterChains.get(0).getFilters(); return filters.stream().filter((f) -> f instanceof BearerTokenAuthenticationFilter).findFirst().orElse(null); } private String cleanIssuerPath(String issuer) { if (issuer.endsWith("/")) { return issuer.substring(0, issuer.length() - 1); } return issuer; } private void setupMockResponse(String issuer) throws JsonProcessingException { MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); this.server.enqueue( new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(JWK_SET)); } private void setupMockResponsesWithErrors(String issuer, int errorResponseCount) throws JsonProcessingException { for (int i = 0; i < errorResponseCount; i++) { MockResponse emptyResponse = new MockResponse().setResponseCode(HttpStatus.NOT_FOUND.value()); this.server.enqueue(emptyResponse); } setupMockResponse(issuer); } private Map<String, Object> getResponse(String issuer) { Map<String, Object> response = new HashMap<>(); response.put("authorization_endpoint", "https://example.com/o/oauth2/v2/auth"); response.put("claims_supported", Collections.emptyList()); response.put("code_challenge_methods_supported", Collections.emptyList()); response.put("id_token_signing_alg_values_supported", Collections.emptyList()); response.put("issuer", issuer); response.put("jwks_uri", issuer + "/.well-known/jwks.json"); response.put("response_types_supported", Collections.emptyList()); response.put("revocation_endpoint", "https://example.com/o/oauth2/revoke"); response.put("scopes_supported", Collections.singletonList("openid")); response.put("subject_types_supported", Collections.singletonList("public")); response.put("grant_types_supported", Collections.singletonList("authorization_code")); response.put("token_endpoint", "https://example.com/oauth2/v4/token"); response.put("token_endpoint_auth_methods_supported", Collections.singletonList("client_secret_basic")); response.put("userinfo_endpoint", "https://example.com/oauth2/v3/userinfo"); return response; } static Jwt.Builder jwt() { // @formatter:off return Jwt.withTokenValue("token") .header("alg", "none") .expiresAt(Instant.MAX) .issuedAt(Instant.MIN) .issuer("https://issuer.example.org") .jti("jti") .notBefore(Instant.MIN) .subject("mock-test-subject"); // @formatter:on } @Configuration(proxyBeanMethods = false) @EnableWebSecurity static class TestConfig { } @Configuration(proxyBeanMethods = false) @EnableWebSecurity static class JwtDecoderConfig { @Bean JwtDecoder decoder() { return mock(JwtDecoder.class); } } @Configuration(proxyBeanMethods = false) @EnableWebSecurity static class OpaqueTokenIntrospectorConfig { @Bean OpaqueTokenIntrospector decoder() { return mock(OpaqueTokenIntrospector.class); } } @Configuration(proxyBeanMethods = false) @EnableWebSecurity static class TestSecurityFilterChainConfig { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { return http.antMatcher("/**").authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) .build(); } } }
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <luck@lucko.me> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lucko.luckperms.common.storage.implementation.mongodb; import com.google.common.base.Strings; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientURI; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.ReplaceOptions; import me.lucko.luckperms.common.actionlog.Log; import me.lucko.luckperms.common.actionlog.LoggedAction; import me.lucko.luckperms.common.bulkupdate.BulkUpdate; import me.lucko.luckperms.common.bulkupdate.comparison.Constraint; import me.lucko.luckperms.common.context.contextset.MutableContextSetImpl; import me.lucko.luckperms.common.model.Group; import me.lucko.luckperms.common.model.Track; import me.lucko.luckperms.common.model.User; import me.lucko.luckperms.common.model.manager.group.GroupManager; import me.lucko.luckperms.common.model.manager.track.TrackManager; import me.lucko.luckperms.common.node.factory.NodeBuilders; import me.lucko.luckperms.common.node.model.HeldNodeImpl; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.storage.implementation.StorageImplementation; import me.lucko.luckperms.common.storage.misc.PlayerSaveResultImpl; import me.lucko.luckperms.common.storage.misc.StorageCredentials; import net.luckperms.api.actionlog.Action; import net.luckperms.api.context.Context; import net.luckperms.api.context.ContextSet; import net.luckperms.api.context.DefaultContextKeys; import net.luckperms.api.context.MutableContextSet; import net.luckperms.api.model.PlayerSaveResult; import net.luckperms.api.model.data.DataType; import net.luckperms.api.node.HeldNode; import net.luckperms.api.node.Node; import net.luckperms.api.node.NodeBuilder; import org.bson.Document; import java.time.Instant; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; public class MongoStorage implements StorageImplementation { private final LuckPermsPlugin plugin; private final StorageCredentials configuration; private MongoClient mongoClient; private MongoDatabase database; private final String prefix; private final String connectionUri; public MongoStorage(LuckPermsPlugin plugin, StorageCredentials configuration, String prefix, String connectionUri) { this.plugin = plugin; this.configuration = configuration; this.prefix = prefix; this.connectionUri = connectionUri; } @Override public LuckPermsPlugin getPlugin() { return this.plugin; } @Override public String getImplementationName() { return "MongoDB"; } @Override public void init() { if (!Strings.isNullOrEmpty(this.connectionUri)) { this.mongoClient = new MongoClient(new MongoClientURI(this.connectionUri)); } else { MongoCredential credential = null; if (!Strings.isNullOrEmpty(this.configuration.getUsername())) { credential = MongoCredential.createCredential( this.configuration.getUsername(), this.configuration.getDatabase(), Strings.isNullOrEmpty(this.configuration.getPassword()) ? null : this.configuration.getPassword().toCharArray() ); } String[] addressSplit = this.configuration.getAddress().split(":"); String host = addressSplit[0]; int port = addressSplit.length > 1 ? Integer.parseInt(addressSplit[1]) : 27017; ServerAddress address = new ServerAddress(host, port); if (credential == null) { this.mongoClient = new MongoClient(address); } else { this.mongoClient = new MongoClient(address, credential, MongoClientOptions.builder().build()); } } this.database = this.mongoClient.getDatabase(this.configuration.getDatabase()); } @Override public void shutdown() { if (this.mongoClient != null) { this.mongoClient.close(); } } @Override public Map<String, String> getMeta() { Map<String, String> ret = new LinkedHashMap<>(); boolean success = true; long start = System.currentTimeMillis(); try { this.database.runCommand(new Document("ping", 1)); } catch (Exception e) { success = false; } long duration = System.currentTimeMillis() - start; if (success) { ret.put("Ping", "&a" + duration + "ms"); ret.put("Connected", "true"); } else { ret.put("Connected", "false"); } return ret; } @Override public void logAction(Action entry) { MongoCollection<Document> c = this.database.getCollection(this.prefix + "action"); Document doc = new Document() .append("timestamp", entry.getTimestamp().getEpochSecond()) .append("source", new Document() .append("uniqueId", entry.getSource().getUniqueId()) .append("name", entry.getSource().getName()) ); Document target = new Document() .append("type", entry.getTarget().getType().name()) .append("name", entry.getTarget().getName()); if (entry.getTarget().getUniqueId().isPresent()) { target.append("uniqueId", entry.getTarget().getUniqueId().get()); } doc.append("target", target); doc.append("description", entry.getDescription()); c.insertOne(doc); } @Override public Log getLog() { Log.Builder log = Log.builder(); MongoCollection<Document> c = this.database.getCollection(this.prefix + "action"); try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) { Document d = cursor.next(); if (d.containsKey("source")) { // new format Document source = d.get("source", Document.class); Document target = d.get("target", Document.class); UUID targetUniqueId = null; if (target.containsKey("uniqueId")) { targetUniqueId = target.get("uniqueId", UUID.class); } LoggedAction e = LoggedAction.build() .timestamp(Instant.ofEpochSecond(d.getLong("timestamp"))) .source(source.get("uniqueId", UUID.class)) .sourceName(source.getString("name")) .targetType(LoggedAction.parseType(target.getString("type"))) .target(targetUniqueId) .targetName(target.getString("name")) .description(d.getString("description")) .build(); log.add(e); } else { // old format UUID actedUuid = null; if (d.containsKey("acted")) { actedUuid = d.get("acted", UUID.class); } LoggedAction e = LoggedAction.build() .timestamp(Instant.ofEpochSecond(d.getLong("timestamp"))) .source(d.get("actor", UUID.class)) .sourceName(d.getString("actorName")) .targetType(LoggedAction.parseTypeCharacter(d.getString("type").charAt(0))) .target(actedUuid) .targetName(d.getString("actedName")) .description(d.getString("action")) .build(); log.add(e); } } } return log.build(); } @Override public void applyBulkUpdate(BulkUpdate bulkUpdate) { if (bulkUpdate.getDataType().isIncludingUsers()) { MongoCollection<Document> c = this.database.getCollection(this.prefix + "users"); try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) { Document d = cursor.next(); UUID uuid = d.get("_id", UUID.class); Set<Node> nodes = new HashSet<>(nodesFromDoc(d)); Set<Node> results = nodes.stream() .map(bulkUpdate::apply) .filter(Objects::nonNull) .collect(Collectors.toSet()); if (!nodes.equals(results)) { List<Document> newNodes = results.stream() .map(MongoStorage::nodeToDoc) .collect(Collectors.toList()); d.append("permissions", newNodes).remove("perms"); c.replaceOne(new Document("_id", uuid), d); } } } } if (bulkUpdate.getDataType().isIncludingGroups()) { MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups"); try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) { Document d = cursor.next(); String holder = d.getString("_id"); Set<Node> nodes = new HashSet<>(nodesFromDoc(d)); Set<Node> results = nodes.stream() .map(bulkUpdate::apply) .filter(Objects::nonNull) .collect(Collectors.toSet()); if (!nodes.equals(results)) { List<Document> newNodes = results.stream() .map(MongoStorage::nodeToDoc) .collect(Collectors.toList()); d.append("permissions", newNodes).remove("perms"); c.replaceOne(new Document("_id", holder), d); } } } } } @Override public User loadUser(UUID uniqueId, String username) { User user = this.plugin.getUserManager().getOrMake(uniqueId, username); user.getIoLock().lock(); try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "users"); try (MongoCursor<Document> cursor = c.find(new Document("_id", user.getUniqueId())).iterator()) { if (cursor.hasNext()) { // User exists, let's load. Document d = cursor.next(); String name = d.getString("name"); user.getPrimaryGroup().setStoredValue(d.getString("primaryGroup")); user.setNodes(DataType.NORMAL, nodesFromDoc(d)); user.setUsername(name, true); boolean save = this.plugin.getUserManager().giveDefaultIfNeeded(user, false); if (user.getUsername().isPresent() && (name == null || !user.getUsername().get().equalsIgnoreCase(name))) { save = true; } if (save | user.auditTemporaryNodes()) { c.replaceOne(new Document("_id", user.getUniqueId()), userToDoc(user)); } } else { if (this.plugin.getUserManager().shouldSave(user)) { user.clearNodes(DataType.NORMAL, null, true); user.getPrimaryGroup().setStoredValue(null); this.plugin.getUserManager().giveDefaultIfNeeded(user, false); } } } } finally { user.getIoLock().unlock(); } return user; } @Override public void saveUser(User user) { user.getIoLock().lock(); try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "users"); if (!this.plugin.getUserManager().shouldSave(user)) { c.deleteOne(new Document("_id", user.getUniqueId())); } else { c.replaceOne(new Document("_id", user.getUniqueId()), userToDoc(user), new ReplaceOptions().upsert(true)); } } finally { user.getIoLock().unlock(); } } @Override public Set<UUID> getUniqueUsers() { Set<UUID> uuids = new HashSet<>(); MongoCollection<Document> c = this.database.getCollection(this.prefix + "users"); try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) { Document d = cursor.next(); uuids.add(d.get("_id", UUID.class)); } } return uuids; } @Override public List<HeldNode<UUID>> getUsersWithPermission(Constraint constraint) { List<HeldNode<UUID>> held = new ArrayList<>(); MongoCollection<Document> c = this.database.getCollection(this.prefix + "users"); try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) { Document d = cursor.next(); UUID holder = d.get("_id", UUID.class); Set<Node> nodes = new HashSet<>(nodesFromDoc(d)); for (Node e : nodes) { if (!constraint.eval(e.getKey())) { continue; } held.add(HeldNodeImpl.of(holder, e)); } } } return held; } @Override public Group createAndLoadGroup(String name) { Group group = this.plugin.getGroupManager().getOrMake(name); group.getIoLock().lock(); try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups"); try (MongoCursor<Document> cursor = c.find(new Document("_id", group.getName())).iterator()) { if (cursor.hasNext()) { Document d = cursor.next(); group.setNodes(DataType.NORMAL, nodesFromDoc(d)); } else { c.insertOne(groupToDoc(group)); } } } finally { group.getIoLock().unlock(); } return group; } @Override public Optional<Group> loadGroup(String name) { Group group = this.plugin.getGroupManager().getIfLoaded(name); if (group != null) { group.getIoLock().lock(); } try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups"); try (MongoCursor<Document> cursor = c.find(new Document("_id", name)).iterator()) { if (!cursor.hasNext()) { return Optional.empty(); } if (group == null) { group = this.plugin.getGroupManager().getOrMake(name); group.getIoLock().lock(); } Document d = cursor.next(); group.setNodes(DataType.NORMAL, nodesFromDoc(d)); } } finally { if (group != null) { group.getIoLock().unlock(); } } return Optional.of(group); } @Override public void loadAllGroups() { List<String> groups = new ArrayList<>(); MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups"); try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) { String name = cursor.next().getString("_id"); groups.add(name); } } boolean success = true; for (String g : groups) { try { loadGroup(g); } catch (Exception e) { e.printStackTrace(); success = false; } } if (!success) { throw new RuntimeException("Exception occurred whilst loading a group"); } GroupManager<?> gm = this.plugin.getGroupManager(); gm.getAll().values().stream() .map(Group::getName) .filter(g -> !groups.contains(g)) .forEach(gm::unload); } @Override public void saveGroup(Group group) { group.getIoLock().lock(); try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups"); c.replaceOne(new Document("_id", group.getName()), groupToDoc(group), new ReplaceOptions().upsert(true)); } finally { group.getIoLock().unlock(); } } @Override public void deleteGroup(Group group) { group.getIoLock().lock(); try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups"); c.deleteOne(new Document("_id", group.getName())); } finally { group.getIoLock().unlock(); } } @Override public List<HeldNode<String>> getGroupsWithPermission(Constraint constraint) { List<HeldNode<String>> held = new ArrayList<>(); MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups"); try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) { Document d = cursor.next(); String holder = d.getString("_id"); Set<Node> nodes = new HashSet<>(nodesFromDoc(d)); for (Node e : nodes) { if (!constraint.eval(e.getKey())) { continue; } held.add(HeldNodeImpl.of(holder, e)); } } } return held; } @Override public Track createAndLoadTrack(String name) { Track track = this.plugin.getTrackManager().getOrMake(name); track.getIoLock().lock(); try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "tracks"); try (MongoCursor<Document> cursor = c.find(new Document("_id", track.getName())).iterator()) { if (!cursor.hasNext()) { c.insertOne(trackToDoc(track)); } else { Document d = cursor.next(); //noinspection unchecked track.setGroups((List<String>) d.get("groups")); } } } finally { track.getIoLock().unlock(); } return track; } @Override public Optional<Track> loadTrack(String name) { Track track = this.plugin.getTrackManager().getIfLoaded(name); if (track != null) { track.getIoLock().lock(); } try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "tracks"); try (MongoCursor<Document> cursor = c.find(new Document("_id", name)).iterator()) { if (!cursor.hasNext()) { return Optional.empty(); } if (track == null) { track = this.plugin.getTrackManager().getOrMake(name); track.getIoLock().lock(); } Document d = cursor.next(); //noinspection unchecked track.setGroups((List<String>) d.get("groups")); } } finally { if (track != null) { track.getIoLock().unlock(); } } return Optional.of(track); } @Override public void loadAllTracks() { List<String> tracks = new ArrayList<>(); MongoCollection<Document> c = this.database.getCollection(this.prefix + "tracks"); try (MongoCursor<Document> cursor = c.find().iterator()) { while (cursor.hasNext()) { String name = cursor.next().getString("_id"); tracks.add(name); } } boolean success = true; for (String t : tracks) { try { loadTrack(t); } catch (Exception e) { e.printStackTrace(); success = false; } } if (!success) { throw new RuntimeException("Exception occurred whilst loading a track"); } TrackManager<?> tm = this.plugin.getTrackManager(); tm.getAll().values().stream() .map(Track::getName) .filter(t -> !tracks.contains(t)) .forEach(tm::unload); } @Override public void saveTrack(Track track) { track.getIoLock().lock(); try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "tracks"); c.replaceOne(new Document("_id", track.getName()), trackToDoc(track)); } finally { track.getIoLock().unlock(); } } @Override public void deleteTrack(Track track) { track.getIoLock().lock(); try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "tracks"); c.deleteOne(new Document("_id", track.getName())); } finally { track.getIoLock().unlock(); } } @Override public PlayerSaveResult savePlayerData(UUID uniqueId, String username) { username = username.toLowerCase(); MongoCollection<Document> c = this.database.getCollection(this.prefix + "uuid"); // find any existing mapping String oldUsername = getPlayerName(uniqueId); // do the insert if (!username.equalsIgnoreCase(oldUsername)) { c.replaceOne(new Document("_id", uniqueId), new Document("_id", uniqueId).append("name", username), new ReplaceOptions().upsert(true)); } PlayerSaveResultImpl result = PlayerSaveResultImpl.determineBaseResult(username, oldUsername); Set<UUID> conflicting = new HashSet<>(); try (MongoCursor<Document> cursor = c.find(new Document("name", username)).iterator()) { if (cursor.hasNext()) { conflicting.add(cursor.next().get("_id", UUID.class)); } } conflicting.remove(uniqueId); if (!conflicting.isEmpty()) { // remove the mappings for conflicting uuids c.deleteMany(Filters.and(conflicting.stream().map(u -> Filters.eq("_id", u)).collect(Collectors.toList()))); result = result.withOtherUuidsPresent(conflicting); } return result; } @Override public UUID getPlayerUniqueId(String username) { MongoCollection<Document> c = this.database.getCollection(this.prefix + "uuid"); Document doc = c.find(new Document("name", username.toLowerCase())).first(); if (doc != null) { return doc.get("_id", UUID.class); } return null; } @Override public String getPlayerName(UUID uniqueId) { MongoCollection<Document> c = this.database.getCollection(this.prefix + "uuid"); Document doc = c.find(new Document("_id", uniqueId)).first(); if (doc != null) { return doc.get("name", String.class); } return null; } private static Document userToDoc(User user) { List<Document> nodes = user.normalData().immutable().values().stream() .map(MongoStorage::nodeToDoc) .collect(Collectors.toList()); return new Document("_id", user.getUniqueId()) .append("name", user.getUsername().orElse("null")) .append("primaryGroup", user.getPrimaryGroup().getStoredValue().orElse(GroupManager.DEFAULT_GROUP_NAME)) .append("permissions", nodes); } private static List<Node> nodesFromDoc(Document document) { List<Node> nodes = new ArrayList<>(); if (document.containsKey("permissions") && document.get("permissions") instanceof List) { //noinspection unchecked List<Document> permsList = (List<Document>) document.get("permissions"); for (Document d : permsList) { nodes.add(nodeFromDoc(d)); } } return nodes; } private static Document groupToDoc(Group group) { List<Document> nodes = group.normalData().immutable().values().stream() .map(MongoStorage::nodeToDoc) .collect(Collectors.toList()); return new Document("_id", group.getName()).append("permissions", nodes); } private static Document trackToDoc(Track track) { return new Document("_id", track.getName()).append("groups", track.getGroups()); } private static Document nodeToDoc(Node node) { Document document = new Document(); document.append("key", node.getKey()); document.append("value", node.getValue()); Instant expiry = node.getExpiry(); if (expiry != null) { document.append("expiry", expiry.getEpochSecond()); } if (!node.getContexts().isEmpty()) { document.append("context", contextSetToDocs(node.getContexts())); } return document; } private static Node nodeFromDoc(Document document) { String key = document.containsKey("permission") ? document.getString("permission") : document.getString("key"); NodeBuilder<?, ?> builder = NodeBuilders.determineMostApplicable(key) .value(document.getBoolean("value", true)); if (document.containsKey("server")) { builder.withContext(DefaultContextKeys.SERVER_KEY, document.getString("server")); } if (document.containsKey("world")) { builder.withContext(DefaultContextKeys.WORLD_KEY, document.getString("world")); } if (document.containsKey("expiry")) { builder.expiry(document.getLong("expiry")); } if (document.containsKey("context") && document.get("context") instanceof List) { //noinspection unchecked List<Document> contexts = (List<Document>) document.get("context"); builder.withContext(docsToContextSet(contexts)); } return builder.build(); } private static List<Document> contextSetToDocs(ContextSet contextSet) { List<Document> contexts = new ArrayList<>(contextSet.size()); for (Context e : contextSet) { contexts.add(new Document().append("key", e.getKey()).append("value", e.getValue())); } return contexts; } private static MutableContextSet docsToContextSet(List<Document> documents) { MutableContextSet map = new MutableContextSetImpl(); for (Document doc : documents) { map.add(doc.getString("key"), doc.getString("value")); } return map; } }
package jtrrntzip; import java.util.EnumSet; import java.util.List; import java.util.Set; public class TorrentZipCheck { private TorrentZipCheck() { throw new IllegalStateException("Utility class"); } public static Set<TrrntZipStatus> checkZipFiles(final List<ZippedFile> zippedFiles, final LogCallback StatusLogCallBack) { final EnumSet<TrrntZipStatus> tzStatus = EnumSet.noneOf(TrrntZipStatus.class); // ***************************** RULE 1 ************************************* // Directory separator should be a '/' a '\' is invalid and should be replaced with '/' // // check if any '\' = 92 need converted to '/' = 47 // this needs done before the sort, so that the sort is correct. // return BadDirectorySeparator if errors found. var error1 = false; for(final ZippedFile t : zippedFiles) { final char[] bytes = t.getName().toCharArray(); var fixDir = false; for(var j = 0; j < bytes.length; j++) { if(bytes[j] != '\\') continue; fixDir = true; bytes[j] = '/'; tzStatus.add(TrrntZipStatus.BADDIRECTORYSEPARATOR); if(!error1 && StatusLogCallBack.isVerboseLogging()) { error1 = true; StatusLogCallBack.statusLogCallBack(Messages.getString("TorrentZipCheck.IncorrectDirectorySeparatoreFound")); //$NON-NLS-1$ } } if(fixDir) t.setName(new String(bytes)); } // ***************************** RULE 2 ************************************* // All Files in a torrentzip should be sorted with a lower case file compare. // // if needed sort the files correctly, and return Unsorted if errors found. var error2 = false; var thisSortFound = true; while(thisSortFound) { thisSortFound = false; for(var i = 0; i < zippedFiles.size() - 1; i++) { final int c = zippedFiles.get(i).getName().compareToIgnoreCase(zippedFiles.get(i + 1).getName()); if(c > 0) { final var zf = zippedFiles.get(i); zippedFiles.set(i, zippedFiles.get(i + 1)); zippedFiles.set(i + 1, zf); tzStatus.add(TrrntZipStatus.UNSORTED); thisSortFound = true; if(!error2 && StatusLogCallBack.isVerboseLogging()) { error2 = true; StatusLogCallBack.statusLogCallBack(Messages.getString("TorrentZipCheck.IncorrectFileOrderFound")); //$NON-NLS-1$ } } } } // ***************************** RULE 3 ************************************* // Directory marker files are only needed if they are empty directories. // // now that the files are sorted correctly, we can see if there are unneeded // directory files, by first finding directory files (these end in a '\' character ascii 92) // and then checking if the next file is a file in that found directory. // If we find this 2 entry pattern (directory followed by file in that directory) // then the directory entry should not be present and the torrentzip is incorrect. // return ExtraDirectoryEnteries if error is found. var error3 = false; for(var i = 0; i < zippedFiles.size() - 1; i++) { // check if this is a directory entry if(zippedFiles.get(i).getName().charAt(zippedFiles.get(i).getName().length() - 1) != '/') continue; // check if the next filename is shorter or equal to this filename. // if it is shorter or equal it cannot be a file in the directory. if(zippedFiles.get(i + 1).getName().length() <= zippedFiles.get(i).getName().length()) continue; // check if the directory part of the two file enteries match // if they do we found an incorrect directory entry. var delete = true; for(var j = 0; j < zippedFiles.get(i).getName().length(); j++) { if(zippedFiles.get(i).getName().charAt(j) != zippedFiles.get(i + 1).getName().charAt(j)) { delete = false; break; } } // we found an incorrect directory so remove it. if(delete) { zippedFiles.remove(i); tzStatus.add(TrrntZipStatus.EXTRADIRECTORYENTRIES); if(!error3 && StatusLogCallBack.isVerboseLogging()) { error3 = true; StatusLogCallBack.statusLogCallBack(Messages.getString("TorrentZipCheck.UnneededDirectoryRecordsFound")); //$NON-NLS-1$ } i--; } } // check for repeat files var error4 = false; for(var i = 0; i < zippedFiles.size() - 1; i++) { if(zippedFiles.get(i).getName().equals(zippedFiles.get(i + 1).getName())) { tzStatus.add(TrrntZipStatus.REPEATFILESFOUND); if(!error4 && StatusLogCallBack.isVerboseLogging()) { error4 = true; StatusLogCallBack.statusLogCallBack(Messages.getString("TorrentZipCheck.DuplicateFileEntriesFound")); //$NON-NLS-1$ } } } return tzStatus; } }
package com.vehicles; import java.awt.Color; import com.Game; import com.Player; import com.Vehicle; public class Wave extends Vehicle { private static float WAVE_STEEPNESS = 8; @Override public void click(Player p) { } @Override public void tick(Player p) { if (Game.g.mousePressed) { p.setyVelocity(WAVE_STEEPNESS * Game.getGravityConstant()); } else { p.setyVelocity(WAVE_STEEPNESS * -Game.getGravityConstant()); } } @Override public Color getColor() { return Color.BLUE; } }
package ca.uhn.fhir.jpa.dao.r4; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.junit.AfterClass; import org.junit.Before; import ca.uhn.fhir.jpa.rp.r4.PatientResourceProvider; import ca.uhn.fhir.rest.api.server.IRequestOperationCallback; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.TestUtil; public abstract class BaseJpaR4SystemTest extends BaseJpaR4Test { protected ServletRequestDetails mySrd; private RestfulServer myServer; @AfterClass public static void afterClassClearContext() { TestUtil.clearAllStaticFieldsForUnitTest(); } @SuppressWarnings("unchecked") @Before public void before() throws ServletException { mySrd = mock(ServletRequestDetails.class); when(mySrd.getRequestOperationCallback()).thenReturn(mock(IRequestOperationCallback.class)); if (myServer == null) { myServer = new RestfulServer(myFhirCtx); PatientResourceProvider patientRp = new PatientResourceProvider(); patientRp.setDao(myPatientDao); myServer.setResourceProviders(patientRp); myServer.init(mock(ServletConfig.class)); } when(mySrd.getServer()).thenReturn(myServer); HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(mySrd.getServletRequest()).thenReturn(servletRequest); when(mySrd.getFhirServerBase()).thenReturn("http://example.com/base"); when(servletRequest.getHeaderNames()).thenReturn(mock(Enumeration.class)); when(servletRequest.getRequestURL()).thenReturn(new StringBuffer("/Patient")); } }
package net.explorviz.api; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.explorviz.model.landscape.Landscape; import net.explorviz.model.store.Timestamp; import net.explorviz.model.store.helper.TimestampHelper; import net.explorviz.repository.LandscapeExchangeService; import net.explorviz.server.helper.PropertyService; import net.explorviz.server.main.Configuration; import net.explorviz.server.providers.CoreModelHandler; import net.explorviz.server.providers.GenericTypeFinder; /** * Interface implementation of the extension API - Offers version information * and provides landscapes and timestamps * * @author Christian Zirkelbach (czi@informatik.uni-kiel.de) * */ public final class ExtensionAPIImpl implements IExtensionAPI { static final Logger LOGGER = LoggerFactory.getLogger(ExtensionAPIImpl.class.getName()); private static ExtensionAPIImpl instance; String versionNumber = "1.2.0a"; LandscapeExchangeService service; private ExtensionAPIImpl() { this.service = LandscapeExchangeService.getInstance(); } public static synchronized ExtensionAPIImpl getInstance() { if (ExtensionAPIImpl.instance == null) { ExtensionAPIImpl.instance = new ExtensionAPIImpl(); } return ExtensionAPIImpl.instance; } /** * Reveals the currently provides API version */ @Override public String getAPIVersion() { return "ExplorViz Extension API version: " + versionNumber; } /** * Provides the current landscape */ @Override public Landscape getLatestLandscape() { return service.getCurrentLandscape(); } /** * Provides a specific landscape determined by a passed timestamp * * @param timestamp * (as configured in Kieker) */ @Override public Landscape getLandscape(final long timestamp, final String folderName) { Landscape specificLandscape = new Landscape(); try { specificLandscape = service.getLandscape(timestamp, folderName); return specificLandscape; } catch (final FileNotFoundException e) { LOGGER.debug("Specific landscape not found!", e.getMessage()); return specificLandscape; } } /** * Provides the "intervalSize" newest timestamps within the server * * @param intervalSize * (number of retrieved timestamps) * @return List of Timestamp */ @Override public List<Timestamp> getNewestTimestamps(final int intervalSize) { final List<Timestamp> allTimestamps = this.service .getTimestampObjectsInRepo(Configuration.LANDSCAPE_REPOSITORY); return TimestampHelper.filterMostRecentTimestamps(allTimestamps, intervalSize); } /** * Provides the "intervalSize" oldest timestamps within the server * * @param intervalSize * (number of retrieved timestamps) * @return List of Timestamp */ @Override public List<Timestamp> getOldestTimestamps(final int intervalSize) { final List<Timestamp> allTimestamps = this.service .getTimestampObjectsInRepo(Configuration.LANDSCAPE_REPOSITORY); return TimestampHelper.filterOldestTimestamps(allTimestamps, intervalSize); } /** * Provides the "intervalSize" timestamps before a passed "fromTimestamp" within * the server * * @param fromTimestamp * (timestamp, which sets the limit) * @param intervalSize * (number of retrieved timestamps) * @return List of Timestamp */ @Override public List<Timestamp> getPreviousTimestamps(final long fromTimestamp, final int intervalSize) { final List<Timestamp> allTimestamps = this.service .getTimestampObjectsInRepo(Configuration.LANDSCAPE_REPOSITORY); return TimestampHelper.filterTimestampsBeforeTimestamp(allTimestamps, fromTimestamp, intervalSize); } /** * Provides the "intervalSize" timestamps after a passed "afterTimestamp" within * the server * * @param afterTimestamp * (timestamp, which sets the limit) * @param intervalSize * (number of retrieved timestamps) * @return List of Timestamp */ @Override public List<Timestamp> getSubsequentTimestamps(final long afterTimestamp, final int intervalSize) { final List<Timestamp> allTimestamps = this.service .getTimestampObjectsInRepo(Configuration.LANDSCAPE_REPOSITORY); return TimestampHelper.filterTimestampsAfterTimestamp(allTimestamps, afterTimestamp, intervalSize); } public List<Timestamp> getUploadedTimestamps() { final List<Timestamp> allTimestamps = this.service.getTimestampObjectsInRepo(Configuration.REPLAY_REPOSITORY); return allTimestamps; } /** * Registers specific core model types for the JSONAPI provider (necessary by * extensions, if they want to use specific backend models) - e.g., * ("Timestamp", Timestamp.class) */ @Override public void registerSpecificCoreModels(final Map<String, Class<?>> typeMap) { for (final Map.Entry<String, Class<?>> entry : typeMap.entrySet()) { GenericTypeFinder.typeMap.putIfAbsent(entry.getKey(), entry.getValue()); } } /** * Registers specific model types for the JSONAPI provider (necessary by * extensions, if they want to use specific or custom backend models) - e.g., * ("Timestamp", Timestamp.class) */ @Override public void registerSpecificModel(final String typeName, final Class<?> type) { GenericTypeFinder.typeMap.putIfAbsent(typeName, type); } /** * Registers all core model types for the JSONAPI provider (necessary by * extensions, if they want to use all backend models) */ @Override public void registerAllCoreModels() { CoreModelHandler.registerAllCoreModels(); } /** * Enable / disable dummy mode true = Use dummy monitoring data instead of real * monitoring data * * @throws IOException * @throws FileNotFoundException */ @Override public void setDummyMode(final boolean value) throws FileNotFoundException, IOException { PropertyService.setBooleanProperty("useDummyMode", value); } }
/** * Copyright (C) 2011 Google 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.google.inject; import static com.google.common.collect.ImmutableList.of; import static com.google.inject.Asserts.assertContains; import static com.google.inject.name.Names.named; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.inject.matcher.AbstractMatcher; import com.google.inject.matcher.Matcher; import com.google.inject.matcher.Matchers; import com.google.inject.name.Named; import com.google.inject.spi.DependencyAndSource; import com.google.inject.spi.InstanceBinding; import com.google.inject.spi.ProvisionListener; import com.google.inject.util.Providers; import junit.framework.TestCase; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * Tests for {@link Binder#bindListener(Matcher, ProvisionListener...)} * * @author sameb@google.com (Sam Berlin) */ // TODO(sameb): Add some tests for private modules & child injectors. public class ProvisionListenerTest extends TestCase { public void testExceptionInListenerBeforeProvisioning() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new FailBeforeProvision()); } }); try { injector.getInstance(Foo.class); fail(); } catch(ProvisionException pe) { assertEquals(1, pe.getErrorMessages().size()); assertContains(pe.getMessage(), "1) Error notifying ProvisionListener " + FailBeforeProvision.class.getName() + " of " + Foo.class.getName(), "Reason: java.lang.RuntimeException: boo", "while locating " + Foo.class.getName()); assertEquals("boo", pe.getCause().getMessage()); } } public void testExceptionInListenerAfterProvisioning() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new FailAfterProvision()); } }); try { injector.getInstance(Foo.class); fail(); } catch(ProvisionException pe) { assertEquals(1, pe.getErrorMessages().size()); assertContains(pe.getMessage(), "1) Error notifying ProvisionListener " + FailAfterProvision.class.getName() + " of " + Foo.class.getName(), "Reason: java.lang.RuntimeException: boo", "while locating " + Foo.class.getName()); assertEquals("boo", pe.getCause().getMessage()); } } public void testExceptionInProvisionExplicitlyCalled() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new JustProvision()); } }); try { injector.getInstance(FooBomb.class); fail(); } catch(ProvisionException pe) { assertEquals(1, pe.getErrorMessages().size()); assertContains(pe.getMessage(), "1) Error injecting constructor, java.lang.RuntimeException: Retry, Abort, Fail", " at " + FooBomb.class.getName(), " while locating " + FooBomb.class.getName()); assertEquals("Retry, Abort, Fail", pe.getCause().getMessage()); } } public void testExceptionInProvisionAutomaticallyCalled() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new NoProvision()); } }); try { injector.getInstance(FooBomb.class); fail(); } catch(ProvisionException pe) { assertEquals(1, pe.getErrorMessages().size()); assertContains(pe.getMessage(), "1) Error injecting constructor, java.lang.RuntimeException: Retry, Abort, Fail", " at " + FooBomb.class.getName(), " while locating " + FooBomb.class.getName()); assertEquals("Retry, Abort, Fail", pe.getCause().getMessage()); } } public void testListenerCallsProvisionTwice() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new ProvisionTwice()); } }); try { injector.getInstance(Foo.class); fail(); } catch(ProvisionException pe) { assertEquals(1, pe.getErrorMessages().size()); assertContains(pe.getMessage(), "1) Error notifying ProvisionListener " + ProvisionTwice.class.getName() + " of " + Foo.class.getName(), "Reason: java.lang.IllegalStateException: Already provisioned in this listener.", "while locating " + Foo.class.getName()); assertEquals("Already provisioned in this listener.", pe.getCause().getMessage()); } } public void testCachedInScopePreventsProvisionNotify() { final Counter count1 = new Counter(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), count1); bind(Foo.class).in(Scopes.SINGLETON); } }); Foo foo = injector.getInstance(Foo.class); assertNotNull(foo); assertEquals(1, count1.count); // not notified the second time because nothing is provisioned // (it's cached in the scope) count1.count = 0; assertSame(foo, injector.getInstance(Foo.class)); assertEquals(0, count1.count); } public void testCombineAllBindListenerCalls() { final Counter count1 = new Counter(); final Counter count2 = new Counter(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), count1); bindListener(Matchers.any(), count2); } }); assertNotNull(injector.getInstance(Foo.class)); assertEquals(1, count1.count); assertEquals(1, count2.count); } public void testNotifyEarlyListenersIfFailBeforeProvision() { final Counter count1 = new Counter(); final Counter count2 = new Counter(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), count1, new FailBeforeProvision(), count2); } }); try { injector.getInstance(Foo.class); fail(); } catch(ProvisionException pe) { assertEquals(1, pe.getErrorMessages().size()); assertContains(pe.getMessage(), "1) Error notifying ProvisionListener " + FailBeforeProvision.class.getName() + " of " + Foo.class.getName(), "Reason: java.lang.RuntimeException: boo", "while locating " + Foo.class.getName()); assertEquals("boo", pe.getCause().getMessage()); assertEquals(1, count1.count); assertEquals(0, count2.count); } } public void testNotifyLaterListenersIfFailAfterProvision() { final Counter count1 = new Counter(); final Counter count2 = new Counter(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), count1, new FailAfterProvision(), count2); } }); try { injector.getInstance(Foo.class); fail(); } catch(ProvisionException pe) { assertEquals(1, pe.getErrorMessages().size()); assertContains(pe.getMessage(), "1) Error notifying ProvisionListener " + FailAfterProvision.class.getName() + " of " + Foo.class.getName(), "Reason: java.lang.RuntimeException: boo", "while locating " + Foo.class.getName()); assertEquals("boo", pe.getCause().getMessage()); assertEquals(1, count1.count); assertEquals(1, count2.count); } } public void testNotifiedKeysOfAllBindTypes() { final Capturer capturer = new Capturer(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), capturer); bind(Foo.class).annotatedWith(named("pk")).toProvider(FooP.class); try { bind(Foo.class).annotatedWith(named("cxtr")).toConstructor(Foo.class.getDeclaredConstructor()); } catch (Exception ex) { throw new RuntimeException(ex); } bind(LinkedFoo.class).to(Foo.class); bind(Interface.class).toInstance(new Implementation()); bindConstant().annotatedWith(named("constant")).to("MyConstant"); } @Provides @Named("pi") Foo provideFooBar() { return new Foo(); } }); // toInstance & constant bindings are notified in random order, at the very beginning. assertEquals( ImmutableSet.of(Key.get(Interface.class), Key.get(String.class, named("constant"))), capturer.getAsSetAndClear()); // simple binding assertNotNull(injector.getInstance(Foo.class)); assertEquals(of(Key.get(Foo.class)), capturer.getAndClear()); // provider key binding -- notifies about provider & the object, always assertNotNull(injector.getInstance(Key.get(Foo.class, named("pk")))); assertEquals(of(Key.get(FooP.class), Key.get(Foo.class, named("pk"))), capturer.getAndClear()); assertNotNull(injector.getInstance(Key.get(Foo.class, named("pk")))); assertEquals(of(Key.get(FooP.class), Key.get(Foo.class, named("pk"))), capturer.getAndClear()); // JIT provider key binding -- notifies about provider & the object, always assertNotNull(injector.getInstance(JitFoo2.class)); assertEquals(of(Key.get(JitFoo2P.class), Key.get(JitFoo2.class)), capturer.getAndClear()); assertNotNull(injector.getInstance(JitFoo2.class)); assertEquals(of(Key.get(JitFoo2P.class), Key.get(JitFoo2.class)), capturer.getAndClear()); // provider instance binding -- just the object (not the provider) assertNotNull(injector.getInstance(Key.get(Foo.class, named("pi")))); assertEquals(of(Key.get(Foo.class, named("pi"))), capturer.getAndClear()); // toConstructor binding assertNotNull(injector.getInstance(Key.get(Foo.class, named("cxtr")))); assertEquals(of(Key.get(Foo.class, named("cxtr"))), capturer.getAndClear()); // linked binding -- notifies about the target (that's what's provisioned), not the link assertNotNull(injector.getInstance(LinkedFoo.class)); assertEquals(of(Key.get(Foo.class)), capturer.getAndClear()); // JIT linked binding -- notifies about the target (that's what's provisioned), not the link assertNotNull(injector.getInstance(JitFoo.class)); assertEquals(of(Key.get(Foo.class)), capturer.getAndClear()); } public void testSingletonMatcher() { final Counter counter = new Counter(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(new AbstractMatcher<Binding<?>>() { @Override public boolean matches(Binding<?> t) { return Scopes.isSingleton(t); } }, counter); } }); assertEquals(0, counter.count); // no increment for getting Many. injector.getInstance(Many.class); assertEquals(0, counter.count); // but an increment for getting Sole, since it's a singleton. injector.getInstance(Sole.class); assertEquals(1, counter.count); } public void testCallingBindingDotGetProviderDotGet() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new ProvisionListener() { @Override public <T> void onProvision(ProvisionInvocation<T> provision) { provision.getBinding().getProvider().get(); // AGH! } }); } }); try { injector.getInstance(Sole.class); fail(); } catch(ProvisionException expected) { // We don't really care what kind of error you get, we only care you get an error. } try { injector.getInstance(Many.class); fail(); } catch(ProvisionException expected) { // We don't really care what kind of error you get, we only care you get an error. } } interface Interface {} class Implementation implements Interface {} @Singleton static class Sole {} static class Many {} @ImplementedBy(Foo.class) static interface JitFoo {} @ProvidedBy(JitFoo2P.class) static class JitFoo2 {} static interface LinkedFoo {} static class Foo implements JitFoo, LinkedFoo {} static class FooP implements Provider<Foo> { public Foo get() { return new Foo(); } } static class JitFoo2P implements Provider<JitFoo2> { public JitFoo2 get() { return new JitFoo2(); } } static class FooBomb { FooBomb() { throw new RuntimeException("Retry, Abort, Fail"); } } private static class Counter implements ProvisionListener { int count = 0; public <T> void onProvision(ProvisionInvocation<T> provision) { count++; } } private static class Capturer implements ProvisionListener { List<Key> keys = Lists.newArrayList(); public <T> void onProvision(ProvisionInvocation<T> provision) { keys.add(provision.getBinding().getKey()); T provisioned = provision.provision(); // InstanceBindings are the only kind of binding where the key can // be an instanceof the provisioned, because it isn't linked to any // direct implementation. I guess maybe it'd also be possible // with a toConstructor binding... but we don't use that in our tests. if (provision.getBinding() instanceof InstanceBinding) { Class<? super T> expected = provision.getBinding().getKey().getRawType(); assertTrue("expected instanceof: " + expected + ", but was: " + provisioned, expected.isInstance(provisioned)); } else { assertEquals(provision.getBinding().getKey().getRawType(), provisioned.getClass()); } } Set<Key> getAsSetAndClear() { Set<Key> copy = ImmutableSet.copyOf(keys); keys.clear(); return copy; } List<Key> getAndClear() { List<Key> copy = ImmutableList.copyOf(keys); keys.clear(); return copy; } } private static class FailBeforeProvision implements ProvisionListener { public <T> void onProvision(ProvisionInvocation<T> provision) { throw new RuntimeException("boo"); } } private static class FailAfterProvision implements ProvisionListener { public <T> void onProvision(ProvisionInvocation<T> provision) { provision.provision(); throw new RuntimeException("boo"); } } private static class JustProvision implements ProvisionListener { public <T> void onProvision(ProvisionInvocation<T> provision) { provision.provision(); } } private static class NoProvision implements ProvisionListener { public <T> void onProvision(ProvisionInvocation<T> provision) { } } private static class ProvisionTwice implements ProvisionListener { public <T> void onProvision(ProvisionInvocation<T> provision) { provision.provision(); provision.provision(); } } private static class ChainAsserter implements ProvisionListener { private final List<Class<?>> provisionList; private final List<Class<?>> expected; public ChainAsserter(List<Class<?>> provisionList, Iterable<Class<?>> expected) { this.provisionList = provisionList; this.expected = ImmutableList.copyOf(expected); } public <T> void onProvision(ProvisionInvocation<T> provision) { List<Class<?>> actual = Lists.newArrayList(); for (DependencyAndSource dep : provision.getDependencyChain()) { actual.add(dep.getDependency().getKey().getRawType()); } assertEquals(expected, actual); provisionList.add(provision.getBinding().getKey().getRawType()); } } private static Matcher<Binding<?>> keyMatcher(final Class<?> clazz) { return new AbstractMatcher<Binding<?>>() { @Override public boolean matches(Binding<?> t) { return t.getKey().equals(Key.get(clazz)); } }; } @SuppressWarnings("unchecked") public void testDependencyChain() { final List<Class<?>> pList = Lists.newArrayList(); final List<Class<?>> totalList = Lists.newArrayList(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Instance.class).toInstance(new Instance()); bind(B.class).to(BImpl.class); bind(D.class).toProvider(DP.class); bindListener(Matchers.any(), new ProvisionListener() { public <T> void onProvision(ProvisionInvocation<T> provision) { totalList.add(provision.getBinding().getKey().getRawType()); } }); // Build up a list of asserters for our dependency chains. ImmutableList.Builder<Class<?>> chain = ImmutableList.builder(); chain.add(Instance.class); bindListener(keyMatcher(Instance.class), new ChainAsserter(pList, chain.build())); chain.add(A.class); bindListener(keyMatcher(A.class), new ChainAsserter(pList, chain.build())); chain.add(B.class).add(BImpl.class); bindListener(keyMatcher(BImpl.class), new ChainAsserter(pList, chain.build())); chain.add(C.class); bindListener(keyMatcher(C.class), new ChainAsserter(pList, chain.build())); // the chain has D before DP even though DP is provisioned & notified first // because we do DP because of D, and need DP to provision D. chain.add(D.class).add(DP.class); bindListener(keyMatcher(D.class), new ChainAsserter(pList, chain.build())); bindListener(keyMatcher(DP.class), new ChainAsserter(pList, chain.build())); chain.add(E.class); bindListener(keyMatcher(E.class), new ChainAsserter(pList, chain.build())); chain.add(F.class); bindListener(keyMatcher(F.class), new ChainAsserter(pList, chain.build())); } @Provides C c(D d) { return new C() {}; } }); Instance instance = injector.getInstance(Instance.class); // make sure we're checking all of the chain asserters.. assertEquals( of(Instance.class, A.class, BImpl.class, C.class, DP.class, D.class, E.class, F.class), pList); // and make sure that nothing else was notified that we didn't expect. assertEquals(totalList, pList); } public void testModuleRequestInjection() { final AtomicBoolean notified = new AtomicBoolean(); Guice.createInjector(new AbstractModule() { @Override protected void configure() { requestInjection(new Object() { @Inject Foo foo; }); bindListener(Matchers.any(), new SpecialChecker(Foo.class, getClass().getName() + ".configure(", notified)); } }); assertTrue(notified.get()); } public void testToProviderInstance() { final AtomicBoolean notified = new AtomicBoolean(); Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Object.class).toProvider(new Provider<Object>() { @Inject Foo foo; public Object get() { return null; } }); bindListener(Matchers.any(), new SpecialChecker(Foo.class, getClass().getName() + ".configure(", notified)); } }); assertTrue(notified.get()); } public void testInjectorInjectMembers() { final Object object = new Object() { @Inject Foo foo; }; final AtomicBoolean notified = new AtomicBoolean(); Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new SpecialChecker(Foo.class, object.getClass().getName(), notified)); } }).injectMembers(object); assertTrue(notified.get()); } private static class SpecialChecker implements ProvisionListener { private final Class<?> notifyType; private final String firstSource; private final AtomicBoolean notified; public SpecialChecker(Class<?> notifyType, String firstSource, AtomicBoolean notified) { this.notifyType = notifyType; this.firstSource = firstSource; this.notified = notified; } public <T> void onProvision(ProvisionInvocation<T> provision) { notified.set(true); assertEquals(notifyType, provision.getBinding().getKey().getRawType()); assertEquals(2, provision.getDependencyChain().size()); assertNull(provision.getDependencyChain().get(0).getDependency()); assertContains(provision.getDependencyChain().get(0).getBindingSource(), firstSource); assertEquals(notifyType, provision.getDependencyChain().get(1).getDependency().getKey().getRawType()); assertContains(provision.getDependencyChain().get(1).getBindingSource(), notifyType.getName() + ".class("); } } private static class Instance { @Inject A a; } private static class A { @Inject A(B b) {} } private interface B {} private static class BImpl implements B { @Inject void inject(C c) {} } private interface C {} private interface D {} private static class DP implements Provider<D> { @Inject Provider<E> ep; public D get() { ep.get(); return new D() {}; } } private static class E { @SuppressWarnings("unused") @Inject F f; } private static class F { } public void testBindToInjectorWithListeningGivesSaneException() { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new Counter()); bind(Injector.class).toProvider(Providers.<Injector>of(null)); } }); fail(); } catch (CreationException ce) { assertContains( ce.getMessage(), "Binding to core guice framework type is not allowed: Injector."); } } public void testProvisionIsNotifiedAfterContextsClear() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), new ProvisionListener() { @Override public <T> void onProvision(ProvisionInvocation<T> provision) { Object provisioned = provision.provision(); if (provisioned instanceof X) { ((X)provisioned).init(); } else if (provisioned instanceof Y) { X.createY = false; ((Y)provisioned).init(); } } }); } }); X.createY = true; X x = injector.getInstance(X.class); assertNotSame(x, x.y.x); assertFalse("x.ID: " + x.ID + ", x.y.x.iD: " + x.y.x.ID, x.ID == x.y.x.ID); } private static class X { final static AtomicInteger COUNTER = new AtomicInteger(); static boolean createY; final int ID = COUNTER.getAndIncrement(); final Provider<Y> yProvider; Y y; @Inject X(Provider<Y> yProvider) { this.yProvider = yProvider; } void init() { if (createY) { this.y = yProvider.get(); } } } private static class Y { final Provider<X> xProvider; X x; @Inject Y(Provider<X> xProvider) { this.xProvider = xProvider; } void init() { this.x = xProvider.get(); } } public void testDeDuplicateProvisionListeners() { final Counter counter = new Counter(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(Matchers.any(), counter); bindListener(Matchers.any(), counter); } }); injector.getInstance(Many.class); assertEquals("ProvisionListener not de-duplicated", 1, counter.count); } }
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.ui.widget; import java.util.HashMap; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiBlob; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiDrawableReference; import org.appcelerator.titanium.view.TiUIView; import android.graphics.Color; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.Drawable; import android.view.Gravity; import android.support.v7.widget.AppCompatButton; public class TiUIButton extends TiUIView { private static final String TAG = "TiUIButton"; private static final float DEFAULT_SHADOW_RADIUS = 1f; private int defaultColor; private float shadowRadius = DEFAULT_SHADOW_RADIUS; private float shadowX = 0f; private float shadowY = 0f; private int shadowColor = Color.TRANSPARENT; public TiUIButton(final TiViewProxy proxy) { super(proxy); Log.d(TAG, "Creating a button", Log.DEBUG_MODE); AppCompatButton btn = new AppCompatButton(proxy.getActivity()) { @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); TiUIHelper.firePostLayoutEvent(proxy); } }; btn.setGravity(Gravity.CENTER); defaultColor = btn.getCurrentTextColor(); setNativeView(btn); } @Override public void processProperties(KrollDict d) { super.processProperties(d); boolean needShadow = false; AppCompatButton btn = (AppCompatButton) getNativeView(); if (d.containsKey(TiC.PROPERTY_IMAGE)) { Object value = d.get(TiC.PROPERTY_IMAGE); TiDrawableReference drawableRef = null; if (value instanceof String) { drawableRef = TiDrawableReference.fromUrl(proxy, (String) value); } else if (value instanceof TiBlob) { drawableRef = TiDrawableReference.fromBlob(proxy.getActivity(), (TiBlob) value); } if (drawableRef != null) { Drawable image = drawableRef.getDensityScaledDrawable(); btn.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null); } } else if (d.containsKey(TiC.PROPERTY_BACKGROUND_COLOR)) { // Reset the padding here if the background color is set. By default the padding will be calculated // for the button, but if we set a background color, it will not look centered unless we reset the padding. btn.setPadding(8, 0, 8, 0); } if (d.containsKey(TiC.PROPERTY_TITLE)) { btn.setText(d.getString(TiC.PROPERTY_TITLE)); } if (d.containsKey(TiC.PROPERTY_COLOR)) { Object color = d.get(TiC.PROPERTY_COLOR); if (color == null) { btn.setTextColor(defaultColor); } else { btn.setTextColor(TiConvert.toColor(d, TiC.PROPERTY_COLOR)); } } if (d.containsKey(TiC.PROPERTY_FONT)) { TiUIHelper.styleText(btn, d.getKrollDict(TiC.PROPERTY_FONT)); } if (d.containsKey(TiC.PROPERTY_TEXT_ALIGN)) { String textAlign = d.getString(TiC.PROPERTY_TEXT_ALIGN); TiUIHelper.setAlignment(btn, textAlign, null); } if (d.containsKey(TiC.PROPERTY_VERTICAL_ALIGN)) { String verticalAlign = d.getString(TiC.PROPERTY_VERTICAL_ALIGN); TiUIHelper.setAlignment(btn, null, verticalAlign); } if (d.containsKey(TiC.PROPERTY_SHADOW_OFFSET)) { Object value = d.get(TiC.PROPERTY_SHADOW_OFFSET); if (value instanceof HashMap) { needShadow = true; HashMap dict = (HashMap) value; shadowX = TiConvert.toFloat(dict.get(TiC.PROPERTY_X), 0); shadowY = TiConvert.toFloat(dict.get(TiC.PROPERTY_Y), 0); } } if (d.containsKey(TiC.PROPERTY_SHADOW_RADIUS)) { needShadow = true; shadowRadius = TiConvert.toFloat(d.get(TiC.PROPERTY_SHADOW_RADIUS), DEFAULT_SHADOW_RADIUS); } if (d.containsKey(TiC.PROPERTY_SHADOW_COLOR)) { needShadow = true; shadowColor = TiConvert.toColor(d, TiC.PROPERTY_SHADOW_COLOR); } if (d.containsKey(TiC.PROPERTY_TINT_COLOR)) { Object color = d.get(TiC.PROPERTY_TINT_COLOR); if (color == null) { btn.getBackground().clearColorFilter(); } else { btn.getBackground().setColorFilter(TiConvert.toColor(d, TiC.PROPERTY_TINT_COLOR), Mode.MULTIPLY); } } if (needShadow) { btn.setShadowLayer(shadowRadius, shadowX, shadowY, shadowColor); } btn.invalidate(); } @Override public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (Log.isDebugModeEnabled()) { Log.d(TAG, "Property: " + key + " old: " + oldValue + " new: " + newValue, Log.DEBUG_MODE); } AppCompatButton btn = (AppCompatButton) getNativeView(); if (key.equals(TiC.PROPERTY_TITLE)) { btn.setText((String) newValue); } else if (key.equals(TiC.PROPERTY_COLOR)) { btn.setTextColor(TiConvert.toColor(TiConvert.toString(newValue))); } else if (key.equals(TiC.PROPERTY_FONT)) { TiUIHelper.styleText(btn, (HashMap) newValue); } else if (key.equals(TiC.PROPERTY_TEXT_ALIGN)) { TiUIHelper.setAlignment(btn, TiConvert.toString(newValue), null); btn.requestLayout(); } else if (key.equals(TiC.PROPERTY_VERTICAL_ALIGN)) { TiUIHelper.setAlignment(btn, null, TiConvert.toString(newValue)); btn.requestLayout(); } else if (key.equals(TiC.PROPERTY_IMAGE)) { TiDrawableReference drawableRef = null; if (newValue instanceof String) { drawableRef = TiDrawableReference.fromUrl(proxy, (String) newValue); } else if (newValue instanceof TiBlob) { drawableRef = TiDrawableReference.fromBlob(proxy.getActivity(), (TiBlob) newValue); } if (drawableRef != null) { Drawable image = drawableRef.getDrawable(); btn.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null); } } else if (key.equals(TiC.PROPERTY_SHADOW_OFFSET)) { if (newValue instanceof HashMap) { HashMap dict = (HashMap) newValue; shadowX = TiConvert.toFloat(dict.get(TiC.PROPERTY_X), 0); shadowY = TiConvert.toFloat(dict.get(TiC.PROPERTY_Y), 0); btn.setShadowLayer(shadowRadius, shadowX, shadowY, shadowColor); } } else if (key.equals(TiC.PROPERTY_SHADOW_RADIUS)) { shadowRadius = TiConvert.toFloat(newValue, DEFAULT_SHADOW_RADIUS); btn.setShadowLayer(shadowRadius, shadowX, shadowY, shadowColor); } else if (key.equals(TiC.PROPERTY_SHADOW_COLOR)) { shadowColor = TiConvert.toColor(TiConvert.toString(newValue)); btn.setShadowLayer(shadowRadius, shadowX, shadowY, shadowColor); } else if (key.equals(TiC.PROPERTY_TINT_COLOR)) { if (newValue == null){ btn.getBackground().clearColorFilter(); } else { btn.getBackground().setColorFilter( TiConvert.toColor(TiConvert.toString(newValue)), Mode.MULTIPLY); } } else { super.propertyChanged(key, oldValue, newValue, proxy); } } }
/* * This file is part of choco-solver, http://choco-solver.org/ * * Copyright (c) 2021, IMT Atlantique. All rights reserved. * * Licensed under the BSD 4-clause license. * * See LICENSE file in the project root for full license information. */ package org.chocosolver.solver.search.strategy.strategy; import org.chocosolver.solver.search.strategy.decision.Decision; import org.chocosolver.solver.search.strategy.selectors.values.RealValueSelector; import org.chocosolver.solver.search.strategy.selectors.variables.VariableSelector; import org.chocosolver.solver.variables.RealVar; import java.util.Arrays; /** * Define a strategy based on {@link RealVar}. * It defines how a variable is selected to be part of the next decision, and which value from its domain is selected too. * Then, the decision will be {@code var} &le; {value}. * <br/> * * @author Charles Prud'homme * @since 2 juil. 2010 */ public class RealStrategy extends AbstractStrategy<RealVar> { /** * How a variable is selected */ private final VariableSelector<RealVar> varselector; /** * How a value is selected */ private final RealValueSelector valueIterator; /** * Gap when refuting a decision */ private final double epsilon; /** * Select left range first */ private final boolean leftFirst; /** * Create a real strategy which generates decision over real variables. * <p> * A real decision is like: * <ul> * <li>left branch: X &le; v</li> * <li>right branch: X &ge; v + e</li> * </ul> * where e is 'epsilon' * </p> * @param scope variables to be managed with this strategy * @param varselector how to select the next variable to branch on * @param valueIterator on to select the value * @param epsilon gap value for refutation * @param leftFirst select left range first */ public RealStrategy(RealVar[] scope, VariableSelector<RealVar> varselector, RealValueSelector valueIterator, double epsilon, boolean leftFirst) { super(scope); this.varselector = varselector; this.valueIterator = valueIterator; if(Double.isNaN(epsilon)){ double min = Arrays.stream(scope).mapToDouble(RealVar::getPrecision).min().getAsDouble(); this.epsilon = min / 10; }else { this.epsilon = epsilon; } this.leftFirst = leftFirst; } @Override public boolean init() { return varselector.init(); } @Override public void remove() { varselector.remove(); } @Override public Decision<RealVar> computeDecision(RealVar variable) { if (variable == null || variable.isInstantiated()) { return null; } double value = valueIterator.selectValue(variable); return variable.getModel().getSolver().getDecisionPath().makeRealDecision(variable, value, epsilon, leftFirst); } @SuppressWarnings({"unchecked"}) @Override public Decision getDecision() { RealVar variable = varselector.getVariable(vars); return computeDecision(variable); } }
package com.stylefeng.guns.rest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.scheduling.annotation.EnableAsync; import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration; @SpringBootApplication(scanBasePackages = {"com.stylefeng.guns"}) @EnableAsync @EnableDubboConfiguration @EnableHystrixDashboard @EnableCircuitBreaker @EnableHystrix public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
package mekanism.common.upgrade.transmitter; import mekanism.common.tile.transmitter.TileEntitySidedPipe.ConnectionType; public class ThermodynamicConductorUpgradeData extends TransmitterUpgradeData { public final double heat; public ThermodynamicConductorUpgradeData(boolean redstoneReactive, ConnectionType[] connectionTypes, double heat) { super(redstoneReactive, connectionTypes); this.heat = heat; } }
/* * * Copyright 2012-2014 Eurocommercial Properties NV * * * 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.estatio.dom.lease; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import org.jmock.Expectations; import org.jmock.auto.Mock; import org.joda.time.LocalDate; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.apache.isis.applib.annotation.Property; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.services.clock.ClockService; import org.apache.isis.core.unittestsupport.comparable.ComparableContractTest_compareTo; import org.apache.isis.core.unittestsupport.jmocking.JUnitRuleMockery2; import org.isisaddons.module.security.dom.tenancy.ApplicationTenancy; import org.incode.module.base.dom.with.WithIntervalMutable; import org.incode.module.unittestsupport.dom.bean.AbstractBeanPropertiesTest; import org.incode.module.unittestsupport.dom.bean.PojoTester.FixtureDatumFactory; import org.incode.module.unittestsupport.dom.with.WithIntervalMutableContractTestAbstract_changeDates; import org.estatio.dom.agreement.type.AgreementType; import org.estatio.dom.charge.Charge; import org.estatio.dom.tax.Tax; import static org.assertj.core.api.Assertions.assertThat; public class LeaseItem_Test { @Rule public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(JUnitRuleMockery2.Mode.INTERFACES_AND_CLASSES); LeaseItem leaseItem; public static class GetCurrentValue extends LeaseItem_Test { private final LocalDate now = LocalDate.now(); private LeaseTermForTesting leaseTerm; private LocalDate getCurrentValueDateArgument; @Mock private ClockService mockClockService; @Before public void setUp() throws Exception { context.checking(new Expectations() { { oneOf(mockClockService).now(); will(returnValue(now)); } }); leaseTerm = new LeaseTermForTesting(); leaseTerm.setValue(BigDecimal.TEN); leaseItem = new LeaseItem() { @Override @Property(hidden = Where.EVERYWHERE) public LeaseTerm currentTerm(LocalDate date) { GetCurrentValue.this.getCurrentValueDateArgument = date; return leaseTerm; } }; leaseItem.clockService = mockClockService; } @Test public void test() { assertThat(leaseItem.getValue()).isEqualTo(BigDecimal.TEN); assertThat(getCurrentValueDateArgument).isEqualTo(now); } } public static class ToString extends LeaseItem_Test { private Lease lease; @Before public void setUp() throws Exception { lease = new Lease(); AgreementType type = new AgreementType(); type.setTitle("Lease"); lease.setType(type); lease.setReference("A"); leaseItem = new LeaseItem(); leaseItem.setLease(lease); } @Test public void happyCase() throws Exception { assertThat(lease.toString()).isEqualTo("Lease{type=Lease, reference=A}"); assertThat(leaseItem.toString()).isEqualTo("LeaseItem{lease=A, type=null, charge=null, startDate=null, sequence=null}"); } } public static class BeanProperties extends AbstractBeanPropertiesTest { @Test public void test() { newPojoTester() .withFixture(pojos(Charge.class)) .withFixture(pojos(Lease.class)) .withFixture(statii()) .withFixture(pojos(Tax.class)) .withFixture(pojos(ApplicationTenancy.class)) .exercise(new LeaseItem()); } @SuppressWarnings({ "rawtypes", "unchecked" }) private static FixtureDatumFactory<LeaseItemStatus> statii() { return new FixtureDatumFactory(LeaseItemStatus.class, (Object[]) LeaseItemStatus.values()); } } public static class ChangeDates extends WithIntervalMutableContractTestAbstract_changeDates<LeaseItem> { private LeaseItem leaseItem; @Before public void setUp() throws Exception { leaseItem = withIntervalMutable; } protected LeaseItem doCreateWithIntervalMutable(final WithIntervalMutable.Helper<LeaseItem> mockChangeDates) { return new LeaseItem() { @Override WithIntervalMutable.Helper<LeaseItem> getChangeDates() { return mockChangeDates; } }; } @Test public void changeDatesDelegate() { leaseItem = new LeaseItem(); assertThat(leaseItem.getChangeDates()).isNotNull(); } } public static class ChoicesNewSourceItem extends LeaseItem_Test { @Mock LeaseItemSourceRepository mockLeaseItemSourceRepository; LeaseItem itemLinked; LeaseItem itemNotLinked; Lease lease; @Before public void setup() { itemLinked = new LeaseItem(); itemLinked.setType(LeaseItemType.RENT); itemNotLinked = new LeaseItem(); itemNotLinked.setType(LeaseItemType.RENT_DISCOUNT); lease = new Lease() { @Override public SortedSet<LeaseItem> getItems() { return new TreeSet<>(Arrays.asList(itemLinked, itemNotLinked, leaseItem)); } }; } @Test public void testChoices() throws Exception { // given leaseItem = new LeaseItem(); leaseItem.setLease(lease); leaseItem.leaseItemSourceRepository = mockLeaseItemSourceRepository; LeaseItemSource leaseItemSource = new LeaseItemSource(); leaseItemSource.setItem(leaseItem); leaseItemSource.setSourceItem(itemLinked); context.checking(new Expectations() { { allowing(mockLeaseItemSourceRepository).findByItem(leaseItem); will(returnValue(Arrays.asList(leaseItemSource))); } }); // when List<LeaseItem> choices = leaseItem.choices0NewSourceItem(leaseItem); // then assertThat(leaseItem.getLease().getItems()).hasSize(3); assertThat(choices).hasSize(1); assertThat(choices.get(0)).isEqualTo(itemNotLinked); } } public static class CompareTo extends ComparableContractTest_compareTo<LeaseItem> { private Lease lease1; private Lease lease2; @Before public void setUp() throws Exception { lease1 = new Lease(); lease2 = new Lease(); lease1.setReference("A"); lease2.setReference("B"); } @SuppressWarnings("unchecked") @Override protected List<List<LeaseItem>> orderedTuples() { return listOf( listOf( newLeaseItem(null, null, null), newLeaseItem(lease1, null, null), newLeaseItem(lease1, null, null), newLeaseItem(lease2, null, null) ), listOf( newLeaseItem(lease1, null, null), newLeaseItem(lease1, LeaseItemType.RENT, null), newLeaseItem(lease1, LeaseItemType.RENT, null), newLeaseItem(lease1, LeaseItemType.SERVICE_CHARGE, null) ), listOf( newLeaseItem(lease1, LeaseItemType.RENT, null), newLeaseItem(lease1, LeaseItemType.RENT, 1), newLeaseItem(lease1, LeaseItemType.RENT, 1), newLeaseItem(lease1, LeaseItemType.RENT, 2) ) ); } private LeaseItem newLeaseItem( Lease lease, LeaseItemType type, Integer sequence) { final LeaseItem li = new LeaseItem(); li.setLease(lease); li.setType(type); li.setSequence(sequence != null ? BigInteger.valueOf(sequence.longValue()) : null); return li; } } }