repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
appledong/JavaDesignPattern
JavaDesignPattern/src/com/dong/design/factory/factory_abstract/Wuqi_B.java
293
package com.dong.design.factory.factory_abstract; public class Wuqi_B implements Wuqi{ @Override public void installZidan(Zidan zidan) { System.out.println("装载B子弹"); } @Override public void shotZidan(Zidan zidan) { System.out.println("发射B子弹"); } }
apache-2.0
Shmilyz/Swap
app/src/main/java/com/shmily/tjz/swap/Fragment/SearchFragment.java
5620
package com.shmily.tjz.swap.Fragment; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.shmily.tjz.swap.Adapter.SearchHotAdapter; import com.shmily.tjz.swap.Adapter.SearchRecentAdapter; import com.shmily.tjz.swap.LitePal.Data; import com.shmily.tjz.swap.LitePal.Hot; import com.shmily.tjz.swap.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.litepal.crud.DataSupport; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; import java.util.ArrayList; import java.util.List; /** * Created by Shmily_Z on 2017/5/4. */ public class SearchFragment extends Fragment{ private View rootView; private Handler handler; final int WHAT_NEWS = 1 ; List<Hot> hot=new ArrayList<>(); List<Data> recent=new ArrayList<>(); public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.search_fragment, container, false); initview(); initv(); return rootView; } private void initv() { List<Data> count=DataSupport.select().find(Data.class); int counts=count.size(); if (counts>0){ Data lastData= DataSupport.findLast(Data.class); int last=lastData.getId(); if (last>5){ recent=DataSupport.limit(5).offset(last-5).find(Data.class); } else { recent=DataSupport.findAll(Data.class); } } final SearchRecentAdapter adapter=new SearchRecentAdapter(getActivity(),R.layout.hot_item,recent); ListView listView= (ListView) rootView.findViewById(R.id.recent_view); listView.setDivider(null); listView.setAdapter(adapter); } private void initview() { SharedPreferences pref=getActivity().getSharedPreferences("hot", getActivity().MODE_PRIVATE); boolean sql=pref.getBoolean("sql",false); if(sql) { hot=DataSupport.findAll(Hot.class); SearchHotAdapter adapter = new SearchHotAdapter(getActivity(), R.layout.hot_item, hot); ListView listView = (ListView) rootView.findViewById(R.id.list_view); listView.setDivider(null); listView.setAdapter(adapter); } else { handler = new Handler() { @Override public void handleMessage(Message msg) { // 负责接收Handler消息,并执行UI更新 // 判断消息的来源:通过消息的类型 what switch (msg.what) { case WHAT_NEWS: SearchHotAdapter adapter = new SearchHotAdapter(getActivity(), R.layout.hot_item, hot); ListView listView = (ListView) rootView.findViewById(R.id.list_view); listView.setDivider(null); listView.setAdapter(adapter); break; } } }; RequestParams params = new RequestParams("http://www.shmilyz.com/ForAndroidHttp/select.action"); String results = "select * from search"; params.addBodyParameter("uname", results); x.http().post(params, new Callback.CacheCallback<String>() { @Override public void onSuccess(String result) { try { JSONObject jsonobject = new JSONObject(result); JSONArray shoesArray = jsonobject.getJSONArray("result"); Gson gson = new Gson(); hot = gson.fromJson(String.valueOf(shoesArray), new TypeToken<List<Hot>>() { }.getType()); for (Hot hots : hot) { Hot data = new Hot(); data.setName(hots.getName()); data.save(); } SharedPreferences.Editor editor = getActivity().getSharedPreferences("hot", getActivity().MODE_PRIVATE).edit(); editor.putBoolean("sql", true); editor.apply(); Message msg = handler.obtainMessage(); // 设置消息内容(可选) // 设置消息类型 msg.what = WHAT_NEWS; // 发送消息 handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } @Override public boolean onCache(String result) { return false; } }); } } }
apache-2.0
ljmdbc7a/leetcode-java
src/main/java/com/ikouz/algorithm/leetcode/Array_283_MoveZeroes.java
1459
package com.ikouz.algorithm.leetcode; import com.ikouz.algorithm.leetcode.utils.TestUtil; /** * Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. * <p> * For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. * <p> * Note: * You must do this in-place without making a copy of the array. * Minimize the total number of operations. * * @author liujiaming * @since 2017/06/26 */ public class Array_283_MoveZeroes { public static void moveZeroes(int[] nums) { if (nums == null || nums.length == 1) { return; } int i = 0, j = 0; while (i < nums.length && j < nums.length) { while (i < nums.length && nums[i] != 0) { i++; } j = i; while (j < nums.length && nums[j] == 0) { j++; } if (i < nums.length && j < nums.length) { swap(nums, i, j); } } } private static void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } public static void main(String[] args) { // int[] intArr = TestUtil.buildIntArr("[0,1,0,3,12]"); int[] intArr = TestUtil.buildIntArr("[1,0]"); moveZeroes(intArr); TestUtil.printIntArr(intArr); } }
apache-2.0
joewoo999/selenium_webuitest
src/main/java/com/github/joseph/core/page/pageObject/commands/options/OptionByIndex.java
963
package com.github.joseph.core.page.pageObject.commands.options; import com.github.joseph.core.page.pageObject.PageElementType; import com.github.joseph.core.page.pageObject.function.OptionFunction; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.pagefactory.ElementLocator; import org.openqa.selenium.support.ui.Select; public class OptionByIndex implements OptionFunction<WebElement> { private ElementLocator locator; private int index; @Override public WebElement apply(ElementLocator locator,Object[] objects) { this.locator = locator; this.index = (int)objects[0]; WebElement element = PageElementType.SELECT.findAndAssertElementType(locator); new Select(element).selectByIndex(index); return element; } @Override public String toString() { return String.format("Select option with index:'%s' at element:%s.", index, locator); } }
apache-2.0
Shaunyl/shauni
src/main/java/com/fil/shauni/command/DatabaseCommandControl.java
2910
package com.fil.shauni.command; import com.fil.shauni.util.GeneralUtil; import com.fil.shauni.db.DbConnection; import com.fil.shauni.db.pool.DatabasePoolManager; import com.fil.shauni.mainframe.ui.CommandLinePresentation; import com.fil.shauni.util.Sysdate; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.sql.DataSource; import lombok.NonNull; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; /** * * @author Filippo Testino (filippo.testino@gmail.com) */ @Log4j2 @Component public abstract class DatabaseCommandControl extends Command.CommandAction { @Inject protected CommandLinePresentation cli; protected JdbcTemplate jdbc; private String host; private final List<DbConnection> dbcs = new ArrayList<>(); private DataSource dataSource; protected DatabasePoolManager databasePoolManager; @Autowired(required = true) public void setDatabasePoolManager(final @NonNull @Value("#{databasePoolManager}") DatabasePoolManager databasePoolManager) { this.databasePoolManager = databasePoolManager; } @Override public void run(int sid) { this.setConnections(configuration.getWorkset()); DbConnection dbc = dbcs.get(sid); databasePoolManager.configure(dbc.getUrl(), dbc.getUser(), dbc.getPasswd(), dbc.getHost(), dbc.getSid()); this.dataSource = databasePoolManager.getDataSource(); this.jdbc = new JdbcTemplate(dataSource); this.jdbc.setFetchSize(100); } @Override public void takedown() { try { this.databasePoolManager.close(); } catch (Exception e) { status.error(); log.error("Pool couldn't be closed.\n{}", e.getMessage()); } log.debug("Pool has been closed at " + Sysdate.now(Sysdate.TIMEONLY)); } private void setConnections(final List<String> urls) { for (String u : urls) { if ("".equals(u)) { log.info("Connection string not set (missing the '=' sign?). It will be skipped."); continue; } Map<String, String> map = GeneralUtil.parseConnectionString(u); if (map == null) { log.info("Connection string is not valid. It will be skipped."); continue; } String user = map.get("user").toUpperCase(); String password = map.get("password"); String sid = map.get("sid").toUpperCase(); host = map.get("host").toUpperCase(); DbConnection dbc = new DbConnection(u, user, password, sid, host); dbcs.add(dbc); } } }
apache-2.0
mstiehr-dev/BTApp
app/src/main/java/com/itc/mstiehr/btapp/ActionFoundReceiver.java
1997
package com.itc.mstiehr.btapp; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import java.util.ArrayList; /** * Created by MStiehr on 14.07.2015. */ public class ActionFoundReceiver extends BroadcastReceiver { private final static String TAG = ActionFoundReceiver.class.getSimpleName(); ArrayList<BluetoothDevice> btDeviceList; ProgressDialog pd; public ActionFoundReceiver(ArrayList<BluetoothDevice> btList) { btDeviceList = btList; } @Override public void onReceive (Context context, Intent intent) { if(null!=intent) { switch(intent.getAction()) { case BluetoothDevice.ACTION_FOUND: BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); btDeviceList.add(device); Log.d(TAG, "action: ACTION_FOUND" + " " + device.getName()); break; case BluetoothDevice.ACTION_UUID: Log.d(TAG, "action: ACTION_UUID"); break; case BluetoothAdapter.ACTION_DISCOVERY_STARTED: Log.d(TAG, "action: ACTION_DISCOVERY_STARTED"); pd = new ProgressDialog(context); pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); pd.setMessage("Scanning BT Network"); pd.show(); break; case BluetoothAdapter.ACTION_DISCOVERY_FINISHED: Log.d(TAG, "action: ACTION_DISCOVERY_FINISHED"); if(null!=pd) { pd.dismiss(); } break; default: break; } } } }
apache-2.0
qq54903099/atom-lang
src/main/java/com/github/obullxl/lang/biz/RightException.java
771
/** * Author: obullxl@gmail.com * Copyright (c) 2004-2013 All Rights Reserved. */ package com.github.obullxl.lang.biz; import java.util.List; /** * 权限异常 * * @author obullxl@gmail.com * @version $Id: RightException.java, V1.0.1 2013年12月15日 下午12:41:19 $ */ public class RightException extends RuntimeException { private static final long serialVersionUID = 2468373106783815600L; /** 权限码 */ private final List<String> rgtCodes; /** * CTOR */ public RightException(List<String> rgtCodes) { super("权限不足-" + rgtCodes); this.rgtCodes = rgtCodes; } // ~~~~~~~~~~~~~ getters and setters ~~~~~~~~~~~~~ // public List<String> getRgtCodes() { return rgtCodes; } }
apache-2.0
stevenhva/InfoLearn_OpenOLAT
src/main/java/org/olat/course/condition/interpreter/InRightGroupFunction.java
4031
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <hr> * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * This file has been modified by the OpenOLAT community. Changes are licensed * under the Apache 2.0 license as the original file. */ package org.olat.course.condition.interpreter; import java.util.List; import org.olat.core.CoreSpringFactory; import org.olat.core.id.Identity; import org.olat.core.util.StringHelper; import org.olat.course.editor.CourseEditorEnv; import org.olat.course.groupsandrights.CourseGroupManager; import org.olat.course.run.userview.UserCourseEnvironment; import org.olat.group.BusinessGroupService; /** * Description:<BR/> * Condition function inRightGroup() * * <P/> * Initial Date: Sep 15, 2004 * @author gnaegi */ public class InRightGroupFunction extends AbstractFunction { public static final String name = "inRightGroup"; /** * @param userCourseEnv */ public InRightGroupFunction(UserCourseEnvironment userCourseEnv) { super(userCourseEnv); } /** * @see com.neemsoft.jmep.FunctionCB#call(java.lang.Object[]) */ public Object call(Object[] inStack) { /* * argument check */ if (inStack.length > 1) { return handleException( new ArgumentParseException(ArgumentParseException.NEEDS_FEWER_ARGUMENTS, name, "", "error.fewerargs", "solution.provideone.groupname")); } else if (inStack.length < 1) { return handleException( new ArgumentParseException(ArgumentParseException.NEEDS_MORE_ARGUMENTS, name, "", "error.moreargs", "solution.provideone.groupname")); } /* * argument type check */ if (!(inStack[0] instanceof String)) return handleException( new ArgumentParseException(ArgumentParseException.WRONG_ARGUMENT_FORMAT, name, "", "error.argtype.groupnameexpected", "solution.example.name.infunction")); String groupName = (String)inStack[0]; /* * check reference integrity */ CourseEditorEnv cev = getUserCourseEnv().getCourseEditorEnv(); if (cev != null) { if (!cev.existsGroup(groupName)) { return handleException( new ArgumentParseException(ArgumentParseException.REFERENCE_NOT_FOUND, name, groupName, "error.notfound.name", "solution.checkgroupmanagement")); } // remember the reference to the node id for this condtion cev.addSoftReference("groupId", groupName); // return a valid value to continue with condition evaluation test return defaultValue(); } /* * the real function evaluation which is used during run time */ Identity ident = getUserCourseEnv().getIdentityEnvironment().getIdentity(); CourseGroupManager cgm = getUserCourseEnv().getCourseEnvironment().getCourseGroupManager(); if(StringHelper.isLong(groupName)) { Long groupKey = new Long(groupName); return cgm.isIdentityInGroup(ident, groupKey) ? ConditionInterpreter.INT_TRUE: ConditionInterpreter.INT_FALSE; } //TODO gm List<Long> groupKeys = CoreSpringFactory.getImpl(BusinessGroupService.class).toGroupKeys(groupName, cgm.getCourseResource()); if(!groupKeys.isEmpty()) { return cgm.isIdentityInGroup(ident, groupKeys.get(0)) ? ConditionInterpreter.INT_TRUE: ConditionInterpreter.INT_FALSE; } return ConditionInterpreter.INT_FALSE; } protected Object defaultValue() { return ConditionInterpreter.INT_TRUE; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/AWSCodePipeline.java
59461
/* * Copyright 2017-2022 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.codepipeline; import javax.annotation.Generated; import com.amazonaws.*; import com.amazonaws.regions.*; import com.amazonaws.services.codepipeline.model.*; /** * Interface for accessing CodePipeline. * <p> * <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from * {@link com.amazonaws.services.codepipeline.AbstractAWSCodePipeline} instead. * </p> * <p> * <fullname>AWS CodePipeline</fullname> * <p> * <b>Overview</b> * </p> * <p> * This is the AWS CodePipeline API Reference. This guide provides descriptions of the actions and data types for AWS * CodePipeline. Some functionality for your pipeline can only be configured through the API. For more information, see * the <a href="https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html">AWS CodePipeline User Guide</a>. * </p> * <p> * You can use the AWS CodePipeline API to work with pipelines, stages, actions, and transitions. * </p> * <p> * <i>Pipelines</i> are models of automated release processes. Each pipeline is uniquely named, and consists of stages, * actions, and transitions. * </p> * <p> * You can work with pipelines by calling: * </p> * <ul> * <li> * <p> * <a>CreatePipeline</a>, which creates a uniquely named pipeline. * </p> * </li> * <li> * <p> * <a>DeletePipeline</a>, which deletes the specified pipeline. * </p> * </li> * <li> * <p> * <a>GetPipeline</a>, which returns information about the pipeline structure and pipeline metadata, including the * pipeline Amazon Resource Name (ARN). * </p> * </li> * <li> * <p> * <a>GetPipelineExecution</a>, which returns information about a specific execution of a pipeline. * </p> * </li> * <li> * <p> * <a>GetPipelineState</a>, which returns information about the current state of the stages and actions of a pipeline. * </p> * </li> * <li> * <p> * <a>ListActionExecutions</a>, which returns action-level details for past executions. The details include full stage * and action-level details, including individual action duration, status, any errors that occurred during the * execution, and input and output artifact location details. * </p> * </li> * <li> * <p> * <a>ListPipelines</a>, which gets a summary of all of the pipelines associated with your account. * </p> * </li> * <li> * <p> * <a>ListPipelineExecutions</a>, which gets a summary of the most recent executions for a pipeline. * </p> * </li> * <li> * <p> * <a>StartPipelineExecution</a>, which runs the most recent revision of an artifact through the pipeline. * </p> * </li> * <li> * <p> * <a>StopPipelineExecution</a>, which stops the specified pipeline execution from continuing through the pipeline. * </p> * </li> * <li> * <p> * <a>UpdatePipeline</a>, which updates a pipeline with edits or changes to the structure of the pipeline. * </p> * </li> * </ul> * <p> * Pipelines include <i>stages</i>. Each stage contains one or more actions that must complete before the next stage * begins. A stage results in success or failure. If a stage fails, the pipeline stops at that stage and remains stopped * until either a new version of an artifact appears in the source location, or a user takes action to rerun the most * recent artifact through the pipeline. You can call <a>GetPipelineState</a>, which displays the status of a pipeline, * including the status of stages in the pipeline, or <a>GetPipeline</a>, which returns the entire structure of the * pipeline, including the stages of that pipeline. For more information about the structure of stages and actions, see * <a href="https://docs.aws.amazon.com/codepipeline/latest/userguide/pipeline-structure.html">AWS CodePipeline Pipeline * Structure Reference</a>. * </p> * <p> * Pipeline stages include <i>actions</i> that are categorized into categories such as source or build actions performed * in a stage of a pipeline. For example, you can use a source action to import artifacts into a pipeline from a source * such as Amazon S3. Like stages, you do not work with actions directly in most cases, but you do define and interact * with actions when working with pipeline operations such as <a>CreatePipeline</a> and <a>GetPipelineState</a>. Valid * action categories are: * </p> * <ul> * <li> * <p> * Source * </p> * </li> * <li> * <p> * Build * </p> * </li> * <li> * <p> * Test * </p> * </li> * <li> * <p> * Deploy * </p> * </li> * <li> * <p> * Approval * </p> * </li> * <li> * <p> * Invoke * </p> * </li> * </ul> * <p> * Pipelines also include <i>transitions</i>, which allow the transition of artifacts from one stage to the next in a * pipeline after the actions in one stage complete. * </p> * <p> * You can work with transitions by calling: * </p> * <ul> * <li> * <p> * <a>DisableStageTransition</a>, which prevents artifacts from transitioning to the next stage in a pipeline. * </p> * </li> * <li> * <p> * <a>EnableStageTransition</a>, which enables transition of artifacts between stages in a pipeline. * </p> * </li> * </ul> * <p> * <b>Using the API to integrate with AWS CodePipeline</b> * </p> * <p> * For third-party integrators or developers who want to create their own integrations with AWS CodePipeline, the * expected sequence varies from the standard API user. To integrate with AWS CodePipeline, developers need to work with * the following items: * </p> * <p> * <b>Jobs</b>, which are instances of an action. For example, a job for a source action might import a revision of an * artifact from a source. * </p> * <p> * You can work with jobs by calling: * </p> * <ul> * <li> * <p> * <a>AcknowledgeJob</a>, which confirms whether a job worker has received the specified job. * </p> * </li> * <li> * <p> * <a>GetJobDetails</a>, which returns the details of a job. * </p> * </li> * <li> * <p> * <a>PollForJobs</a>, which determines whether there are any jobs to act on. * </p> * </li> * <li> * <p> * <a>PutJobFailureResult</a>, which provides details of a job failure. * </p> * </li> * <li> * <p> * <a>PutJobSuccessResult</a>, which provides details of a job success. * </p> * </li> * </ul> * <p> * <b>Third party jobs</b>, which are instances of an action created by a partner action and integrated into AWS * CodePipeline. Partner actions are created by members of the AWS Partner Network. * </p> * <p> * You can work with third party jobs by calling: * </p> * <ul> * <li> * <p> * <a>AcknowledgeThirdPartyJob</a>, which confirms whether a job worker has received the specified job. * </p> * </li> * <li> * <p> * <a>GetThirdPartyJobDetails</a>, which requests the details of a job for a partner action. * </p> * </li> * <li> * <p> * <a>PollForThirdPartyJobs</a>, which determines whether there are any jobs to act on. * </p> * </li> * <li> * <p> * <a>PutThirdPartyJobFailureResult</a>, which provides details of a job failure. * </p> * </li> * <li> * <p> * <a>PutThirdPartyJobSuccessResult</a>, which provides details of a job success. * </p> * </li> * </ul> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public interface AWSCodePipeline { /** * The region metadata service name for computing region endpoints. You can use this value to retrieve metadata * (such as supported regions) of the service. * * @see RegionUtils#getRegionsForService(String) */ String ENDPOINT_PREFIX = "codepipeline"; /** * Overrides the default endpoint for this client ("https://codepipeline.us-east-1.amazonaws.com"). Callers can use * this method to control which AWS region they want to work with. * <p> * Callers can pass in just the endpoint (ex: "codepipeline.us-east-1.amazonaws.com") or a full URL, including the * protocol (ex: "https://codepipeline.us-east-1.amazonaws.com"). If the protocol is not specified here, the default * protocol from this client's {@link ClientConfiguration} will be used, which by default is HTTPS. * <p> * For more information on using AWS regions with the AWS SDK for Java, and a complete list of all available * endpoints for all AWS services, see: <a href= * "https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#region-selection-choose-endpoint" * > https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#region-selection- * choose-endpoint</a> * <p> * <b>This method is not threadsafe. An endpoint should be configured when the client is created and before any * service requests are made. Changing it afterwards creates inevitable race conditions for any service requests in * transit or retrying.</b> * * @param endpoint * The endpoint (ex: "codepipeline.us-east-1.amazonaws.com") or a full URL, including the protocol (ex: * "https://codepipeline.us-east-1.amazonaws.com") of the region specific AWS endpoint this client will * communicate with. * @deprecated use {@link AwsClientBuilder#setEndpointConfiguration(AwsClientBuilder.EndpointConfiguration)} for * example: * {@code builder.setEndpointConfiguration(new EndpointConfiguration(endpoint, signingRegion));} */ @Deprecated void setEndpoint(String endpoint); /** * An alternative to {@link AWSCodePipeline#setEndpoint(String)}, sets the regional endpoint for this client's * service calls. Callers can use this method to control which AWS region they want to work with. * <p> * By default, all service endpoints in all regions use the https protocol. To use http instead, specify it in the * {@link ClientConfiguration} supplied at construction. * <p> * <b>This method is not threadsafe. A region should be configured when the client is created and before any service * requests are made. Changing it afterwards creates inevitable race conditions for any service requests in transit * or retrying.</b> * * @param region * The region this client will communicate with. See {@link Region#getRegion(com.amazonaws.regions.Regions)} * for accessing a given region. Must not be null and must be a region where the service is available. * * @see Region#getRegion(com.amazonaws.regions.Regions) * @see Region#createClient(Class, com.amazonaws.auth.AWSCredentialsProvider, ClientConfiguration) * @see Region#isServiceSupported(String) * @deprecated use {@link AwsClientBuilder#setRegion(String)} */ @Deprecated void setRegion(Region region); /** * <p> * Returns information about a specified job and whether that job has been received by the job worker. Used for * custom actions only. * </p> * * @param acknowledgeJobRequest * Represents the input of an AcknowledgeJob action. * @return Result of the AcknowledgeJob operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws InvalidNonceException * The nonce was specified in an invalid format. * @throws JobNotFoundException * The job was specified in an invalid format or cannot be found. * @sample AWSCodePipeline.AcknowledgeJob * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeJob" target="_top">AWS * API Documentation</a> */ AcknowledgeJobResult acknowledgeJob(AcknowledgeJobRequest acknowledgeJobRequest); /** * <p> * Confirms a job worker has received the specified job. Used for partner actions only. * </p> * * @param acknowledgeThirdPartyJobRequest * Represents the input of an AcknowledgeThirdPartyJob action. * @return Result of the AcknowledgeThirdPartyJob operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws InvalidNonceException * The nonce was specified in an invalid format. * @throws JobNotFoundException * The job was specified in an invalid format or cannot be found. * @throws InvalidClientTokenException * The client token was specified in an invalid format * @sample AWSCodePipeline.AcknowledgeThirdPartyJob * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeThirdPartyJob" * target="_top">AWS API Documentation</a> */ AcknowledgeThirdPartyJobResult acknowledgeThirdPartyJob(AcknowledgeThirdPartyJobRequest acknowledgeThirdPartyJobRequest); /** * <p> * Creates a new custom action that can be used in all pipelines associated with the AWS account. Only used for * custom actions. * </p> * * @param createCustomActionTypeRequest * Represents the input of a CreateCustomActionType operation. * @return Result of the CreateCustomActionType operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws LimitExceededException * The number of pipelines associated with the AWS account has exceeded the limit allowed for the account. * @throws TooManyTagsException * The tags limit for a resource has been exceeded. * @throws InvalidTagsException * The specified resource tags are invalid. * @throws ConcurrentModificationException * Unable to modify the tag due to a simultaneous update request. * @sample AWSCodePipeline.CreateCustomActionType * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreateCustomActionType" * target="_top">AWS API Documentation</a> */ CreateCustomActionTypeResult createCustomActionType(CreateCustomActionTypeRequest createCustomActionTypeRequest); /** * <p> * Creates a pipeline. * </p> * <note> * <p> * In the pipeline structure, you must include either <code>artifactStore</code> or <code>artifactStores</code> in * your pipeline, but you cannot use both. If you create a cross-region action in your pipeline, you must use * <code>artifactStores</code>. * </p> * </note> * * @param createPipelineRequest * Represents the input of a <code>CreatePipeline</code> action. * @return Result of the CreatePipeline operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws PipelineNameInUseException * The specified pipeline name is already in use. * @throws InvalidStageDeclarationException * The stage declaration was specified in an invalid format. * @throws InvalidActionDeclarationException * The action declaration was specified in an invalid format. * @throws InvalidBlockerDeclarationException * Reserved for future use. * @throws InvalidStructureException * The structure was specified in an invalid format. * @throws LimitExceededException * The number of pipelines associated with the AWS account has exceeded the limit allowed for the account. * @throws TooManyTagsException * The tags limit for a resource has been exceeded. * @throws InvalidTagsException * The specified resource tags are invalid. * @throws ConcurrentModificationException * Unable to modify the tag due to a simultaneous update request. * @sample AWSCodePipeline.CreatePipeline * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreatePipeline" target="_top">AWS * API Documentation</a> */ CreatePipelineResult createPipeline(CreatePipelineRequest createPipelineRequest); /** * <p> * Marks a custom action as deleted. <code>PollForJobs</code> for the custom action fails after the action is marked * for deletion. Used for custom actions only. * </p> * <important> * <p> * To re-create a custom action after it has been deleted you must use a string in the version field that has never * been used before. This string can be an incremented version number, for example. To restore a deleted custom * action, use a JSON file that is identical to the deleted action, including the original string in the version * field. * </p> * </important> * * @param deleteCustomActionTypeRequest * Represents the input of a <code>DeleteCustomActionType</code> operation. The custom action will be marked * as deleted. * @return Result of the DeleteCustomActionType operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ConcurrentModificationException * Unable to modify the tag due to a simultaneous update request. * @sample AWSCodePipeline.DeleteCustomActionType * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeleteCustomActionType" * target="_top">AWS API Documentation</a> */ DeleteCustomActionTypeResult deleteCustomActionType(DeleteCustomActionTypeRequest deleteCustomActionTypeRequest); /** * <p> * Deletes the specified pipeline. * </p> * * @param deletePipelineRequest * Represents the input of a <code>DeletePipeline</code> action. * @return Result of the DeletePipeline operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ConcurrentModificationException * Unable to modify the tag due to a simultaneous update request. * @sample AWSCodePipeline.DeletePipeline * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeletePipeline" target="_top">AWS * API Documentation</a> */ DeletePipelineResult deletePipeline(DeletePipelineRequest deletePipelineRequest); /** * <p> * Deletes a previously created webhook by name. Deleting the webhook stops AWS CodePipeline from starting a * pipeline every time an external event occurs. The API returns successfully when trying to delete a webhook that * is already deleted. If a deleted webhook is re-created by calling PutWebhook with the same name, it will have a * different URL. * </p> * * @param deleteWebhookRequest * @return Result of the DeleteWebhook operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ConcurrentModificationException * Unable to modify the tag due to a simultaneous update request. * @sample AWSCodePipeline.DeleteWebhook * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeleteWebhook" target="_top">AWS API * Documentation</a> */ DeleteWebhookResult deleteWebhook(DeleteWebhookRequest deleteWebhookRequest); /** * <p> * Removes the connection between the webhook that was created by CodePipeline and the external tool with events to * be detected. Currently supported only for webhooks that target an action type of GitHub. * </p> * * @param deregisterWebhookWithThirdPartyRequest * @return Result of the DeregisterWebhookWithThirdParty operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws WebhookNotFoundException * The specified webhook was entered in an invalid format or cannot be found. * @sample AWSCodePipeline.DeregisterWebhookWithThirdParty * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeregisterWebhookWithThirdParty" * target="_top">AWS API Documentation</a> */ DeregisterWebhookWithThirdPartyResult deregisterWebhookWithThirdParty(DeregisterWebhookWithThirdPartyRequest deregisterWebhookWithThirdPartyRequest); /** * <p> * Prevents artifacts in a pipeline from transitioning to the next stage in the pipeline. * </p> * * @param disableStageTransitionRequest * Represents the input of a <code>DisableStageTransition</code> action. * @return Result of the DisableStageTransition operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws StageNotFoundException * The stage was specified in an invalid format or cannot be found. * @sample AWSCodePipeline.DisableStageTransition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DisableStageTransition" * target="_top">AWS API Documentation</a> */ DisableStageTransitionResult disableStageTransition(DisableStageTransitionRequest disableStageTransitionRequest); /** * <p> * Enables artifacts in a pipeline to transition to a stage in a pipeline. * </p> * * @param enableStageTransitionRequest * Represents the input of an <code>EnableStageTransition</code> action. * @return Result of the EnableStageTransition operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws StageNotFoundException * The stage was specified in an invalid format or cannot be found. * @sample AWSCodePipeline.EnableStageTransition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/EnableStageTransition" * target="_top">AWS API Documentation</a> */ EnableStageTransitionResult enableStageTransition(EnableStageTransitionRequest enableStageTransitionRequest); /** * <p> * Returns information about an action type created for an external provider, where the action is to be used by * customers of the external provider. The action can be created with any supported integration model. * </p> * * @param getActionTypeRequest * @return Result of the GetActionType operation returned by the service. * @throws ActionTypeNotFoundException * The specified action type cannot be found. * @throws ValidationException * The validation was specified in an invalid format. * @sample AWSCodePipeline.GetActionType * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetActionType" target="_top">AWS API * Documentation</a> */ GetActionTypeResult getActionType(GetActionTypeRequest getActionTypeRequest); /** * <p> * Returns information about a job. Used for custom actions only. * </p> * <important> * <p> * When this API is called, AWS CodePipeline returns temporary credentials for the S3 bucket used to store artifacts * for the pipeline, if the action requires access to that S3 bucket for input or output artifacts. This API also * returns any secret values defined for the action. * </p> * </important> * * @param getJobDetailsRequest * Represents the input of a <code>GetJobDetails</code> action. * @return Result of the GetJobDetails operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws JobNotFoundException * The job was specified in an invalid format or cannot be found. * @sample AWSCodePipeline.GetJobDetails * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetJobDetails" target="_top">AWS API * Documentation</a> */ GetJobDetailsResult getJobDetails(GetJobDetailsRequest getJobDetailsRequest); /** * <p> * Returns the metadata, structure, stages, and actions of a pipeline. Can be used to return the entire structure of * a pipeline in JSON format, which can then be modified and used to update the pipeline structure with * <a>UpdatePipeline</a>. * </p> * * @param getPipelineRequest * Represents the input of a <code>GetPipeline</code> action. * @return Result of the GetPipeline operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws PipelineVersionNotFoundException * The pipeline version was specified in an invalid format or cannot be found. * @sample AWSCodePipeline.GetPipeline * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipeline" target="_top">AWS API * Documentation</a> */ GetPipelineResult getPipeline(GetPipelineRequest getPipelineRequest); /** * <p> * Returns information about an execution of a pipeline, including details about artifacts, the pipeline execution * ID, and the name, version, and status of the pipeline. * </p> * * @param getPipelineExecutionRequest * Represents the input of a <code>GetPipelineExecution</code> action. * @return Result of the GetPipelineExecution operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws PipelineExecutionNotFoundException * The pipeline execution was specified in an invalid format or cannot be found, or an execution ID does not * belong to the specified pipeline. * @sample AWSCodePipeline.GetPipelineExecution * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineExecution" * target="_top">AWS API Documentation</a> */ GetPipelineExecutionResult getPipelineExecution(GetPipelineExecutionRequest getPipelineExecutionRequest); /** * <p> * Returns information about the state of a pipeline, including the stages and actions. * </p> * <note> * <p> * Values returned in the <code>revisionId</code> and <code>revisionUrl</code> fields indicate the source revision * information, such as the commit ID, for the current state. * </p> * </note> * * @param getPipelineStateRequest * Represents the input of a <code>GetPipelineState</code> action. * @return Result of the GetPipelineState operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @sample AWSCodePipeline.GetPipelineState * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineState" target="_top">AWS * API Documentation</a> */ GetPipelineStateResult getPipelineState(GetPipelineStateRequest getPipelineStateRequest); /** * <p> * Requests the details of a job for a third party action. Used for partner actions only. * </p> * <important> * <p> * When this API is called, AWS CodePipeline returns temporary credentials for the S3 bucket used to store artifacts * for the pipeline, if the action requires access to that S3 bucket for input or output artifacts. This API also * returns any secret values defined for the action. * </p> * </important> * * @param getThirdPartyJobDetailsRequest * Represents the input of a <code>GetThirdPartyJobDetails</code> action. * @return Result of the GetThirdPartyJobDetails operation returned by the service. * @throws JobNotFoundException * The job was specified in an invalid format or cannot be found. * @throws ValidationException * The validation was specified in an invalid format. * @throws InvalidClientTokenException * The client token was specified in an invalid format * @throws InvalidJobException * The job was specified in an invalid format or cannot be found. * @sample AWSCodePipeline.GetThirdPartyJobDetails * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetThirdPartyJobDetails" * target="_top">AWS API Documentation</a> */ GetThirdPartyJobDetailsResult getThirdPartyJobDetails(GetThirdPartyJobDetailsRequest getThirdPartyJobDetailsRequest); /** * <p> * Lists the action executions that have occurred in a pipeline. * </p> * * @param listActionExecutionsRequest * @return Result of the ListActionExecutions operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws InvalidNextTokenException * The next token was specified in an invalid format. Make sure that the next token you provide is the token * returned by a previous call. * @throws PipelineExecutionNotFoundException * The pipeline execution was specified in an invalid format or cannot be found, or an execution ID does not * belong to the specified pipeline. * @sample AWSCodePipeline.ListActionExecutions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionExecutions" * target="_top">AWS API Documentation</a> */ ListActionExecutionsResult listActionExecutions(ListActionExecutionsRequest listActionExecutionsRequest); /** * <p> * Gets a summary of all AWS CodePipeline action types associated with your account. * </p> * * @param listActionTypesRequest * Represents the input of a <code>ListActionTypes</code> action. * @return Result of the ListActionTypes operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws InvalidNextTokenException * The next token was specified in an invalid format. Make sure that the next token you provide is the token * returned by a previous call. * @sample AWSCodePipeline.ListActionTypes * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionTypes" target="_top">AWS * API Documentation</a> */ ListActionTypesResult listActionTypes(ListActionTypesRequest listActionTypesRequest); /** * <p> * Gets a summary of the most recent executions for a pipeline. * </p> * * @param listPipelineExecutionsRequest * Represents the input of a <code>ListPipelineExecutions</code> action. * @return Result of the ListPipelineExecutions operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws InvalidNextTokenException * The next token was specified in an invalid format. Make sure that the next token you provide is the token * returned by a previous call. * @sample AWSCodePipeline.ListPipelineExecutions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelineExecutions" * target="_top">AWS API Documentation</a> */ ListPipelineExecutionsResult listPipelineExecutions(ListPipelineExecutionsRequest listPipelineExecutionsRequest); /** * <p> * Gets a summary of all of the pipelines associated with your account. * </p> * * @param listPipelinesRequest * Represents the input of a <code>ListPipelines</code> action. * @return Result of the ListPipelines operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws InvalidNextTokenException * The next token was specified in an invalid format. Make sure that the next token you provide is the token * returned by a previous call. * @sample AWSCodePipeline.ListPipelines * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelines" target="_top">AWS API * Documentation</a> */ ListPipelinesResult listPipelines(ListPipelinesRequest listPipelinesRequest); /** * <p> * Gets the set of key-value pairs (metadata) that are used to manage the resource. * </p> * * @param listTagsForResourceRequest * @return Result of the ListTagsForResource operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ResourceNotFoundException * The resource was specified in an invalid format. * @throws InvalidNextTokenException * The next token was specified in an invalid format. Make sure that the next token you provide is the token * returned by a previous call. * @throws InvalidArnException * The specified resource ARN is invalid. * @sample AWSCodePipeline.ListTagsForResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListTagsForResource" * target="_top">AWS API Documentation</a> */ ListTagsForResourceResult listTagsForResource(ListTagsForResourceRequest listTagsForResourceRequest); /** * <p> * Gets a listing of all the webhooks in this AWS Region for this account. The output lists all webhooks and * includes the webhook URL and ARN and the configuration for each webhook. * </p> * * @param listWebhooksRequest * @return Result of the ListWebhooks operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws InvalidNextTokenException * The next token was specified in an invalid format. Make sure that the next token you provide is the token * returned by a previous call. * @sample AWSCodePipeline.ListWebhooks * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListWebhooks" target="_top">AWS API * Documentation</a> */ ListWebhooksResult listWebhooks(ListWebhooksRequest listWebhooksRequest); /** * <p> * Returns information about any jobs for AWS CodePipeline to act on. <code>PollForJobs</code> is valid only for * action types with "Custom" in the owner field. If the action type contains "AWS" or "ThirdParty" in the owner * field, the <code>PollForJobs</code> action returns an error. * </p> * <important> * <p> * When this API is called, AWS CodePipeline returns temporary credentials for the S3 bucket used to store artifacts * for the pipeline, if the action requires access to that S3 bucket for input or output artifacts. This API also * returns any secret values defined for the action. * </p> * </important> * * @param pollForJobsRequest * Represents the input of a <code>PollForJobs</code> action. * @return Result of the PollForJobs operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ActionTypeNotFoundException * The specified action type cannot be found. * @sample AWSCodePipeline.PollForJobs * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForJobs" target="_top">AWS API * Documentation</a> */ PollForJobsResult pollForJobs(PollForJobsRequest pollForJobsRequest); /** * <p> * Determines whether there are any third party jobs for a job worker to act on. Used for partner actions only. * </p> * <important> * <p> * When this API is called, AWS CodePipeline returns temporary credentials for the S3 bucket used to store artifacts * for the pipeline, if the action requires access to that S3 bucket for input or output artifacts. * </p> * </important> * * @param pollForThirdPartyJobsRequest * Represents the input of a <code>PollForThirdPartyJobs</code> action. * @return Result of the PollForThirdPartyJobs operation returned by the service. * @throws ActionTypeNotFoundException * The specified action type cannot be found. * @throws ValidationException * The validation was specified in an invalid format. * @sample AWSCodePipeline.PollForThirdPartyJobs * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForThirdPartyJobs" * target="_top">AWS API Documentation</a> */ PollForThirdPartyJobsResult pollForThirdPartyJobs(PollForThirdPartyJobsRequest pollForThirdPartyJobsRequest); /** * <p> * Provides information to AWS CodePipeline about new revisions to a source. * </p> * * @param putActionRevisionRequest * Represents the input of a <code>PutActionRevision</code> action. * @return Result of the PutActionRevision operation returned by the service. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws StageNotFoundException * The stage was specified in an invalid format or cannot be found. * @throws ActionNotFoundException * The specified action cannot be found. * @throws ValidationException * The validation was specified in an invalid format. * @sample AWSCodePipeline.PutActionRevision * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutActionRevision" target="_top">AWS * API Documentation</a> */ PutActionRevisionResult putActionRevision(PutActionRevisionRequest putActionRevisionRequest); /** * <p> * Provides the response to a manual approval request to AWS CodePipeline. Valid responses include Approved and * Rejected. * </p> * * @param putApprovalResultRequest * Represents the input of a <code>PutApprovalResult</code> action. * @return Result of the PutApprovalResult operation returned by the service. * @throws InvalidApprovalTokenException * The approval request already received a response or has expired. * @throws ApprovalAlreadyCompletedException * The approval action has already been approved or rejected. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws StageNotFoundException * The stage was specified in an invalid format or cannot be found. * @throws ActionNotFoundException * The specified action cannot be found. * @throws ValidationException * The validation was specified in an invalid format. * @sample AWSCodePipeline.PutApprovalResult * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutApprovalResult" target="_top">AWS * API Documentation</a> */ PutApprovalResultResult putApprovalResult(PutApprovalResultRequest putApprovalResultRequest); /** * <p> * Represents the failure of a job as returned to the pipeline by a job worker. Used for custom actions only. * </p> * * @param putJobFailureResultRequest * Represents the input of a <code>PutJobFailureResult</code> action. * @return Result of the PutJobFailureResult operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws JobNotFoundException * The job was specified in an invalid format or cannot be found. * @throws InvalidJobStateException * The job state was specified in an invalid format. * @sample AWSCodePipeline.PutJobFailureResult * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobFailureResult" * target="_top">AWS API Documentation</a> */ PutJobFailureResultResult putJobFailureResult(PutJobFailureResultRequest putJobFailureResultRequest); /** * <p> * Represents the success of a job as returned to the pipeline by a job worker. Used for custom actions only. * </p> * * @param putJobSuccessResultRequest * Represents the input of a <code>PutJobSuccessResult</code> action. * @return Result of the PutJobSuccessResult operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws JobNotFoundException * The job was specified in an invalid format or cannot be found. * @throws InvalidJobStateException * The job state was specified in an invalid format. * @throws OutputVariablesSizeExceededException * Exceeded the total size limit for all variables in the pipeline. * @sample AWSCodePipeline.PutJobSuccessResult * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobSuccessResult" * target="_top">AWS API Documentation</a> */ PutJobSuccessResultResult putJobSuccessResult(PutJobSuccessResultRequest putJobSuccessResultRequest); /** * <p> * Represents the failure of a third party job as returned to the pipeline by a job worker. Used for partner actions * only. * </p> * * @param putThirdPartyJobFailureResultRequest * Represents the input of a <code>PutThirdPartyJobFailureResult</code> action. * @return Result of the PutThirdPartyJobFailureResult operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws JobNotFoundException * The job was specified in an invalid format or cannot be found. * @throws InvalidJobStateException * The job state was specified in an invalid format. * @throws InvalidClientTokenException * The client token was specified in an invalid format * @sample AWSCodePipeline.PutThirdPartyJobFailureResult * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobFailureResult" * target="_top">AWS API Documentation</a> */ PutThirdPartyJobFailureResultResult putThirdPartyJobFailureResult(PutThirdPartyJobFailureResultRequest putThirdPartyJobFailureResultRequest); /** * <p> * Represents the success of a third party job as returned to the pipeline by a job worker. Used for partner actions * only. * </p> * * @param putThirdPartyJobSuccessResultRequest * Represents the input of a <code>PutThirdPartyJobSuccessResult</code> action. * @return Result of the PutThirdPartyJobSuccessResult operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws JobNotFoundException * The job was specified in an invalid format or cannot be found. * @throws InvalidJobStateException * The job state was specified in an invalid format. * @throws InvalidClientTokenException * The client token was specified in an invalid format * @sample AWSCodePipeline.PutThirdPartyJobSuccessResult * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobSuccessResult" * target="_top">AWS API Documentation</a> */ PutThirdPartyJobSuccessResultResult putThirdPartyJobSuccessResult(PutThirdPartyJobSuccessResultRequest putThirdPartyJobSuccessResultRequest); /** * <p> * Defines a webhook and returns a unique webhook URL generated by CodePipeline. This URL can be supplied to third * party source hosting providers to call every time there's a code change. When CodePipeline receives a POST * request on this URL, the pipeline defined in the webhook is started as long as the POST request satisfied the * authentication and filtering requirements supplied when defining the webhook. RegisterWebhookWithThirdParty and * DeregisterWebhookWithThirdParty APIs can be used to automatically configure supported third parties to call the * generated webhook URL. * </p> * * @param putWebhookRequest * @return Result of the PutWebhook operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws LimitExceededException * The number of pipelines associated with the AWS account has exceeded the limit allowed for the account. * @throws InvalidWebhookFilterPatternException * The specified event filter rule is in an invalid format. * @throws InvalidWebhookAuthenticationParametersException * The specified authentication type is in an invalid format. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws TooManyTagsException * The tags limit for a resource has been exceeded. * @throws InvalidTagsException * The specified resource tags are invalid. * @throws ConcurrentModificationException * Unable to modify the tag due to a simultaneous update request. * @sample AWSCodePipeline.PutWebhook * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutWebhook" target="_top">AWS API * Documentation</a> */ PutWebhookResult putWebhook(PutWebhookRequest putWebhookRequest); /** * <p> * Configures a connection between the webhook that was created and the external tool with events to be detected. * </p> * * @param registerWebhookWithThirdPartyRequest * @return Result of the RegisterWebhookWithThirdParty operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws WebhookNotFoundException * The specified webhook was entered in an invalid format or cannot be found. * @sample AWSCodePipeline.RegisterWebhookWithThirdParty * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/RegisterWebhookWithThirdParty" * target="_top">AWS API Documentation</a> */ RegisterWebhookWithThirdPartyResult registerWebhookWithThirdParty(RegisterWebhookWithThirdPartyRequest registerWebhookWithThirdPartyRequest); /** * <p> * Resumes the pipeline execution by retrying the last failed actions in a stage. You can retry a stage immediately * if any of the actions in the stage fail. When you retry, all actions that are still in progress continue working, * and failed actions are triggered again. * </p> * * @param retryStageExecutionRequest * Represents the input of a <code>RetryStageExecution</code> action. * @return Result of the RetryStageExecution operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ConflictException * Your request cannot be handled because the pipeline is busy handling ongoing activities. Try again later. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws StageNotFoundException * The stage was specified in an invalid format or cannot be found. * @throws StageNotRetryableException * Unable to retry. The pipeline structure or stage state might have changed while actions awaited retry, or * the stage contains no failed actions. * @throws NotLatestPipelineExecutionException * The stage has failed in a later run of the pipeline and the pipelineExecutionId associated with the * request is out of date. * @sample AWSCodePipeline.RetryStageExecution * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/RetryStageExecution" * target="_top">AWS API Documentation</a> */ RetryStageExecutionResult retryStageExecution(RetryStageExecutionRequest retryStageExecutionRequest); /** * <p> * Starts the specified pipeline. Specifically, it begins processing the latest commit to the source location * specified as part of the pipeline. * </p> * * @param startPipelineExecutionRequest * Represents the input of a <code>StartPipelineExecution</code> action. * @return Result of the StartPipelineExecution operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ConflictException * Your request cannot be handled because the pipeline is busy handling ongoing activities. Try again later. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @sample AWSCodePipeline.StartPipelineExecution * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StartPipelineExecution" * target="_top">AWS API Documentation</a> */ StartPipelineExecutionResult startPipelineExecution(StartPipelineExecutionRequest startPipelineExecutionRequest); /** * <p> * Stops the specified pipeline execution. You choose to either stop the pipeline execution by completing * in-progress actions without starting subsequent actions, or by abandoning in-progress actions. While completing * or abandoning in-progress actions, the pipeline execution is in a <code>Stopping</code> state. After all * in-progress actions are completed or abandoned, the pipeline execution is in a <code>Stopped</code> state. * </p> * * @param stopPipelineExecutionRequest * @return Result of the StopPipelineExecution operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ConflictException * Your request cannot be handled because the pipeline is busy handling ongoing activities. Try again later. * @throws PipelineNotFoundException * The pipeline was specified in an invalid format or cannot be found. * @throws PipelineExecutionNotStoppableException * Unable to stop the pipeline execution. The execution might already be in a <code>Stopped</code> state, or * it might no longer be in progress. * @throws DuplicatedStopRequestException * The pipeline execution is already in a <code>Stopping</code> state. If you already chose to stop and * wait, you cannot make that request again. You can choose to stop and abandon now, but be aware that this * option can lead to failed tasks or out of sequence tasks. If you already chose to stop and abandon, you * cannot make that request again. * @sample AWSCodePipeline.StopPipelineExecution * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StopPipelineExecution" * target="_top">AWS API Documentation</a> */ StopPipelineExecutionResult stopPipelineExecution(StopPipelineExecutionRequest stopPipelineExecutionRequest); /** * <p> * Adds to or modifies the tags of the given resource. Tags are metadata that can be used to manage a resource. * </p> * * @param tagResourceRequest * @return Result of the TagResource operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ResourceNotFoundException * The resource was specified in an invalid format. * @throws InvalidArnException * The specified resource ARN is invalid. * @throws TooManyTagsException * The tags limit for a resource has been exceeded. * @throws InvalidTagsException * The specified resource tags are invalid. * @throws ConcurrentModificationException * Unable to modify the tag due to a simultaneous update request. * @sample AWSCodePipeline.TagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/TagResource" target="_top">AWS API * Documentation</a> */ TagResourceResult tagResource(TagResourceRequest tagResourceRequest); /** * <p> * Removes tags from an AWS resource. * </p> * * @param untagResourceRequest * @return Result of the UntagResource operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws ResourceNotFoundException * The resource was specified in an invalid format. * @throws InvalidArnException * The specified resource ARN is invalid. * @throws InvalidTagsException * The specified resource tags are invalid. * @throws ConcurrentModificationException * Unable to modify the tag due to a simultaneous update request. * @sample AWSCodePipeline.UntagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UntagResource" target="_top">AWS API * Documentation</a> */ UntagResourceResult untagResource(UntagResourceRequest untagResourceRequest); /** * <p> * Updates an action type that was created with any supported integration model, where the action type is to be used * by customers of the action type provider. Use a JSON file with the action definition and * <code>UpdateActionType</code> to provide the full structure. * </p> * * @param updateActionTypeRequest * @return Result of the UpdateActionType operation returned by the service. * @throws RequestFailedException * The request failed because of an unknown error, exception, or failure. * @throws ValidationException * The validation was specified in an invalid format. * @throws ActionTypeNotFoundException * The specified action type cannot be found. * @sample AWSCodePipeline.UpdateActionType * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UpdateActionType" target="_top">AWS * API Documentation</a> */ UpdateActionTypeResult updateActionType(UpdateActionTypeRequest updateActionTypeRequest); /** * <p> * Updates a specified pipeline with edits or changes to its structure. Use a JSON file with the pipeline structure * and <code>UpdatePipeline</code> to provide the full structure of the pipeline. Updating the pipeline increases * the version number of the pipeline by 1. * </p> * * @param updatePipelineRequest * Represents the input of an <code>UpdatePipeline</code> action. * @return Result of the UpdatePipeline operation returned by the service. * @throws ValidationException * The validation was specified in an invalid format. * @throws InvalidStageDeclarationException * The stage declaration was specified in an invalid format. * @throws InvalidActionDeclarationException * The action declaration was specified in an invalid format. * @throws InvalidBlockerDeclarationException * Reserved for future use. * @throws InvalidStructureException * The structure was specified in an invalid format. * @throws LimitExceededException * The number of pipelines associated with the AWS account has exceeded the limit allowed for the account. * @sample AWSCodePipeline.UpdatePipeline * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UpdatePipeline" target="_top">AWS * API Documentation</a> */ UpdatePipelineResult updatePipeline(UpdatePipelineRequest updatePipelineRequest); /** * Shuts down this client object, releasing any resources that might be held open. This is an optional method, and * callers are not expected to call it, but can if they want to explicitly release any open resources. Once a client * has been shutdown, it should not be used to make any more requests. */ void shutdown(); /** * Returns additional metadata for a previously executed successful request, typically used for debugging issues * where a service isn't acting as expected. This data isn't considered part of the result data returned by an * operation, so it's available through this separate, diagnostic interface. * <p> * Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic * information for an executed request, you should use this method to retrieve it as soon as possible after * executing a request. * * @param request * The originally executed request. * * @return The response metadata for the specified request, or null if none is available. */ ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request); }
apache-2.0
vmuzikar/keycloak
model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanOAuth2DeviceTokenStoreProviderFactory.java
2195
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.models.sessions.infinispan; import org.infinispan.commons.api.BasicCache; import org.keycloak.Config; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.OAuth2DeviceTokenStoreProvider; import org.keycloak.models.OAuth2DeviceTokenStoreProviderFactory; import org.keycloak.models.sessions.infinispan.entities.ActionTokenValueEntity; import java.util.function.Supplier; /** * @author <a href="mailto:h2-wada@nri.co.jp">Hiroyuki Wada</a> */ public class InfinispanOAuth2DeviceTokenStoreProviderFactory implements OAuth2DeviceTokenStoreProviderFactory { // Reuse "actionTokens" infinispan cache for now private volatile Supplier<BasicCache<String, ActionTokenValueEntity>> codeCache; @Override public OAuth2DeviceTokenStoreProvider create(KeycloakSession session) { lazyInit(session); return new InfinispanOAuth2DeviceTokenStoreProvider(session, codeCache); } private void lazyInit(KeycloakSession session) { if (codeCache == null) { synchronized (this) { codeCache = InfinispanSingleUseTokenStoreProviderFactory.getActionTokenCache(session); } } } @Override public void init(Config.Scope config) { } @Override public void postInit(KeycloakSessionFactory factory) { } @Override public void close() { } @Override public String getId() { return "infinispan"; } }
apache-2.0
youdonghai/intellij-community
java/java-psi-api/src/com/intellij/codeInsight/AnnotationTargetUtil.java
8531
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.codeInsight; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; import com.intellij.psi.PsiAnnotation.TargetType; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.Set; /** * @author peter */ public class AnnotationTargetUtil { private static final Logger LOG = Logger.getInstance(AnnotationTargetUtil.class); public static final Set<TargetType> DEFAULT_TARGETS = ContainerUtil.immutableSet( TargetType.PACKAGE, TargetType.TYPE, TargetType.ANNOTATION_TYPE, TargetType.FIELD, TargetType.METHOD, TargetType.CONSTRUCTOR, TargetType.PARAMETER, TargetType.LOCAL_VARIABLE); private static final TargetType[] PACKAGE_TARGETS = {TargetType.PACKAGE}; private static final TargetType[] TYPE_USE_TARGETS = {TargetType.TYPE_USE}; private static final TargetType[] ANNOTATION_TARGETS = {TargetType.ANNOTATION_TYPE, TargetType.TYPE, TargetType.TYPE_USE}; private static final TargetType[] TYPE_TARGETS = {TargetType.TYPE, TargetType.TYPE_USE}; private static final TargetType[] TYPE_PARAMETER_TARGETS = {TargetType.TYPE_PARAMETER, TargetType.TYPE_USE}; private static final TargetType[] CONSTRUCTOR_TARGETS = {TargetType.CONSTRUCTOR, TargetType.TYPE_USE}; private static final TargetType[] METHOD_TARGETS = {TargetType.METHOD, TargetType.TYPE_USE}; private static final TargetType[] FIELD_TARGETS = {TargetType.FIELD, TargetType.TYPE_USE}; private static final TargetType[] PARAMETER_TARGETS = {TargetType.PARAMETER, TargetType.TYPE_USE}; private static final TargetType[] LOCAL_VARIABLE_TARGETS = {TargetType.LOCAL_VARIABLE, TargetType.TYPE_USE}; @NotNull public static TargetType[] getTargetsForLocation(@Nullable PsiAnnotationOwner owner) { if (owner == null) { return TargetType.EMPTY_ARRAY; } if (owner instanceof PsiType || owner instanceof PsiTypeElement) { return TYPE_USE_TARGETS; } if (owner instanceof PsiTypeParameter) { return TYPE_PARAMETER_TARGETS; } if (owner instanceof PsiModifierList) { PsiElement element = ((PsiModifierList)owner).getParent(); if (element instanceof PsiPackageStatement) { return PACKAGE_TARGETS; } if (element instanceof PsiClass) { if (((PsiClass)element).getModifierList() != owner){ return TargetType.EMPTY_ARRAY; } if (((PsiClass)element).isAnnotationType()) { return ANNOTATION_TARGETS; } else { return TYPE_TARGETS; } } if (element instanceof PsiMethod) { if (((PsiMethod)element).isConstructor()) { return CONSTRUCTOR_TARGETS; } else { return METHOD_TARGETS; } } if (element instanceof PsiField) { return FIELD_TARGETS; } if (element instanceof PsiParameter) { // PARAMETER applies only to formal parameters (methods & lambdas) and catch parameters // see https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6.4.1 PsiElement scope = element.getParent(); if (scope instanceof PsiForeachStatement) { return LOCAL_VARIABLE_TARGETS; } if (scope instanceof PsiParameterList && scope.getParent() instanceof PsiLambdaExpression && ((PsiParameter)element).getTypeElement() == null) { return TargetType.EMPTY_ARRAY; } return PARAMETER_TARGETS; } if (element instanceof PsiLocalVariable) { return LOCAL_VARIABLE_TARGETS; } if (element instanceof PsiReceiverParameter) { return TYPE_USE_TARGETS; } } return TargetType.EMPTY_ARRAY; } @Nullable public static Set<TargetType> extractRequiredAnnotationTargets(@Nullable PsiAnnotationMemberValue value) { if (value instanceof PsiReference) { TargetType targetType = translateTargetRef((PsiReference)value); if (targetType != null) { return Collections.singleton(targetType); } } else if (value instanceof PsiArrayInitializerMemberValue) { Set <TargetType> targets = ContainerUtil.newHashSet(); for (PsiAnnotationMemberValue initializer : ((PsiArrayInitializerMemberValue)value).getInitializers()) { if (initializer instanceof PsiReference) { TargetType targetType = translateTargetRef((PsiReference)initializer); if (targetType != null) { targets.add(targetType); } } } return targets; } return null; } @Nullable private static TargetType translateTargetRef(@NotNull PsiReference reference) { if (reference instanceof PsiJavaCodeReferenceElement) { String name = ((PsiJavaCodeReferenceElement)reference).getReferenceName(); if (name != null) { try { return TargetType.valueOf(name); } catch (IllegalArgumentException ignore) { } } } PsiElement field = reference.resolve(); if (field instanceof PsiEnumConstant) { String name = ((PsiEnumConstant)field).getName(); try { return TargetType.valueOf(name); } catch (IllegalArgumentException e) { LOG.warn("Unknown target: " + name); } } return null; } /** * Returns {@code true} if the annotation resolves to a class having {@link TargetType#TYPE_USE} in it's targets. */ public static boolean isTypeAnnotation(@NotNull PsiAnnotation element) { return findAnnotationTarget(element, TargetType.TYPE_USE) == TargetType.TYPE_USE; } /** * From given targets, returns first where the annotation may be applied. Returns {@code null} when the annotation is not applicable * at any of the targets, or {@linkplain TargetType#UNKNOWN} if the annotation does not resolve to a valid annotation type. */ @Nullable public static TargetType findAnnotationTarget(@NotNull PsiAnnotation annotation, @NotNull TargetType... types) { if (types.length != 0) { PsiJavaCodeReferenceElement ref = annotation.getNameReferenceElement(); if (ref != null) { PsiElement annotationType = ref.resolve(); if (annotationType instanceof PsiClass) { return findAnnotationTarget((PsiClass)annotationType, types); } } } return TargetType.UNKNOWN; } /** * From given targets, returns first where the annotation may be applied. Returns {@code null} when the annotation is not applicable * at any of the targets, or {@linkplain TargetType#UNKNOWN} if the type is not a valid annotation (e.g. cannot be resolved). */ @Nullable public static TargetType findAnnotationTarget(@NotNull PsiClass annotationType, @NotNull TargetType... types) { if (types.length != 0) { Set<TargetType> targets = getAnnotationTargets(annotationType); if (targets != null) { for (TargetType type : types) { if (type != TargetType.UNKNOWN && targets.contains(type)) { return type; } } return null; } } return TargetType.UNKNOWN; } /** * Returns a set of targets where the given annotation may be applied, or {@code null} when the type is not a valid annotation. */ @Nullable public static Set<TargetType> getAnnotationTargets(@NotNull PsiClass annotationType) { if (!annotationType.isAnnotationType()) return null; PsiModifierList modifierList = annotationType.getModifierList(); if (modifierList == null) return null; PsiAnnotation target = modifierList.findAnnotation(CommonClassNames.JAVA_LANG_ANNOTATION_TARGET); if (target == null) return DEFAULT_TARGETS; // if omitted it is applicable to all but Java 8 TYPE_USE/TYPE_PARAMETERS targets return extractRequiredAnnotationTargets(target.findAttributeValue(null)); } }
apache-2.0
wido/cloudstack
engine/schema/src/main/java/com/cloud/network/dao/NetworkDao.java
4467
// 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.cloud.network.dao; import java.util.List; import java.util.Map; import com.cloud.network.Network; import com.cloud.network.Network.GuestType; import com.cloud.network.Network.State; import com.cloud.network.Networks.TrafficType; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.fsm.StateDao; public interface NetworkDao extends GenericDao<NetworkVO, Long>, StateDao<State, Network.Event, Network> { List<NetworkVO> listByOwner(long ownerId); List<NetworkVO> listByGuestType(GuestType type); List<NetworkVO> listBy(long accountId, long offeringId, long dataCenterId); List<NetworkVO> listBy(long accountId, long dataCenterId, String cidr, boolean skipVpc); List<NetworkVO> listByZoneAndGuestType(long accountId, long dataCenterId, Network.GuestType type, Boolean isSystem); NetworkVO persist(NetworkVO network, boolean gc, Map<String, String> serviceProviderMap); SearchBuilder<NetworkAccountVO> createSearchBuilderForAccount(); List<NetworkVO> getNetworksForOffering(long offeringId, long dataCenterId, long accountId); @Override @Deprecated NetworkVO persist(NetworkVO vo); /** * Retrieves the next available mac address in this network configuration. * * @param networkConfigId * id * @param zoneMacIdentifier * @return mac address if there is one. null if not. */ String getNextAvailableMacAddress(long networkConfigId, Integer zoneMacIdentifier); List<NetworkVO> listBy(long accountId, long networkId); List<NetworkVO> listByZoneAndUriAndGuestType(long zoneId, String broadcastUri, GuestType guestType); List<NetworkVO> listByZone(long zoneId); void changeActiveNicsBy(long networkId, int nicsCount); int getActiveNicsIn(long networkId); List<Long> findNetworksToGarbageCollect(); void clearCheckForGc(long networkId); List<NetworkVO> listByZoneSecurityGroup(Long zoneId); void addDomainToNetwork(long networkId, long domainId, Boolean subdomainAccess); List<NetworkVO> listByPhysicalNetwork(long physicalNetworkId); List<NetworkVO> listSecurityGroupEnabledNetworks(); List<NetworkVO> listByPhysicalNetworkTrafficType(long physicalNetworkId, TrafficType trafficType); List<NetworkVO> listBy(long accountId, long dataCenterId, Network.GuestType type, TrafficType trafficType); List<NetworkVO> listByPhysicalNetworkAndProvider(long physicalNetworkId, String providerName); void persistNetworkServiceProviders(long networkId, Map<String, String> serviceProviderMap); boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap); List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType); void setCheckForGc(long networkId); int getNetworkCountByNetworkOffId(long networkOfferingId); long countNetworksUserCanCreate(long ownerId); List<NetworkVO> listSourceNATEnabledNetworks(long accountId, long dataCenterId, GuestType type); int getNetworkCountByVpcId(long vpcId); List<NetworkVO> listByVpc(long vpcId); NetworkVO getPrivateNetwork(String broadcastUri, String cidr, long accountId, long zoneId, Long networkOfferingId); long countVpcNetworks(long vpcId); List<NetworkVO> listNetworksByAccount(long accountId, long zoneId, Network.GuestType type, boolean isSystem); List<NetworkVO> listRedundantNetworks(); List<NetworkVO> listVpcNetworks(); List<NetworkVO> listByAclId(long aclId); int getNonSystemNetworkCountByVpcId(long vpcId); List<NetworkVO> listNetworkVO(List<Long> idset); }
apache-2.0
jpkrohling/secret-store
secret-store-api/src/main/java/org/keycloak/secretstore/api/internal/ApplicationResources.java
1938
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.secretstore.api.internal; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; /** * @author Juraci Paixão Kröhling */ @ApplicationScoped public class ApplicationResources { @Inject @SecretStore Session session; private Map<BoundStatements, PreparedStatement> statements = new HashMap<>(BoundStatements.values().length); @PostConstruct public void buildStatements() { for (BoundStatements statement : BoundStatements.values()) { statements.put(statement, session.prepare(statement.getValue())); } } @Produces @NamedStatement public BoundStatement produceStatementByName(InjectionPoint injectionPoint) { NamedStatement annotation = injectionPoint.getAnnotated().getAnnotation(NamedStatement.class); BoundStatements stmtName = annotation.value(); return statements.get(stmtName).bind(); } }
apache-2.0
PublicHealthEngland/animal-welfare-assessment-grid
code/server/src/main/java/uk/gov/phe/erdst/sc/awag/service/factory/source/ImportSourceFactory.java
735
package uk.gov.phe.erdst.sc.awag.service.factory.source; import javax.ejb.Stateless; import uk.gov.phe.erdst.sc.awag.datamodel.ImportSource; @Stateless public class ImportSourceFactory { private static int CSV_COLUMN_LINE_NUMBER = 0; private static int CSV_COLUMN_SOURCE_NAME = 1; public ImportSource create(String[] importSourceCSVLineData) { final Long lineNumber = Long.parseLong(importSourceCSVLineData[CSV_COLUMN_LINE_NUMBER]); final String sourceName = importSourceCSVLineData[CSV_COLUMN_SOURCE_NAME]; ImportSource importSource = new ImportSource(); importSource.setLineNumber(lineNumber); importSource.setSourceName(sourceName); return importSource; } }
apache-2.0
JinBuHanLin/eshow-android
eshow_framwork/src/cn/org/eshow/framwork/task/AbTaskListener.java
1098
/* * Copyright (C) 2012 www.amsoft.cn * * 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 cn.org.eshow.framwork.task; // TODO: Auto-generated Javadoc /** * 任务执行的控制父类. * */ public class AbTaskListener { /** * 执行开始. * * @return 返回的结果对象 */ public void get() { }; /** * 执行开始后调用. * */ public void update() { }; /** * 监听进度变化. * * @param values * the values */ public void onProgressUpdate(Integer... values) { }; }
apache-2.0
yyitsz/myjavastudio
jcg-andygene-web-archetype/src/main/resources/archetype-resources/src/main/java/drools/MyDomain.java
1234
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}.drools; import java.io.Serializable; import javax.validation.constraints.Pattern; public class MyDomain implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Pattern(regexp = ".+", message = "Name must not be empty!") private String name; @Pattern(regexp = ".+", message = "Last Name must not be empty!") private String lastName; private String description; public MyDomain() { } public MyDomain(String name, String lastName, String description) { super(); this.name = name; this.lastName = lastName; this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String toString() { return "MyDomain [name=" + name + ", lastName=" + lastName + ", description=" + description + "]"; } }
apache-2.0
mklab/taskit
src/main/java/org/mklab/taskit/server/domain/SubmissionLocator.java
982
/* * 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.mklab.taskit.server.domain; /** * @author ishikura * @version $Revision$, 2011/09/19 */ public class SubmissionLocator extends AbstractLocator<Submission, Integer> { /** * {@inheritDoc} */ @Override public Class<Submission> getDomainType() { return Submission.class; } /** * {@inheritDoc} */ @Override public Class<Integer> getIdType() { return Integer.class; } }
apache-2.0
google/agi
gapic/src/platform/windows/org/eclipse/swt/widgets/SwtUtil.java
2643
/* * Copyright (C) 2017 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 org.eclipse.swt.widgets; import org.eclipse.swt.SWT; import org.eclipse.swt.internal.win32.OS; import org.eclipse.swt.internal.win32.SCROLLINFO; public class SwtUtil { private SwtUtil() { } public static void disableAutoHideScrollbars(@SuppressWarnings("unused") Scrollable widget) { // Do nothing. } public static void syncTreeAndTableScroll(Tree tree, Table table) { Exclusive exclusive = new Exclusive(); table.getVerticalBar().addListener(SWT.Selection, e -> exclusive.runExclusive(() -> { int pos = table.getVerticalBar().getSelection(); SCROLLINFO info = new SCROLLINFO (); info.cbSize = SCROLLINFO.sizeof; info.fMask = OS.SIF_POS; info.nPos = pos; OS.SetScrollInfo(tree.handle, OS.SB_VERT, info, true); OS.SendMessage(tree.handle, OS.WM_VSCROLL, OS.SB_THUMBPOSITION | (pos << 16), 0); })); Runnable updateTableScroll = () -> { exclusive.runExclusive(() -> table.setTopIndex(tree.getVerticalBar().getSelection())); }; tree.getVerticalBar().addListener(SWT.Selection, e -> updateTableScroll.run()); tree.addListener(SWT.Expand, e -> table.getDisplay().asyncExec(updateTableScroll)); tree.addListener(SWT.Collapse, e -> table.getDisplay().asyncExec(updateTableScroll)); // Make sure the rows are the same height in the table as the tree. int[] height = { tree.getItemHeight() }; table.addListener(SWT.Paint, event -> { height[0] = tree.getItemHeight(); if (table.getItemHeight() != height[0]) { table.setItemHeight(height[0]); updateTableScroll.run(); } }); } // Used to prevent infite loops from handling one event triggering another handled event. private static class Exclusive { private boolean ignore = false; public Exclusive() { } public void runExclusive(Runnable run) { if (!ignore) { ignore = true; try { run.run(); } finally { ignore = false; } } } } }
apache-2.0
crate/crate
server/src/test/java/org/elasticsearch/indices/recovery/PeerRecoverySourceServiceTests.java
3335
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package org.elasticsearch.indices.recovery; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.seqno.SequenceNumbers; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.IndexShardTestCase; import org.elasticsearch.index.store.Store; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.transport.TransportService; import org.junit.Test; import java.io.IOException; import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; public class PeerRecoverySourceServiceTests extends IndexShardTestCase { @Test public void testDuplicateRecoveries() throws IOException { IndexShard primary = newStartedShard(true); PeerRecoverySourceService peerRecoverySourceService = new PeerRecoverySourceService( mock(TransportService.class), mock(IndicesService.class), new RecoverySettings(Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS))); StartRecoveryRequest startRecoveryRequest = new StartRecoveryRequest(primary.shardId(), randomAlphaOfLength(10), getFakeDiscoNode("source"), getFakeDiscoNode("target"), Store.MetadataSnapshot.EMPTY, randomBoolean(), randomLong(), SequenceNumbers.UNASSIGNED_SEQ_NO); peerRecoverySourceService.start(); RecoverySourceHandler handler = peerRecoverySourceService.ongoingRecoveries .addNewRecovery(startRecoveryRequest, primary); DelayRecoveryException delayRecoveryException = expectThrows( DelayRecoveryException.class, () -> peerRecoverySourceService.ongoingRecoveries.addNewRecovery( startRecoveryRequest, primary)); assertThat(delayRecoveryException.getMessage(), containsString("recovery with same target already registered")); peerRecoverySourceService.ongoingRecoveries.remove(primary, handler); // re-adding after removing previous attempt works handler = peerRecoverySourceService.ongoingRecoveries.addNewRecovery(startRecoveryRequest, primary); peerRecoverySourceService.ongoingRecoveries.remove(primary, handler); closeShards(primary); } }
apache-2.0
rajapulau/qiscus-sdk-android
chat/src/main/java/com/qiscus/sdk/ui/adapter/viewholder/QiscusBaseAccountLinkingMessageViewHolder.java
3969
/* * Copyright (c) 2016 Qiscus. * * 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.qiscus.sdk.ui.adapter.viewholder; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.TextView; import com.qiscus.sdk.Qiscus; import com.qiscus.sdk.R; import com.qiscus.sdk.data.model.QiscusComment; import com.qiscus.sdk.ui.adapter.OnItemClickListener; import com.qiscus.sdk.ui.adapter.OnLongItemClickListener; import com.qiscus.sdk.util.QiscusRawDataExtractor; import org.json.JSONException; import org.json.JSONObject; /** * Created on : March 01, 2017 * Author : zetbaitsu * Name : Zetra * GitHub : https://github.com/zetbaitsu */ public abstract class QiscusBaseAccountLinkingMessageViewHolder extends QiscusBaseTextMessageViewHolder { @NonNull protected TextView accountLinkingView; protected int accountLinkingTextColor; protected Drawable accountLinkingBackgroundDrawable; protected int accountLinkingBackgroundColor; protected String accountLinkingText; private OnItemClickListener itemClickListener; public QiscusBaseAccountLinkingMessageViewHolder(View itemView, OnItemClickListener itemClickListener, OnLongItemClickListener longItemClickListener) { super(itemView, itemClickListener, longItemClickListener); this.itemClickListener = itemClickListener; accountLinkingView = getAccountLinkingView(itemView); accountLinkingView.setOnClickListener(this); } @Override protected void loadChatConfig() { super.loadChatConfig(); accountLinkingText = Qiscus.getChatConfig().getAccountLinkingText(); accountLinkingTextColor = ContextCompat.getColor(Qiscus.getApps(), Qiscus.getChatConfig().getAccountLinkingTextColor()); accountLinkingBackgroundColor = ContextCompat.getColor(Qiscus.getApps(), Qiscus.getChatConfig().getAccountLinkingBackground()); accountLinkingBackgroundDrawable = ContextCompat.getDrawable(Qiscus.getApps(), R.drawable.qiscus_button_account_linking_bg); accountLinkingBackgroundDrawable.setColorFilter(accountLinkingBackgroundColor, PorterDuff.Mode.SRC_ATOP); } @Override protected void setUpColor() { super.setUpColor(); accountLinkingView.setTextColor(accountLinkingTextColor); accountLinkingView.setBackground(accountLinkingBackgroundDrawable); } @NonNull protected abstract TextView getAccountLinkingView(View itemView); @Override protected void showMessage(QiscusComment qiscusComment) { super.showMessage(qiscusComment); try { JSONObject payload = QiscusRawDataExtractor.getPayload(qiscusComment); String text = payload.getJSONObject("params").optString("button_text", accountLinkingText); if (text == null || text.isEmpty()) { text = accountLinkingText; } accountLinkingView.setText(text); } catch (JSONException e) { e.printStackTrace(); accountLinkingView.setText(accountLinkingText); } } @Override public void onClick(View v) { if (v.equals(accountLinkingView)) { itemClickListener.onItemClick(v, getAdapterPosition()); } } }
apache-2.0
FangWW/meinv
app/src/main/java/com/meinv/ui/activity/FeedBackActivity.java
2932
///* // * Copyright (c) 2015 [1076559197@qq.com | tchen0707@gmail.com] // * // * Licensed under the Apache License, Version 2.0 (the "License”); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // */ // //package com.meinv.ui.activity; // //import android.os.Bundle; //import android.view.View; // //import com.library.eventbus.EventCenter; //import com.library.netstatus.NetUtils; //import R; //import com.meinv.ui.activity.base.BaseSwipeBackActivity; //import com.umeng.fb.fragment.FeedbackFragment; // ///** // * Author: Tau.Chen // * Email: 1076559197@qq.com | tauchen1990@gmail.com // * Date: 15/7/22 // * Description: // */ //public class FeedBackActivity extends BaseSwipeBackActivity { // // private String mConversationId = null; // private FeedbackFragment mFeedbackFragment; // // @Override // protected void onNewIntent(android.content.Intent intent) { // mFeedbackFragment.refresh(); // } // // @Override // protected boolean isApplyKitKatTranslucency() { // return true; // } // // @Override // protected void getBundleExtras(Bundle extras) { // mConversationId = extras.getString(FeedbackFragment.BUNDLE_KEY_CONVERSATION_ID); // } // // @Override // protected int getContentViewLayoutID() { // return R.layout.common_fragment_placeholder; // } // // @Override // protected void onEventComming(EventCenter eventCenter) { // // } // // @Override // protected View getLoadingTargetView() { // return null; // } // // @Override // protected void initViewsAndEvents() { // mFeedbackFragment = FeedbackFragment.newInstance(mConversationId); // // getSupportFragmentManager().beginTransaction() // .add(R.id.common_fragment_placeholder_container, mFeedbackFragment) // .commit(); // } // // @Override // protected void onNetworkConnected(NetUtils.NetType type) { // // } // // @Override // protected void onNetworkDisConnected() { // // } // // @Override // protected boolean isApplyStatusBarTranslucency() { // return true; // } // // @Override // protected boolean isBindEventBusHere() { // return false; // } // // @Override // protected boolean toggleOverridePendingTransition() { // return true; // } // // @Override // protected TransitionMode getOverridePendingTransitionMode() { // return TransitionMode.RIGHT; // } //}
apache-2.0
zavtech/morpheus-core
src/main/java/com/zavtech/morpheus/source/ExcelSource.java
25554
package com.zavtech.morpheus.source; import com.univocity.parsers.common.ParserOutput; import com.univocity.parsers.csv.CsvParserSettings; import com.zavtech.morpheus.array.Array; import com.zavtech.morpheus.frame.DataFrame; import com.zavtech.morpheus.frame.DataFrameContent; import com.zavtech.morpheus.frame.DataFrameException; import com.zavtech.morpheus.frame.DataFrameSource; import com.zavtech.morpheus.index.Index; import com.zavtech.morpheus.util.Resource; import com.zavtech.morpheus.util.text.Formats; import com.zavtech.morpheus.util.text.parser.Parser; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellReference; import org.apache.poi.util.SAXHelper; import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler; import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.usermodel.XSSFComment; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedTransferQueue; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import static java.util.Arrays.stream; /** * A DataFrameSource designed to load DataFrames from Microsoft Excel. * * @param <R> the row key type * * <p><strong>This is open source software released under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0 License</a></strong></p> * * @author Dwight Gunning */ public class ExcelSource<R> extends DataFrameSource<R,String,ExcelSourceOptions<R>> { public ExcelSource(){super();} /** * Read from the excel resource * @param configurator the options consumer to configure load options * @return a new DataFrame * @throws DataFrameException if the DataFrame cannot be constructed */ @Override public DataFrame<R, String> read(Consumer<ExcelSourceOptions<R>> configurator) throws DataFrameException { final ExcelSourceOptions<R> options = initOptions(new ExcelSourceOptions<>(), configurator); switch (options.getExcelType()){ case XLSX: return readXslx(options); case XLS: return readXls(options); } throw new DataFrameException("Unimplemented excel type"); } private DataFrame<R,String> readXls(ExcelSourceOptions<R> options) { final Resource resource = options.getResource(); try { switch (resource.getType()) { case FILE: return readWorkbook(options, WorkbookFactory.create(resource.asFile())); case URL: return readWorkbook(options, WorkbookFactory.create(new File(resource.asURL().getFile()))); case INPUT_STREAM: return readWorkbook(options, WorkbookFactory.create(resource.asInputStream())); default: throw new DataFrameException("Unsupported resource specified in ExcelRequest: " + resource); } }catch (IOException | InvalidFormatException e){ throw new DataFrameException("Cannot read excel file: " + resource, e); } } /** * Read the workbook and return a DataFrame * @param options the ExcelSourceOptions * @param workbook the workbook to read * @return a new DataFrame * @throws IOException */ private DataFrame<R,String> readWorkbook(ExcelSourceOptions<R> options, Workbook workbook) throws IOException{ try { final Sheet sheet = getSheetForParsing(options, workbook); XlsParser parser = new XlsParser(options); return parser.parse(sheet); }finally{ workbook.close(); } } private DataFrame<R, String> readXslx(ExcelSourceOptions<R> options) throws DataFrameException { final Resource resource = options.getResource(); try(OPCPackage opcPackage = open(resource)){ return parse(options, opcPackage); } catch (DataFrameException ex) { throw ex; } catch (Exception ex) { throw new DataFrameException("Failed to create DataFrame from Excel source", ex); } } /** * Opens the excel resource * @param resource the resource to open * @return an OPCPackage representing the excel resource * @throws IOException if an io problem occurs * @throws InvalidFormatException if the file has an incorrect format */ private OPCPackage open(Resource resource) throws IOException, InvalidFormatException { switch (resource.getType()) { case FILE: return OPCPackage.open(resource.asFile()); case URL: return OPCPackage.open(resource.asURL().getPath()); case INPUT_STREAM: return OPCPackage.open(resource.asInputStream()); default: throw new DataFrameException("Unsupported resource specified in ExcelRequest: " + resource); } } /** * Returns a DataFrame parsed from the stream specified stream * * @return the DataFrame parsed from stream * @throws IOException if there stream read error */ private DataFrame<R, String> parse(ExcelSourceOptions<R> options, OPCPackage opcPackage) throws IOException { try { ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(opcPackage); XSSFReader xssfReader = new XSSFReader(opcPackage); XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); try (InputStream inputStream = getSheetForParsing( options, iter)) { StylesTable styles = xssfReader.getStylesTable(); XMLReader sheetParser = SAXHelper.newXMLReader(); final ExcelXSSFSheetContentHandler sheetContentsHandler = new ExcelXSSFSheetContentHandler(options); DataFormatter formatter = new DataFormatter(); ContentHandler contentHandler = new XSSFSheetXMLHandler(styles, null, strings, sheetContentsHandler, formatter, false); sheetParser.setContentHandler(contentHandler); sheetParser.parse(new InputSource(inputStream)); sheetContentsHandler.endProcess(); return sheetContentsHandler.getFrame(); } catch (InvalidFormatException e) { throw new DataFrameException("Failed to parse Excel file - invalid format", e); } catch (ParserConfigurationException e) { throw new DataFrameException("Failed to parse Excel file - parser configuration issue", e); } } catch (OpenXML4JException|SAXException ex) { throw new DataFrameException("Failed to parse Excel file", ex); } } /** * Get the sheet that should be parsed * @param options The ExcelSourceOptions * @param workbook The Excel workbook (OLE) * @return A sheet that matches the name if the sheet name is provided */ private Sheet getSheetForParsing(ExcelSourceOptions<R> options, Workbook workbook) { Sheet theSheet = options.getSheetName() != null? workbook.getSheet(options.getSheetName()) : workbook.getSheetAt(0); if( theSheet != null){ return theSheet; } throw new DataFrameException("No sheet found for that matched configured sheet " + options.getSheetName()); } /** * Get the sheet that should be parsed * @param options The options * @param iter The sheet iterator * @return A sheet that matches the name if the sheet name is provided */ private InputStream getSheetForParsing(ExcelSourceOptions<R> options, XSSFReader.SheetIterator iter) { while(iter.hasNext()){ InputStream inputStream = iter.next(); final String sheetName = iter.getSheetName(); if(options.getSheetName() == null){ return inputStream; }else{ if( sheetName.equals(options.getSheetName())){ return inputStream; } } } throw new DataFrameException("No sheet found for that matched configured sheet " + options.getSheetName()); } /** * Handles the excel parsing events and populates the DataFrame * * This handles only the newer Excel XSLX format. */ class ExcelSheetContentHandler implements Runnable{ int rowCounter; String[] headers; int[] colIndexes; String[] rowValues; final int logBatchSize; volatile boolean done; protected ParserOutput output; final Function<String[],R> rowKeyParser; CsvSource.DataBatch<R> batch; final ExcelSourceOptions<R> options; DataFrame<R,String> frame; Parser<?>[] parsers; CountDownLatch countDownLatch; final Predicate<String[]> rowPredicate; LinkedTransferQueue<CsvSource.DataBatch<R>> queue; final Object lock = new Object(); ExcelSheetContentHandler(ExcelSourceOptions<R> options){ this.options = options; this.rowPredicate = options.getRowPredicate().orElse(null); this.rowKeyParser = options.getRowKeyParser().orElse(null); this.logBatchSize = options.getLogBatchSize(); this.output = new ParserOutput(new CsvParserSettings()); if (options.isParallel()) { this.countDownLatch = new CountDownLatch(1); this.queue = new LinkedTransferQueue<>(); final Thread thread = new Thread(this, "DataFrameExcelReaderThread"); thread.setDaemon(true); thread.start(); } } /** * Returns true if processing is complete * @return true if processing is complete */ boolean isComplete() { synchronized (lock) { return done && queue.isEmpty(); } } @Override() public void run() { try { while (!isComplete()) { try { final CsvSource.DataBatch<R> batch = queue.take(); if (batch != null && batch.rowCount() > 0) { processBatch(batch); } } catch (Exception ex) { throw new DataFrameException("Failed to process CSV data batch", ex); } } } catch (Exception ex) { ex.printStackTrace(); } finally { countDownLatch.countDown(); } } public DataFrame<R,String> getFrame() { try { if(options.isParallel()){ countDownLatch.await(); } return frame; } catch (Exception ex) { throw new DataFrameException("Failed to resolve frame", ex); } } /** * Initializes data structures to capture parsed content * @param csvColCount the number of columns in CSV content */ @SuppressWarnings("unchecked") protected void initBatch(int csvColCount, String[] headers) { initHeader(csvColCount, headers); this.rowValues = new String[csvColCount]; this.batch = new CsvSource.DataBatch(options.getRowAxisType(), options.getReadBatchSize(), colIndexes.length); this.parsers = new Parser[csvColCount]; } /** * Initializes the header array and column ordinals * @param csvColCount the number of columns in CSV content * @return the column count for frame */ protected int initHeader(int csvColCount, String[] headers) { this.headers = options.isHeader() ? headers : IntStream.range(0, csvColCount).mapToObj(i -> "Column-" + i).toArray(String[]::new); this.headers = IntStream.range(0, headers.length).mapToObj(i -> headers[i] != null ? headers[i] : "Column-" + i).toArray(String[]::new); this.colIndexes = IntStream.range(0, headers.length).toArray(); this.options.getColIndexPredicate().ifPresent(predicate -> { final Map<String,Integer> indexMap = IntStream.range(0, headers.length).boxed().collect(Collectors.toMap(i -> headers[i], i -> colIndexes[i])); this.headers = stream(headers).filter(colName -> predicate.test(indexMap.get(colName))).toArray(String[]::new); this.colIndexes = stream(headers).mapToInt(indexMap::get).toArray(); }); this.options.getColNamePredicate().ifPresent(predicate -> { final Map<String,Integer> indexMap = IntStream.range(0, headers.length).boxed().collect(Collectors.toMap(i -> headers[i], i -> colIndexes[i])); this.headers = stream(headers).filter(predicate).toArray(String[]::new); this.colIndexes = stream(headers).mapToInt(indexMap::get).toArray(); }); this.options.getColumnNameMapping().ifPresent(mapping -> { final IntStream colOrdinals = IntStream.range(0, headers.length); this.headers = colOrdinals.mapToObj(ordinal -> mapping.apply(headers[ordinal], ordinal)).toArray(String[]::new); }); return colIndexes.length; } /** * Initializes the frame based on the contents of the first batch * @param batch the initial batch to initialize frame */ protected void initFrame(CsvSource.DataBatch<R> batch) { if (headers == null) { final Class<R> rowType = options.getRowAxisType(); final Index<R> rowKeys = Index.of(rowType, 1); final Index<String> colKeys = Index.of(String.class, 1); this.frame = DataFrame.of(rowKeys, colKeys, Object.class); } else { final int colCount = headers.length; final Formats formats = options.getFormats(); final Class<R> rowType = options.getRowAxisType(); final Index<R> rowKeys = Index.of(rowType, options.getRowCapacity().orElse(10000)); final Index<String> colKeys = Index.of(String.class, colCount); this.frame = DataFrame.of(rowKeys, colKeys, Object.class); for (int i=0; i<colCount; ++i) { final String colName = headers[i] != null ? headers[i] : "Column-" + i; try { final String[] rawValues = batch.colData(i); final Optional<Parser<?>> userParser = CsvSource.getParser(options.getFormats(), colName); final Optional<Class<?>> colType = getColumnType(colName); if (colType.isPresent()) { final Class<?> type = colType.get(); final Parser<?> parser = userParser.orElse(formats.getParserOrFail(colType.get(), Object.class)); this.parsers[i] = parser; this.frame.cols().add(colName, type); } else { final Parser<?> stringParser = formats.getParserOrFail(String.class); final Parser<?> parser = userParser.orElse(formats.findParser(rawValues).orElse(stringParser)); final Set<Class<?>> typeSet = stream(rawValues).map(parser).filter(Objects::nonNull).map(Object::getClass).collect(Collectors.toSet()); final Class<?> type = typeSet.size() == 1 ? typeSet.iterator().next() : Object.class; this.parsers[i] = parser; this.frame.cols().add(colName, type); } } catch (Exception ex) { throw new DataFrameException("Failed to inspect seed values in column: " + colName, ex); } } } } /** * Returns the column type for the column name * @param colName the column name * @return the column type */ Optional<Class<?>> getColumnType(String colName) { final Optional<Class<?>> colType = options.getColumnType(colName); if (colType.isPresent()) { return colType; } else { for (Map.Entry<String,Class<?>> entry : options.getColTypeMap().entrySet()) { if (colName.matches( entry.getKey())) { return Optional.of(entry.getValue()); } } return Optional.empty(); } } /** * Processes the batch of data provided * @param batch the batch reference */ protected void processBatch(CsvSource.DataBatch<R> batch) { int rowIndex = -1; try { if (frame == null) { initFrame(batch); } if (batch.rowCount() > 0) { final Array<R> keys = batch.keys(); final int rowCount = batch.rowCount(); final int fromRowIndex = frame.rowCount(); final Array<R> rowKeys = rowCount < options.getReadBatchSize() ? keys.copy(0, rowCount) : keys; this.frame.rows().addAll(rowKeys); final DataFrameContent<R,String> data = frame.data(); for (int j=0; j<colIndexes.length; ++j) { final String[] colValues = batch.colData(j); final Parser<?> parser = parsers[j]; for (int i=0; i<rowCount; ++i) { rowIndex = fromRowIndex + i; final String rawValue = colValues[i]; switch (parser.getStyle()) { case INTEGER: data.setInt(rowIndex, j, parser.applyAsInt(rawValue)); break; case BOOLEAN: data.setBoolean(rowIndex, j, parser.applyAsBoolean(rawValue)); break; case LONG: data.setLong(rowIndex, j, parser.applyAsLong(rawValue)); break; case DOUBLE: data.setDouble(rowIndex, j, parser.applyAsDouble(rawValue)); break; default: data.setValue(rowIndex, j, parser.apply(rawValue)); break; } } } if (frame.rowCount() % 100000 == 0) { System.out.println("Processed " + frame.rowCount() + " rows..."); } } } catch (Exception ex) { final int lineNo = options.isHeader() ? rowIndex + 2 : rowIndex + 1; throw new DataFrameException("Failed to process CSV batch, line no " + lineNo, ex); } } protected void endRow(String[] row, int rowIndex){ try { if (batch == null) { if(headers == null){ headers = row; } initBatch(row.length, headers); } if (rowIndex > 0 && (rowPredicate == null || rowPredicate.test(row)) ) { this.rowCounter++; if (logBatchSize > 0 && rowCounter % logBatchSize == 0) { System.out.println("Loaded " + rowCounter + " rows..."); } for (int i = 0; i < colIndexes.length; ++i) { final int colIndex = colIndexes[i]; final String rawValue = row.length > colIndex ? row[colIndex] : null; this.rowValues[i] = rawValue; } if (rowKeyParser == null) { this.batch.addRow(rowCounter - 1, rowValues); } else { final R rowKey = rowKeyParser.apply(row); this.batch.addRow(rowKey, rowValues); } if (batch.rowCount() == options.getReadBatchSize()) { if (!options.isParallel()) { this.processBatch(batch); this.batch.clear(); } else { synchronized (lock) { this.queue.add(batch); this.batch = new CsvSource.DataBatch<>(options.getRowAxisType(), options.getReadBatchSize(), colIndexes.length); this.lock.notify(); } } } } } catch (DataFrameException ex) { throw ex; } catch (Exception ex) { throw new DataFrameException("Failed to parse row: " + Arrays.toString(row), ex); } } void endProcess() { try { if (!options.isParallel()) { this.batch = batch != null ? batch : new CsvSource.DataBatch<>(options.getRowAxisType(), options.getReadBatchSize(), 0); this.processBatch(batch); } else { synchronized (lock) { this.done = true; this.batch = batch != null ? batch : new CsvSource.DataBatch<>(options.getRowAxisType(), options.getReadBatchSize(), 0); this.queue.add(batch); } } } catch (DataFrameException ex) { throw ex; } catch (Exception ex) { throw new DataFrameException("Failed to process CSV parse end", ex); } } } /** * A handler for Excel XML based data, implementing the XSSFSheetContentHandler interface * */ class ExcelXSSFSheetContentHandler extends ExcelSheetContentHandler implements XSSFSheetXMLHandler.SheetContentsHandler{ private int currentCol = -1; ExcelXSSFSheetContentHandler(ExcelSourceOptions options){ super(options); } @Override public void startRow(int i) { if( this.output == null ){ this.output = new ParserOutput(new CsvParserSettings()); } currentCol = -1; } @Override public void endRow(int rowIndex) { String[] row = output.rowParsed(); endRow(row, rowIndex); } /** * POI calls this with the value parsed from the cell. * @param cellReference The cell reference * @param formattedValue The value of the cell * @param comment a comment */ @Override public void cell(String cellReference, String formattedValue, XSSFComment comment) { this.output.valueParsed(formattedValue); int thisCol = (new CellReference(cellReference)).getCol(); //Fill missing columns int missedCols = thisCol - currentCol - 1; for (int i=0; i<missedCols; i++) { this.output.valueParsed(""); } currentCol = thisCol; } /** * Unused, and unimplemented. This comes from the from interface */ @Override public void headerFooter(String text, boolean isHeader, String tagName) { } } /** * Handles the OLE school xls parser */ class XlsParser extends ExcelSheetContentHandler{ XlsParser(ExcelSourceOptions<R> options) { super(options); } private DataFrame<R,String> parse(Sheet sheet) { DataFormatter formatter = new DataFormatter(); int rowIndex = 0; for(Iterator<Row> rowIter = sheet.rowIterator(); rowIter.hasNext();){ Row excelRow = rowIter.next(); if( rowIndex ==0){ if( this.output == null ){ this.output = new ParserOutput(new CsvParserSettings()); } } final int numberOfColumns = excelRow.getLastCellNum(); String[] row = new String[numberOfColumns]; for(int i = 0; i < numberOfColumns; i++){ Cell cell = excelRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); row[i] = formatter.formatCellValue(cell); } endRow( row, rowIndex ); rowIndex++; } endProcess(); return this.frame; } } }
apache-2.0
ArvinDevel/incubator-pulsar
pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/MockedPulsarServiceBaseTest.java
11632
/** * 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.pulsar.broker.auth; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.function.Supplier; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.PulsarMockBookKeeper; import org.apache.bookkeeper.test.PortManager; import org.apache.bookkeeper.util.ZkUtils; import org.apache.pulsar.broker.BookKeeperClientFactory; import org.apache.pulsar.broker.PulsarService; import org.apache.pulsar.broker.ServiceConfiguration; import org.apache.pulsar.broker.namespace.NamespaceService; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.compaction.Compactor; import org.apache.pulsar.zookeeper.ZooKeeperClientFactory; import org.apache.pulsar.zookeeper.ZookeeperClientFactoryImpl; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.MockZooKeeper; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for all tests that need a Pulsar instance without a ZK and BK cluster */ public abstract class MockedPulsarServiceBaseTest { protected ServiceConfiguration conf; protected PulsarService pulsar; protected PulsarAdmin admin; protected PulsarClient pulsarClient; protected URL brokerUrl; protected URL brokerUrlTls; protected URI lookupUrl; protected final int BROKER_WEBSERVICE_PORT = PortManager.nextFreePort(); protected final int BROKER_WEBSERVICE_PORT_TLS = PortManager.nextFreePort(); protected final int BROKER_PORT = PortManager.nextFreePort(); protected final int BROKER_PORT_TLS = PortManager.nextFreePort(); protected MockZooKeeper mockZookKeeper; protected NonClosableMockBookKeeper mockBookKeeper; protected boolean isTcpLookup = false; protected final String configClusterName = "test"; private SameThreadOrderedSafeExecutor sameThreadOrderedSafeExecutor; private ExecutorService bkExecutor; public MockedPulsarServiceBaseTest() { resetConfig(); } protected void resetConfig() { this.conf = new ServiceConfiguration(); this.conf.setBrokerServicePort(BROKER_PORT); this.conf.setBrokerServicePortTls(BROKER_PORT_TLS); this.conf.setAdvertisedAddress("localhost"); this.conf.setWebServicePort(BROKER_WEBSERVICE_PORT); this.conf.setWebServicePortTls(BROKER_WEBSERVICE_PORT_TLS); this.conf.setClusterName(configClusterName); this.conf.setAdvertisedAddress("localhost"); // there are TLS tests in here, they need to use localhost because of the certificate this.conf.setManagedLedgerCacheSizeMB(8); this.conf.setActiveConsumerFailoverDelayTimeMillis(0); this.conf.setDefaultNumberOfNamespaceBundles(1); this.conf.setZookeeperServers("localhost:2181"); this.conf.setConfigurationStoreServers("localhost:3181"); } protected final void internalSetup() throws Exception { init(); lookupUrl = new URI(brokerUrl.toString()); if (isTcpLookup) { lookupUrl = new URI("pulsar://localhost:" + BROKER_PORT); } pulsarClient = PulsarClient.builder().serviceUrl(lookupUrl.toString()).statsInterval(0, TimeUnit.SECONDS).build(); } protected final void internalSetupForStatsTest() throws Exception { init(); String lookupUrl = brokerUrl.toString(); if (isTcpLookup) { lookupUrl = new URI("pulsar://localhost:" + BROKER_PORT).toString(); } pulsarClient = PulsarClient.builder().serviceUrl(lookupUrl.toString()).statsInterval(1, TimeUnit.SECONDS).build(); } protected final void init() throws Exception { sameThreadOrderedSafeExecutor = new SameThreadOrderedSafeExecutor(); bkExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("mock-pulsar-bk") .setUncaughtExceptionHandler((thread, ex) -> log.info("Uncaught exception", ex)) .build()); mockZookKeeper = createMockZooKeeper(); mockBookKeeper = createMockBookKeeper(mockZookKeeper, bkExecutor); startBroker(); brokerUrl = new URL("http://" + pulsar.getAdvertisedAddress() + ":" + BROKER_WEBSERVICE_PORT); brokerUrlTls = new URL("https://" + pulsar.getAdvertisedAddress() + ":" + BROKER_WEBSERVICE_PORT_TLS); admin = spy(PulsarAdmin.builder().serviceHttpUrl(brokerUrl.toString()).build()); } protected final void internalCleanup() throws Exception { try { // if init fails, some of these could be null, and if so would throw // an NPE in shutdown, obscuring the real error if (admin != null) { admin.close(); } if (pulsarClient != null) { pulsarClient.close(); } if (pulsar != null) { pulsar.close(); } if (mockBookKeeper != null) { mockBookKeeper.reallyShutdow(); } if (mockZookKeeper != null) { mockZookKeeper.shutdown(); } if (sameThreadOrderedSafeExecutor != null) { sameThreadOrderedSafeExecutor.shutdown(); } if (bkExecutor != null) { bkExecutor.shutdown(); } } catch (Exception e) { log.warn("Failed to clean up mocked pulsar service:", e); throw e; } } protected abstract void setup() throws Exception; protected abstract void cleanup() throws Exception; protected void restartBroker() throws Exception { stopBroker(); startBroker(); } protected void stopBroker() throws Exception { pulsar.close(); // Simulate cleanup of ephemeral nodes //mockZookKeeper.delete("/loadbalance/brokers/localhost:" + pulsar.getConfiguration().getWebServicePort(), -1); } protected void startBroker() throws Exception { this.pulsar = startBroker(conf); } protected PulsarService startBroker(ServiceConfiguration conf) throws Exception { PulsarService pulsar = spy(new PulsarService(conf)); setupBrokerMocks(pulsar); boolean isAuthorizationEnabled = conf.isAuthorizationEnabled(); // enable authrorization to initialize authorization service which is used by grant-permission conf.setAuthorizationEnabled(true); pulsar.start(); conf.setAuthorizationEnabled(isAuthorizationEnabled); Compactor spiedCompactor = spy(pulsar.getCompactor()); doReturn(spiedCompactor).when(pulsar).getCompactor(); return pulsar; } protected void setupBrokerMocks(PulsarService pulsar) throws Exception { // Override default providers with mocked ones doReturn(mockZooKeeperClientFactory).when(pulsar).getZooKeeperClientFactory(); doReturn(mockBookKeeperClientFactory).when(pulsar).newBookKeeperClientFactory(); Supplier<NamespaceService> namespaceServiceSupplier = () -> spy(new NamespaceService(pulsar)); doReturn(namespaceServiceSupplier).when(pulsar).getNamespaceServiceProvider(); doReturn(sameThreadOrderedSafeExecutor).when(pulsar).getOrderedExecutor(); } public static MockZooKeeper createMockZooKeeper() throws Exception { MockZooKeeper zk = MockZooKeeper.newInstance(MoreExecutors.newDirectExecutorService()); List<ACL> dummyAclList = new ArrayList<ACL>(0); ZkUtils.createFullPathOptimistic(zk, "/ledgers/available/192.168.1.1:" + 5000, "".getBytes(ZookeeperClientFactoryImpl.ENCODING_SCHEME), dummyAclList, CreateMode.PERSISTENT); zk.create("/ledgers/LAYOUT", "1\nflat:1".getBytes(ZookeeperClientFactoryImpl.ENCODING_SCHEME), dummyAclList, CreateMode.PERSISTENT); return zk; } public static NonClosableMockBookKeeper createMockBookKeeper(ZooKeeper zookeeper, ExecutorService executor) throws Exception { return spy(new NonClosableMockBookKeeper(zookeeper, executor)); } // Prevent the MockBookKeeper instance from being closed when the broker is restarted within a test public static class NonClosableMockBookKeeper extends PulsarMockBookKeeper { public NonClosableMockBookKeeper(ZooKeeper zk, ExecutorService executor) throws Exception { super(zk, executor); } @Override public void close() throws InterruptedException, BKException { // no-op } @Override public void shutdown() { // no-op } public void reallyShutdow() { super.shutdown(); } } protected ZooKeeperClientFactory mockZooKeeperClientFactory = new ZooKeeperClientFactory() { @Override public CompletableFuture<ZooKeeper> create(String serverList, SessionType sessionType, int zkSessionTimeoutMillis) { // Always return the same instance (so that we don't loose the mock ZK content on broker restart return CompletableFuture.completedFuture(mockZookKeeper); } }; private BookKeeperClientFactory mockBookKeeperClientFactory = new BookKeeperClientFactory() { @Override public BookKeeper create(ServiceConfiguration conf, ZooKeeper zkClient) throws IOException { // Always return the same instance (so that we don't loose the mock BK content on broker restart return mockBookKeeper; } @Override public void close() { // no-op } }; public static void retryStrategically(Predicate<Void> predicate, int retryCount, long intSleepTimeInMillis) throws Exception { for (int i = 0; i < retryCount; i++) { if (predicate.test(null) || i == (retryCount - 1)) { break; } Thread.sleep(intSleepTimeInMillis + (intSleepTimeInMillis * i)); } } private static final Logger log = LoggerFactory.getLogger(MockedPulsarServiceBaseTest.class); }
apache-2.0
falko/camunda-bpm-platform
distro/jbossas7/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/service/MscManagedProcessEngineController.java
11329
/* * 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. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.container.impl.jboss.service; import org.camunda.bpm.container.impl.jboss.config.ManagedJtaProcessEngineConfiguration; import org.camunda.bpm.container.impl.jboss.config.ManagedProcessEngineMetadata; import org.camunda.bpm.container.impl.jboss.util.JBossCompatibilityExtension; import org.camunda.bpm.container.impl.jboss.util.Tccl; import org.camunda.bpm.container.impl.jboss.util.Tccl.Operation; import org.camunda.bpm.container.impl.jmx.services.JmxManagedProcessEngineController; import org.camunda.bpm.container.impl.metadata.PropertyHelper; import org.camunda.bpm.container.impl.metadata.spi.ProcessEnginePluginXml; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.ProcessEngineConfiguration; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.impl.cfg.JtaProcessEngineConfiguration; import org.camunda.bpm.engine.impl.cfg.ProcessEnginePlugin; import org.jboss.as.connector.subsystems.datasources.DataSourceReferenceFactoryService; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import javax.sql.DataSource; import javax.transaction.TransactionManager; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.logging.Level; import java.util.logging.Logger; /** * <p>Service responsible for starting / stopping a managed process engine inside the Msc</p> * * <p>This service is used for managing process engines that are started / stopped * through the application server management infrastructure.</p> * * <p>This is the Msc counterpart of the {@link JmxManagedProcessEngineController}</p> * * @author Daniel Meyer */ public class MscManagedProcessEngineController extends MscManagedProcessEngine { private final static Logger LOGGER = Logger.getLogger(MscManagedProcessEngineController.class.getName()); protected InjectedValue<ExecutorService> executorInjector = new InjectedValue<ExecutorService>(); // Injecting these values makes the MSC aware of our dependencies on these resources. // This ensures that they are available when this service is started protected final InjectedValue<TransactionManager> transactionManagerInjector = new InjectedValue<TransactionManager>(); protected final InjectedValue<DataSourceReferenceFactoryService> datasourceBinderServiceInjector = new InjectedValue<DataSourceReferenceFactoryService>(); protected final InjectedValue<MscRuntimeContainerJobExecutor> mscRuntimeContainerJobExecutorInjector = new InjectedValue<MscRuntimeContainerJobExecutor>(); protected ManagedProcessEngineMetadata processEngineMetadata; protected JtaProcessEngineConfiguration processEngineConfiguration; /** * Instantiate the process engine controller for a process engine configuration. * */ public MscManagedProcessEngineController(ManagedProcessEngineMetadata processEngineConfiguration) { this.processEngineMetadata = processEngineConfiguration; } public void start(final StartContext context) throws StartException { context.asynchronous(); executorInjector.getValue().submit(new Runnable() { public void run() { try { startInternal(context); context.complete(); } catch (StartException e) { context.failed(e); } catch (Throwable e) { context.failed(new StartException(e)); } } }); } public void stop(final StopContext context) { stopInternal(context); } protected void stopInternal(StopContext context) { try { super.stop(context); } finally { try { processEngine.close(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "exception while closing process engine", e); } } } public void startInternal(StartContext context) throws StartException { // setting the TCCL to the Classloader of this module. // this exploits a hack in MyBatis allowing it to use the TCCL to load the // mapping files from the process engine module Tccl.runUnderClassloader(new Operation<Void>() { public Void run() { startProcessEngine(); return null; } }, ProcessEngine.class.getClassLoader()); // invoke super start behavior. super.start(context); } protected void startProcessEngine() { processEngineConfiguration = createProcessEngineConfiguration(); // set the name for the process engine processEngineConfiguration.setProcessEngineName(processEngineMetadata.getEngineName()); // set the value for the history processEngineConfiguration.setHistory(processEngineMetadata.getHistoryLevel()); // use the injected datasource processEngineConfiguration.setDataSource((DataSource) datasourceBinderServiceInjector.getValue().getReference().getInstance()); // use the injected transaction manager processEngineConfiguration.setTransactionManager(transactionManagerInjector.getValue()); // set auto schema update if(processEngineMetadata.isAutoSchemaUpdate()) { processEngineConfiguration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE); } else { processEngineConfiguration.setDatabaseSchemaUpdate("off"); } // set db table prefix if( processEngineMetadata.getDbTablePrefix() != null ) { processEngineConfiguration.setDatabaseTablePrefix(processEngineMetadata.getDbTablePrefix()); } // set job executor on process engine. MscRuntimeContainerJobExecutor mscRuntimeContainerJobExecutor = mscRuntimeContainerJobExecutorInjector.getValue(); processEngineConfiguration.setJobExecutor(mscRuntimeContainerJobExecutor); PropertyHelper.applyProperties(processEngineConfiguration, processEngineMetadata.getConfigurationProperties()); addProcessEnginePlugins(processEngineConfiguration); processEngine = processEngineConfiguration.buildProcessEngine(); } protected void addProcessEnginePlugins(JtaProcessEngineConfiguration processEngineConfiguration) { // add process engine plugins: List<ProcessEnginePluginXml> pluginConfigurations = processEngineMetadata.getPluginConfigurations(); for (ProcessEnginePluginXml pluginXml : pluginConfigurations) { // create plugin instance ProcessEnginePlugin plugin = null; String pluginClassName = pluginXml.getPluginClass(); try { plugin = (ProcessEnginePlugin) createInstance(pluginClassName); } catch(ClassCastException e) { throw new ProcessEngineException("Process engine plugin '"+pluginClassName+"' does not implement interface "+ProcessEnginePlugin.class.getName()+"'."); } // apply configured properties Map<String, String> properties = pluginXml.getProperties(); PropertyHelper.applyProperties(plugin, properties); // add to configuration processEngineConfiguration.getProcessEnginePlugins().add(plugin); } } protected JtaProcessEngineConfiguration createProcessEngineConfiguration() { String configurationClassName = ManagedJtaProcessEngineConfiguration.class.getName(); if(processEngineMetadata.getConfiguration() != null && !processEngineMetadata.getConfiguration().isEmpty()) { configurationClassName = processEngineMetadata.getConfiguration(); } Object configurationObject = createInstance(configurationClassName); if (configurationObject instanceof JtaProcessEngineConfiguration) { return (JtaProcessEngineConfiguration) configurationObject; } else { throw new ProcessEngineException("Configuration class '"+configurationClassName+"' " + "is not a subclass of " + JtaProcessEngineConfiguration.class.getName()); } } private Object createInstance(String configurationClassName) { try { Class<?> configurationClass = getClass().getClassLoader().loadClass(configurationClassName); return configurationClass.newInstance(); } catch (Exception e) { throw new ProcessEngineException("Could not load '"+configurationClassName+"': the class must be visible from the camunda-jboss-subsystem module.", e); } } public Injector<TransactionManager> getTransactionManagerInjector() { return transactionManagerInjector; } public Injector<DataSourceReferenceFactoryService> getDatasourceBinderServiceInjector() { return datasourceBinderServiceInjector; } public InjectedValue<MscRuntimeContainerJobExecutor> getMscRuntimeContainerJobExecutorInjector() { return mscRuntimeContainerJobExecutorInjector; } public static void initializeServiceBuilder(ManagedProcessEngineMetadata processEngineConfiguration, MscManagedProcessEngineController service, ServiceBuilder<ProcessEngine> serviceBuilder, String jobExecutorName) { ContextNames.BindInfo datasourceBindInfo = ContextNames.bindInfoFor(processEngineConfiguration.getDatasourceJndiName()); serviceBuilder.addDependency(ServiceName.JBOSS.append("txn").append("TransactionManager"), TransactionManager.class, service.getTransactionManagerInjector()) .addDependency(datasourceBindInfo.getBinderServiceName(), DataSourceReferenceFactoryService.class, service.getDatasourceBinderServiceInjector()) .addDependency(ServiceNames.forMscRuntimeContainerDelegate(), MscRuntimeContainerDelegate.class, service.getRuntimeContainerDelegateInjector()) .addDependency(ServiceNames.forMscRuntimeContainerJobExecutorService(jobExecutorName), MscRuntimeContainerJobExecutor.class, service.getMscRuntimeContainerJobExecutorInjector()) .addDependency(ServiceNames.forMscExecutorService()) .setInitialMode(Mode.ACTIVE); if(processEngineConfiguration.isDefault()) { serviceBuilder.addAliases(ServiceNames.forDefaultProcessEngine()); } JBossCompatibilityExtension.addServerExecutorDependency(serviceBuilder, service.getExecutorInjector(), false); } public ProcessEngine getProcessEngine() { return processEngine; } public InjectedValue<ExecutorService> getExecutorInjector() { return executorInjector; } public ManagedProcessEngineMetadata getProcessEngineMetadata() { return processEngineMetadata; } }
apache-2.0
johnjianfang/jxse
src/main/java/net/jxta/discovery/DiscoveryEvent.java
4678
/* * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. * * The Sun Project JXTA(TM) Software License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: "This product includes software * developed by Sun Microsystems, Inc. for JXTA(TM) technology." * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must * not be used to endorse or promote products derived from this software * without prior written permission. For written permission, please contact * Project JXTA at http://www.jxta.org. * * 5. Products derived from this software may not be called "JXTA", nor may * "JXTA" appear in their name, without prior written permission of Sun. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 SUN * MICROSYSTEMS OR ITS 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. * * JXTA is a registered trademark of Sun Microsystems, Inc. in the United * States and other countries. * * Please see the license information page at : * <http://www.jxta.org/project/www/license.html> for instructions on use of * the license in source files. * * ==================================================================== * * This software consists of voluntary contributions made by many individuals * on behalf of Project JXTA. For more information on Project JXTA, please see * http://www.jxta.org. * * This license is based on the BSD license adopted by the Apache Foundation. */ package net.jxta.discovery; import net.jxta.document.Advertisement; import net.jxta.protocol.DiscoveryResponseMsg; import java.util.Enumeration; import java.util.EventObject; /** * Container for DiscoveryService events. The source of the event is the Endpoint * address of the responding peer */ public class DiscoveryEvent extends EventObject { private final DiscoveryResponseMsg response; private final int queryID; /** * Creates a new event * * @see net.jxta.protocol.DiscoveryResponseMsg * @see net.jxta.protocol.ResolverResponseMsg * * @param source The source of the event is the Endpoint address of the responding peer * @param response The response message for which this event is being generated. * @param queryid The query id associated with the response returned in this event */ public DiscoveryEvent(Object source, DiscoveryResponseMsg response, int queryid) { super(source); this.response = response; this.queryID = queryid; } /** * Returns the response associated with the event * * @return DiscoveryResponseMsg * * @see net.jxta.protocol.DiscoveryResponseMsg */ public DiscoveryResponseMsg getResponse() { return response; } /** * Returns the query id associated with the response returned in this event * * @return query id associated with the response */ public int getQueryID() { return queryID; } /** * Returns an array of advertisements contained in the DiscoveryResponse * for this event. * * @return Enumeration of Advertisements */ public Enumeration<Advertisement> getSearchResults() { return response.getAdvertisements(); } }
apache-2.0
trinopoty/protobuf-rpc
src/main/java/me/trinopoty/protobufRpc/client/ProtobufRpcClientChannelPool.java
7424
package me.trinopoty.protobufRpc.client; import me.trinopoty.protobufRpc.ProtobufRpcLog; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.util.concurrent.atomic.AtomicLong; @SuppressWarnings({"WeakerAccess", "unused"}) public final class ProtobufRpcClientChannelPool implements Closeable { private static final int BORROW_RETRY_COUNT = 5; private static final class RpcClientChannelProxyImpl implements ProtobufRpcClientChannel { private final ProtobufRpcClientChannelPool mClientChannelPool; private final ProtobufRpcClientChannel mRpcClientChannel; RpcClientChannelProxyImpl(ProtobufRpcClientChannelPool clientChannelPool, ProtobufRpcClientChannel rpcClientChannel) { mClientChannelPool = clientChannelPool; mRpcClientChannel = rpcClientChannel; } @Override public <T> T getService(Class<T> classOfService) { return mRpcClientChannel.getService(classOfService); } @Override public <T> void addOobHandler(Class<T> classOfOob, T objectOfOob) { mRpcClientChannel.addOobHandler(classOfOob, objectOfOob); } @Override public void setChannelDisconnectListener(ProtobufRpcClientChannelDisconnectListener channelDisconnectListener) { mRpcClientChannel.setChannelDisconnectListener(channelDisconnectListener); } @Override public boolean isActive() { return mRpcClientChannel.isActive(); } @Override public void close() { mClientChannelPool.returnResource(this); } @Override public InetSocketAddress getRemoteAddress() { return mRpcClientChannel.getRemoteAddress(); } void realClose() { mRpcClientChannel.close(); } } private final class ClientChannelFactory extends BasePooledObjectFactory<ProtobufRpcClientChannel> { private final ProtobufRpcClient mProtobufRpcClient; private final InetSocketAddress mRemoteAddress; private final boolean mSsl; ClientChannelFactory(ProtobufRpcClient protobufRpcClient, InetSocketAddress remoteAddress, boolean ssl) { mProtobufRpcClient = protobufRpcClient; mRemoteAddress = remoteAddress; mSsl = ssl; } @Override public ProtobufRpcClientChannel create() { return new RpcClientChannelProxyImpl( ProtobufRpcClientChannelPool.this, mProtobufRpcClient.getClientChannel(mRemoteAddress, mSsl)); } @Override public PooledObject<ProtobufRpcClientChannel> wrap(ProtobufRpcClientChannel protobufRpcClientChannel) { return new DefaultPooledObject<>(protobufRpcClientChannel); } @Override public void destroyObject(PooledObject<ProtobufRpcClientChannel> p) { ((RpcClientChannelProxyImpl) p.getObject()).realClose(); } @Override public boolean validateObject(PooledObject<ProtobufRpcClientChannel> p) { return p.getObject().isActive(); } } private final Logger mLogger; private final String mLogTag; private final boolean mLogCallingMethod; private final AtomicLong mBorrowedObjectCount; private GenericObjectPool<ProtobufRpcClientChannel> mClientChannelPool; ProtobufRpcClientChannelPool(RpcClientChannelPoolConfig poolConfig, ProtobufRpcClient protobufRpcClient, InetSocketAddress remoteAddress, boolean ssl) { mClientChannelPool = new GenericObjectPool<>(new ClientChannelFactory(protobufRpcClient, remoteAddress, ssl), poolConfig); if(poolConfig.isLoggingEnabled()) { mLogger = LogManager.getLogger(ProtobufRpcLog.CLIENT_POOL); mLogTag = (poolConfig.getLogTag() != null)? poolConfig.getLogTag() : Integer.toHexString(System.identityHashCode(this)); mLogCallingMethod = poolConfig.isLogCallingMethod(); mBorrowedObjectCount = new AtomicLong(0); } else { mLogger = null; mLogTag = null; mLogCallingMethod = false; mBorrowedObjectCount = null; } if(mLogger != null) { mLogger.debug("[ProtobufRpc Pool, " + mLogTag + ", Init] { remoteAddress : \"" + remoteAddress.getHostName() + ":" + remoteAddress.getPort() + "\" }"); } } @Override public void close() { mClientChannelPool.close(); } /** * Retrieves an instance of {@link ProtobufRpcClientChannel} object from the pool. * * @return An instance of {@link ProtobufRpcClientChannel} for communicating with server. */ public ProtobufRpcClientChannel getResource() throws IOException { ProtobufRpcClientChannel result = null; try { int thisRetryCount = 0; do { result = mClientChannelPool.borrowObject(); if(!result.isActive()) { mClientChannelPool.invalidateObject(result); result = null; thisRetryCount += 1; } } while ((result == null) && (thisRetryCount < BORROW_RETRY_COUNT)); } catch (Exception ignore) { } if(result == null) { throw new IOException("Unable to borrow channel resource."); } if(mLogger != null) { String additionalData = null; if(mLogCallingMethod) { @SuppressWarnings("ThrowableNotThrown") StackTraceElement[] stackTraceElementList = (new Throwable()).getStackTrace(); StackTraceElement callingMethod = (stackTraceElementList.length > 1)? stackTraceElementList[1] : null; if(callingMethod != null) { additionalData = "calledFrom: { class: " + callingMethod.getClassName() + ", method: " + callingMethod.getMethodName() + ", file: " + callingMethod.getFileName() + ", line: " + callingMethod.getLineNumber() + " }"; } } mLogger.debug("[ProtobufRpc Pool, " + mLogTag + ", Borrow] { borrowCount: " + mBorrowedObjectCount.incrementAndGet() + ((additionalData != null)? ", " + additionalData : "") + " }"); } return result; } /** * Returns a {@link ProtobufRpcClientChannel} instance to the pool. * * @param clientChannel The instance to return. */ public void returnResource(ProtobufRpcClientChannel clientChannel) { if(mLogger != null) { mLogger.debug("[ProtobufRpc Pool, " + mLogTag + ", Return] { borrowCount: " + mBorrowedObjectCount.decrementAndGet() + " }"); } if(clientChannel.isActive()) { mClientChannelPool.returnObject(clientChannel); } else { try { mClientChannelPool.invalidateObject(clientChannel); } catch (Exception ignore) { } } } }
apache-2.0
innovimax/vxquery
vxquery-core/src/main/java/org/apache/vxquery/compiler/rewriter/rules/ConvertToAlgebricksExpressionsRule.java
6079
/* * 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.vxquery.compiler.rewriter.rules; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.mutable.Mutable; import org.apache.vxquery.compiler.rewriter.rules.util.ExpressionToolbox; import org.apache.vxquery.compiler.rewriter.rules.util.OperatorToolbox; import org.apache.vxquery.functions.BuiltinFunctions; import org.apache.vxquery.functions.BuiltinOperators; import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException; import edu.uci.ics.hyracks.algebricks.core.algebra.base.ILogicalExpression; import edu.uci.ics.hyracks.algebricks.core.algebra.base.ILogicalOperator; import edu.uci.ics.hyracks.algebricks.core.algebra.base.IOptimizationContext; import edu.uci.ics.hyracks.algebricks.core.algebra.base.LogicalExpressionTag; import edu.uci.ics.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression; import edu.uci.ics.hyracks.algebricks.core.algebra.functions.AlgebricksBuiltinFunctions; import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import edu.uci.ics.hyracks.algebricks.core.algebra.functions.IFunctionInfo; import edu.uci.ics.hyracks.algebricks.core.rewriter.base.IAlgebraicRewriteRule; /** * The rule searches for where the XQuery function are used in place of Algebricks builtin function. * The combination the boolean XQuery function and the XQuery equivalent function are replace with * the Algebricks builtin function . * * <pre> * Before * * plan__parent * %OPERATOR( $v1 : boolean(xquery_function( \@input_expression ) ) ) * plan__child * * Where xquery_function creates an atomic value. * * After * * plan__parent * %OPERATOR( $v1 : algebricks_function( \@input_expression ) ) * plan__child * </pre> * * @author prestonc */ public class ConvertToAlgebricksExpressionsRule implements IAlgebraicRewriteRule { final List<Mutable<ILogicalExpression>> functionList = new ArrayList<Mutable<ILogicalExpression>>(); final Map<FunctionIdentifier, FunctionIdentifier> ALGEBRICKS_MAP = new HashMap<FunctionIdentifier, FunctionIdentifier>(); public ConvertToAlgebricksExpressionsRule() { ALGEBRICKS_MAP.put(BuiltinOperators.AND.getFunctionIdentifier(), AlgebricksBuiltinFunctions.AND); ALGEBRICKS_MAP.put(BuiltinOperators.OR.getFunctionIdentifier(), AlgebricksBuiltinFunctions.OR); ALGEBRICKS_MAP.put(BuiltinFunctions.FN_NOT_1.getFunctionIdentifier(), AlgebricksBuiltinFunctions.NOT); ALGEBRICKS_MAP.put(BuiltinOperators.VALUE_EQ.getFunctionIdentifier(), AlgebricksBuiltinFunctions.EQ); ALGEBRICKS_MAP.put(BuiltinOperators.VALUE_NE.getFunctionIdentifier(), AlgebricksBuiltinFunctions.NEQ); ALGEBRICKS_MAP.put(BuiltinOperators.VALUE_LT.getFunctionIdentifier(), AlgebricksBuiltinFunctions.LT); ALGEBRICKS_MAP.put(BuiltinOperators.VALUE_LE.getFunctionIdentifier(), AlgebricksBuiltinFunctions.LE); ALGEBRICKS_MAP.put(BuiltinOperators.VALUE_GT.getFunctionIdentifier(), AlgebricksBuiltinFunctions.GT); ALGEBRICKS_MAP.put(BuiltinOperators.VALUE_GE.getFunctionIdentifier(), AlgebricksBuiltinFunctions.GE); } @Override public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { return false; } @Override public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { boolean modified = false; List<Mutable<ILogicalExpression>> expressions = OperatorToolbox.getExpressions(opRef); for (Mutable<ILogicalExpression> expression : expressions) { if (processExpression(opRef, expression, context)) { modified = true; } } return modified; } private boolean processExpression(Mutable<ILogicalOperator> opRef, Mutable<ILogicalExpression> search, IOptimizationContext context) { boolean modified = false; functionList.clear(); ExpressionToolbox.findAllFunctionExpressions(search, BuiltinFunctions.FN_BOOLEAN_1.getFunctionIdentifier(), functionList); for (Mutable<ILogicalExpression> searchM : functionList) { // Get input function AbstractFunctionCallExpression searchFunction = (AbstractFunctionCallExpression) searchM.getValue(); ILogicalExpression argFirst = searchFunction.getArguments().get(0).getValue(); if (argFirst.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) { continue; } AbstractFunctionCallExpression functionCall = (AbstractFunctionCallExpression) argFirst; if (ALGEBRICKS_MAP.containsKey(functionCall.getFunctionIdentifier())) { FunctionIdentifier algebricksFid = ALGEBRICKS_MAP.get(functionCall.getFunctionIdentifier()); IFunctionInfo algebricksFunction = context.getMetadataProvider().lookupFunction(algebricksFid); functionCall.setFunctionInfo(algebricksFunction); searchM.setValue(argFirst); modified = true; } } return modified; } }
apache-2.0
Ariah-Group/Finance
af_webapp/src/main/java/org/kuali/kfs/coa/businessobject/AccountDelegateModel.java
5885
/* * Copyright 2006 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * 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.kuali.kfs.coa.businessobject; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import org.apache.log4j.Logger; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.rice.core.api.mo.common.active.MutableInactivatable; import org.kuali.rice.krad.bo.PersistableBusinessObjectBase; import org.kuali.rice.krad.service.BusinessObjectService; /** * */ public class AccountDelegateModel extends PersistableBusinessObjectBase implements MutableInactivatable { private static final Logger LOG = Logger.getLogger(AccountDelegateModel.class); private String chartOfAccountsCode; private String organizationCode; private String accountDelegateModelName; private boolean active; private List<AccountDelegateModelDetail> accountDelegateModelDetails; private Organization organization; private Chart chartOfAccounts; /** * Default constructor. */ public AccountDelegateModel() { accountDelegateModelDetails = new ArrayList<AccountDelegateModelDetail>(); } /** * Gets the chartOfAccountsCode attribute. * * @return Returns the chartOfAccountsCode */ public String getChartOfAccountsCode() { return chartOfAccountsCode; } /** * Sets the chartOfAccountsCode attribute. * * @param chartOfAccountsCode The chartOfAccountsCode to set. */ public void setChartOfAccountsCode(String chartOfAccountsCode) { this.chartOfAccountsCode = chartOfAccountsCode; } /** * Gets the organizationCode attribute. * * @return Returns the organizationCode */ public String getOrganizationCode() { return organizationCode; } /** * Sets the organizationCode attribute. * * @param organizationCode The organizationCode to set. */ public void setOrganizationCode(String organizationCode) { this.organizationCode = organizationCode; } /** * Gets the accountDelegateModelName attribute. * * @return Returns the accountDelegateModelName */ public String getAccountDelegateModelName() { return accountDelegateModelName; } /** * Sets the accountDelegateModelName attribute. * * @param accountDelegateModelName The accountDelegateModelName to set. */ public void setAccountDelegateModelName(String organizationRoutingModelName) { this.accountDelegateModelName = organizationRoutingModelName; } /** * Gets the organization attribute. * * @return Returns the organization */ public Organization getOrganization() { return organization; } /** * Sets the organization attribute. * * @param organization The organization to set. * @deprecated */ public void setOrganization(Organization organization) { this.organization = organization; } /** * Gets the chartOfAccounts attribute. * * @return Returns the chartOfAccounts */ public Chart getChartOfAccounts() { return chartOfAccounts; } /** * Sets the chartOfAccounts attribute. * * @param chartOfAccounts The chartOfAccounts to set. * @deprecated */ public void setChartOfAccounts(Chart chartOfAccounts) { this.chartOfAccounts = chartOfAccounts; } /** * Gets the accountDelegateModelDetails attribute. * * @return Returns the accountDelegateModelDetails. */ public List<AccountDelegateModelDetail> getAccountDelegateModelDetails() { return accountDelegateModelDetails; } /** * Sets the accountDelegateModelDetails attribute value. * * @param accountDelegateModelDetails The accountDelegateModelDetails to set. */ public void setAccountDelegateModelDetails(List<AccountDelegateModelDetail> organizationRoutingModel) { this.accountDelegateModelDetails = organizationRoutingModel; } /** * @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper() */ protected LinkedHashMap toStringMapper_RICE20_REFACTORME() { LinkedHashMap m = new LinkedHashMap(); m.put("chartOfAccountsCode", this.chartOfAccountsCode); m.put("organizationCode", this.organizationCode); m.put("accountDelegateModelName", this.accountDelegateModelName); return m; } /** * @see org.kuali.rice.krad.bo.PersistableBusinessObjectBase#linkEditableUserFields() */ @Override public void linkEditableUserFields() { super.linkEditableUserFields(); if (this == null) { throw new IllegalArgumentException("parameter passed in was null"); } List bos = new ArrayList(); bos.addAll(getAccountDelegateModelDetails()); SpringContext.getBean(BusinessObjectService.class).linkUserFields(bos); } /** * Gets the active attribute. * @return Returns the active. */ public boolean isActive() { return active; } /** * Sets the active attribute value. * @param active The active to set. */ public void setActive(boolean active) { this.active = active; } }
apache-2.0
UnifiedPaymentSolutions/everypay-android
android-sdk/src/release/java/com/everypay/sdk/Config.java
150
package com.everypay.sdk; public class Config { public static final boolean DEBUG = false; public static final boolean USE_DEBUG = true; }
apache-2.0
h2oai/h2o-3
h2o-algos/src/main/java/hex/modelselection/ModelSelectionModel.java
16838
package hex.modelselection; import hex.*; import hex.deeplearning.DeepLearningModel; import hex.glm.GLM; import hex.glm.GLMModel; import org.apache.commons.lang.ArrayUtils; import water.*; import water.fvec.Frame; import water.fvec.Vec; import water.udf.CFuncRef; import water.util.TwoDimTable; import java.io.Serializable; import java.util.*; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.Stream; import static hex.glm.GLMModel.GLMParameters.Family.AUTO; import static hex.modelselection.ModelSelectionUtils.*; public class ModelSelectionModel extends Model<ModelSelectionModel, ModelSelectionModel.ModelSelectionParameters, ModelSelectionModel.ModelSelectionModelOutput> { public ModelSelectionModel(Key<ModelSelectionModel> selfKey, ModelSelectionParameters parms, ModelSelectionModelOutput output) { super(selfKey, parms, output); } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { assert domain == null; switch (_output.getModelCategory()) { case Regression: return new ModelMetricsRegression.MetricBuilderRegression(); default: throw H2O.unimpl("Invalid ModelCategory " + _output.getModelCategory()); } } @Override protected double[] score0(double[] data, double[] preds) { throw new UnsupportedOperationException("ModelSelection does not support scoring on data. It only provide " + "information on predictor relevance"); } @Override public Frame score(Frame fr, String destination_key, Job j, boolean computeMetrics, CFuncRef customMetricFunc) { throw new UnsupportedOperationException("AnovaGLM does not support scoring on data. It only provide " + "information on predictor relevance"); } @Override public Frame result() { return _output.generateResultFrame(); } public static class ModelSelectionParameters extends Model.Parameters { public double[] _alpha; public double[] _lambda; public boolean _standardize = true; GLMModel.GLMParameters.Family _family = AUTO; public boolean _lambda_search; public GLMModel.GLMParameters.Link _link = GLMModel.GLMParameters.Link.family_default; public GLMModel.GLMParameters.Solver _solver = GLMModel.GLMParameters.Solver.IRLSM; public String[] _interactions=null; public Serializable _missing_values_handling = GLMModel.GLMParameters.MissingValuesHandling.MeanImputation; public boolean _compute_p_values = false; public boolean _remove_collinear_columns = false; public int _nfolds = 0; // disable cross-validation public Key<Frame> _plug_values = null; public int _max_predictor_number = 1; public int _min_predictor_number = 1; public int _nparallelism = 0; public double _p_values_threshold = 0; public double _tweedie_variance_power; public double _tweedie_link_power; public Mode _mode = Mode.maxr; // mode chosen to perform model selection public enum Mode { allsubsets, // use combinatorial, exponential runtime maxr, // use sequential replacement backward // use backward selection } @Override public String algoName() { return "ModelSelection"; } @Override public String fullName() { return "Model Selection"; } @Override public String javaName() { return ModelSelectionModel.class.getName(); } @Override public long progressUnits() { return 1; } public GLMModel.GLMParameters.MissingValuesHandling missingValuesHandling() { if (_missing_values_handling instanceof GLMModel.GLMParameters.MissingValuesHandling) return (GLMModel.GLMParameters.MissingValuesHandling) _missing_values_handling; assert _missing_values_handling instanceof DeepLearningModel.DeepLearningParameters.MissingValuesHandling; switch ((DeepLearningModel.DeepLearningParameters.MissingValuesHandling) _missing_values_handling) { case MeanImputation: return GLMModel.GLMParameters.MissingValuesHandling.MeanImputation; case Skip: return GLMModel.GLMParameters.MissingValuesHandling.Skip; default: throw new IllegalStateException("Unsupported missing values handling value: " + _missing_values_handling); } } public boolean imputeMissing() { return missingValuesHandling() == GLMModel.GLMParameters.MissingValuesHandling.MeanImputation || missingValuesHandling() == GLMModel.GLMParameters.MissingValuesHandling.PlugValues; } public DataInfo.Imputer makeImputer() { if (missingValuesHandling() == GLMModel.GLMParameters.MissingValuesHandling.PlugValues) { if (_plug_values == null || _plug_values.get() == null) { throw new IllegalStateException("Plug values frame needs to be specified when Missing Value Handling = PlugValues."); } return new GLM.PlugValuesImputer(_plug_values.get()); } else { // mean/mode imputation and skip (even skip needs an imputer right now! PUBDEV-6809) return new DataInfo.MeanImputer(); } } } public static class ModelSelectionModelOutput extends Model.Output { GLMModel.GLMParameters.Family _family; DataInfo _dinfo; String[][] _best_model_predictors; // store for each predictor number, the best model predictors double[] _best_r2_values; // store the best R2 values of the best models with fix number of predictors public Key[] _best_model_ids; String[][] _coefficient_names; double[][] _coef_p_values; double[][] _z_values; public ModelSelectionModelOutput(hex.modelselection.ModelSelection b, DataInfo dinfo) { super(b, dinfo._adaptedFrame); _dinfo = dinfo; } public String[][] coefficientNames() { return _coefficient_names; } public double[][] beta() { int numModel = _best_model_ids.length; double[][] coeffs = new double[numModel][]; for (int index=0; index < numModel; index++) { GLMModel oneModel = DKV.getGet(_best_model_ids[index]); coeffs[index] = oneModel._output.beta().clone(); } return coeffs; } public double[][] getNormBeta() { int numModel = _best_model_ids.length; double[][] coeffs = new double[numModel][]; for (int index=0; index < numModel; index++) { GLMModel oneModel = DKV.getGet(_best_model_ids[index]); coeffs[index] = oneModel._output.getNormBeta().clone(); } return coeffs; } @Override public ModelCategory getModelCategory() { return ModelCategory.Regression; } private Frame generateResultFrame() { int numRows = _best_model_predictors.length; String[] modelNames = new String[numRows]; String[] predNames = new String[numRows]; String[] modelIds = Stream.of(_best_model_ids).map(Key::toString).toArray(String[]::new); String[] zvalues = new String[numRows]; String[] pvalues = new String[numRows]; boolean backwardMode = _z_values!=null; // generate model names and predictor names for (int index=0; index < numRows; index++) { int numPred = _best_model_predictors[index].length; modelNames[index] = "best "+numPred+" predictor(s) model"; predNames[index] = backwardMode ? String.join(", ", _coefficient_names[index]) :String.join(", ", _best_model_predictors[index]); if (backwardMode) { zvalues[index] = joinDouble(_z_values[index]); pvalues[index] = joinDouble(_coef_p_values[index]); } } // generate vectors before forming frame Vec.VectorGroup vg = Vec.VectorGroup.VG_LEN1; Vec modNames = Vec.makeVec(modelNames, vg.addVec()); Vec modelIDV = Vec.makeVec(modelIds, vg.addVec()); Vec r2=null; Vec zval=null; Vec pval=null; if (backwardMode) { zval = Vec.makeVec(zvalues, vg.addVec()); pval = Vec.makeVec(pvalues, vg.addVec()); } else { r2 = Vec.makeVec(_best_r2_values, vg.addVec()); } Vec predN = Vec.makeVec(predNames, vg.addVec()); if (backwardMode) { String[] colNames = new String[]{"model_name", "model_id", "z_values", "p_values", "coefficient_names"}; return new Frame(Key.<Frame>make(), colNames, new Vec[]{modNames, modelIDV, zval, pval, predN}); } else { String[] colNames = new String[]{"model_name", "model_id", "best_r2_value", "predictor_names"}; return new Frame(Key.<Frame>make(), colNames, new Vec[]{modNames, modelIDV, r2, predN}); } } public void shrinkArrays(int numModelsBuilt) { if (_best_model_predictors.length > numModelsBuilt) { _best_model_predictors = shrinkStringArray(_best_model_predictors, numModelsBuilt); _coefficient_names = shrinkStringArray(_coefficient_names, numModelsBuilt); _z_values = shrinkDoubleArray(_z_values, numModelsBuilt); _coef_p_values = shrinkDoubleArray(_coef_p_values, numModelsBuilt); _best_model_ids = shrinkKeyArray(_best_model_ids, numModelsBuilt); } } public void generateSummary() { int numModels = _best_r2_values.length; String[] names = new String[]{"best r2 value", "predictor names"}; String[] types = new String[]{"double", "String"}; String[] formats = new String[]{"%d", "%s"}; String[] rowHeaders = new String[numModels]; for (int index=1; index<=numModels; index++) rowHeaders[index-1] = "with "+index+" predictors"; _model_summary = new TwoDimTable("ModelSelection Model Summary", "summary", rowHeaders, names, types, formats, ""); for (int rIndex=0; rIndex < numModels; rIndex++) { int colInd = 0; _model_summary.set(rIndex, colInd++, _best_r2_values[rIndex]); _model_summary.set(rIndex, colInd++, String.join(", ", _best_model_predictors[rIndex])); } } public void generateSummary(int numModels) { String[] names = new String[]{"coefficient names", "z values", "p values"}; String[] types = new String[]{"string", "string", "string"}; String[] formats = new String[]{"%s", "%s", "%s"}; String[] rowHeaders = new String[numModels]; for (int index=0; index < numModels; index++) { rowHeaders[index] = "with "+_best_model_predictors[index].length+" predictors"; } _model_summary = new TwoDimTable("ModelSlection Model Summary", "summary", rowHeaders, names, types, formats, ""); for (int rIndex=0; rIndex < numModels; rIndex++) { int colInd = 0; String pValue = joinDouble(_coef_p_values[rIndex]); String zValue = joinDouble(_z_values[rIndex]); String coeffNames = String.join(", ", _coefficient_names[rIndex]); _model_summary.set(rIndex, colInd++, coeffNames); _model_summary.set(rIndex, colInd++, zValue); _model_summary.set(rIndex, colInd++, pValue); } } void updateBestModels(GLMModel bestModel, int index) { _best_model_ids[index] = bestModel.getKey(); if (bestModel._parms._nfolds > 0) { int r2Index = Arrays.asList(bestModel._output._cross_validation_metrics_summary.getRowHeaders()).indexOf("r2"); Float tempR2 = (Float) bestModel._output._cross_validation_metrics_summary.get(r2Index, 0); _best_r2_values[index] = tempR2.doubleValue(); } else { _best_r2_values[index] = bestModel.r2(); } extractCoeffs(bestModel, index); } void extractCoeffs(GLMModel model, int index) { _coefficient_names[index] = model._output.coefficientNames().clone(); // all coefficients ArrayList<String> coeffNames = new ArrayList<>(Arrays.asList(model._output.coefficientNames())); coeffNames.remove(coeffNames.size()-1); // remove intercept as it is not a predictor _best_model_predictors[index] = coeffNames.toArray(new String[0]); // without intercept } /*** * Eliminate predictors with lowest z-value (z-score) magnitude as described in III of * ModelSelectionTutorial.pdf in https://h2oai.atlassian.net/browse/PUBDEV-8428 */ void extractPredictors4NextModel(GLMModel model, int index, List<String> predNames, List<Integer> predIndices) { extractCoeffs(model, index); _best_model_ids[index] = model.getKey(); List<Double> zValList = Arrays.stream(model._output.zValues()).boxed().map(Math::abs).collect(Collectors.toList()); zValList.remove(zValList.size()-1); // remove intercept terms int minZInd = zValList.indexOf(zValList.stream().min(Double::compare).get()); // find min magnitude String minZvalPred = _best_model_predictors[index][minZInd]; int predIndex = predNames.indexOf(minZvalPred); predIndices.remove(predIndices.indexOf(predIndex)); _z_values[index] = model._output.zValues().clone(); _coef_p_values[index] = model._output.pValues().clone(); } } @Override protected Futures remove_impl(Futures fs, boolean cascade) { super.remove_impl(fs, cascade); if (cascade && _output._best_model_ids != null && _output._best_model_ids.length > 0) { for (Key oneModelID : _output._best_model_ids) if (null != oneModelID) Keyed.remove(oneModelID, fs, cascade); // remove model key } return fs; } @Override protected AutoBuffer writeAll_impl(AutoBuffer ab) { if (_output._best_model_ids != null && _output._best_model_ids.length > 0) { for (Key oneModelID : _output._best_model_ids) if (null != oneModelID) ab.putKey(oneModelID); // add GLM model key } return super.writeAll_impl(ab); } @Override protected Keyed readAll_impl(AutoBuffer ab, Futures fs) { if (_output._best_model_ids != null && _output._best_model_ids.length > 0) { for (Key oneModelID : _output._best_model_ids) { if (null != oneModelID) ab.getKey(oneModelID, fs); // add GLM model key } } return super.readAll_impl(ab, fs); } public HashMap<String, Double>[] coefficients() { return coefficients(false); } public HashMap<String, Double>[] coefficients(boolean standardize) { int numModel = _output._best_model_ids.length; HashMap<String, Double>[] coeffs = new HashMap[numModel]; for (int index=0; index < numModel; index++) { coeffs[index] = coefficients(index+1, standardize); } return coeffs; } public HashMap<String, Double> coefficients(int predictorSize) { return coefficients(predictorSize, false); } public HashMap<String, Double> coefficients(int predictorSize, boolean standardize) { int numModel = _output._best_model_ids.length; if (predictorSize <= 0 || predictorSize > numModel) throw new IllegalArgumentException("predictorSize must be between 1 and maximum size of predictor subset" + " size."); GLMModel oneModel = DKV.getGet(_output._best_model_ids[predictorSize-1]); return oneModel.coefficients(standardize); } }
apache-2.0
eiichiro/bootleg
src/main/java/org/eiichiro/bootleg/Types.java
16178
/* * Copyright (C) 2011-2013 Eiichiro Uchiumi. 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 org.eiichiro.bootleg; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.sql.Timestamp; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Deque; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.TreeSet; import java.util.Vector; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.SynchronousQueue; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.Converter; import org.apache.commons.beanutils.converters.DateConverter; import org.apache.commons.lang.ClassUtils; /** * {@code Types} is a type system utility for Bootleg built-in components. * * @author <a href="mailto:mail@eiichiro.org">Eiichiro Uchiumi</a> */ public abstract class Types { private Types() {} private static Set<Class<?>> builtins = new CopyOnWriteArraySet<Class<?>>(); private static Set<Class<?>> collections = new CopyOnWriteArraySet<Class<?>>(); private static Set<Class<?>> values = new CopyOnWriteArraySet<Class<?>>(); private static Map<Class<?>, Class<?>> implementations = new ConcurrentHashMap<Class<?>, Class<?>>(); private static Map<Class<?>, Collection<?>> empties = new ConcurrentHashMap<Class<?>, Collection<?>>(); static { // Built-in types. builtins.add(WebContext.class); builtins.add(HttpServletRequest.class); builtins.add(HttpServletResponse.class); builtins.add(HttpSession.class); builtins.add(ServletContext.class); builtins.add(Request.class); // Interfaces. collections.add(Collection.class); collections.add(List.class); collections.add(Set.class); collections.add(SortedSet.class); collections.add(NavigableSet.class); collections.add(Queue.class); collections.add(Deque.class); // Implementations. collections.add(ArrayList.class); collections.add(LinkedList.class); collections.add(CopyOnWriteArrayList.class); collections.add(Stack.class); collections.add(Vector.class); collections.add(HashSet.class); collections.add(LinkedHashSet.class); collections.add(CopyOnWriteArraySet.class); collections.add(TreeSet.class); collections.add(ConcurrentSkipListSet.class); collections.add(PriorityQueue.class); collections.add(ConcurrentLinkedQueue.class); collections.add(DelayQueue.class); collections.add(ArrayBlockingQueue.class); collections.add(LinkedBlockingQueue.class); collections.add(PriorityBlockingQueue.class); collections.add(SynchronousQueue.class); collections.add(ArrayDeque.class); collections.add(LinkedBlockingDeque.class); // Value types. values.add(Boolean.TYPE); values.add(Byte.TYPE); values.add(Character.TYPE); values.add(Double.TYPE); values.add(Float.TYPE); values.add(Integer.TYPE); values.add(Long.TYPE); values.add(Short.TYPE); values.add(BigDecimal.class); values.add(BigInteger.class); values.add(Boolean.class); values.add(Byte.class); values.add(Character.class); values.add(Double.class); values.add(Float.class); values.add(Integer.class); values.add(Long.class); values.add(Short.class); values.add(String.class); values.add(Class.class); values.add(java.util.Date.class); values.add(Calendar.class); values.add(File.class); values.add(java.sql.Date.class); values.add(java.sql.Time.class); values.add(Timestamp.class); values.add(URL.class); values.add(Object.class); // XXX: :-/ DateConverter converter = new DateConverter(); converter.setUseLocaleFormat(true); ConvertUtils.register(converter, Date.class); // Default collection implementations. implementations.put(Collection.class, ArrayList.class); implementations.put(List.class, ArrayList.class); implementations.put(Set.class, HashSet.class); implementations.put(SortedSet.class, TreeSet.class); implementations.put(NavigableSet.class, TreeSet.class); implementations.put(Queue.class, PriorityQueue.class); implementations.put(Deque.class, ArrayDeque.class); // Empty collections. empties.put(Collection.class, Collections.EMPTY_LIST); empties.put(List.class, Collections.EMPTY_LIST); empties.put(Set.class, Collections.EMPTY_SET); empties.put(SortedSet.class, new TreeSet<Object>()); empties.put(NavigableSet.class, new TreeSet<Object>()); empties.put(Queue.class, new PriorityQueue<Object>()); empties.put(Deque.class, new ArrayDeque<Object>(0)); empties.put(ArrayList.class, new ArrayList<Object>(0)); empties.put(LinkedList.class, new LinkedList<Object>()); empties.put(CopyOnWriteArrayList.class, new CopyOnWriteArrayList<Object>()); empties.put(Stack.class, new Stack<Object>()); empties.put(Vector.class, new Vector<Object>(0)); empties.put(HashSet.class, new HashSet<Object>(0)); empties.put(LinkedHashSet.class, new LinkedHashSet<Object>(0)); empties.put(CopyOnWriteArraySet.class, new CopyOnWriteArraySet<Object>()); empties.put(TreeSet.class, new TreeSet<Object>()); empties.put(ConcurrentSkipListSet.class, new ConcurrentSkipListSet<Object>()); empties.put(PriorityQueue.class, new PriorityQueue<Object>()); empties.put(ConcurrentLinkedQueue.class, new ConcurrentLinkedQueue<Object>()); empties.put(DelayQueue.class, new DelayQueue<Delayed>()); empties.put(ArrayBlockingQueue.class, new ArrayBlockingQueue<Object>(1)); empties.put(LinkedBlockingQueue.class, new LinkedBlockingDeque<Object>()); empties.put(PriorityBlockingQueue.class, new PriorityBlockingQueue<Object>()); empties.put(SynchronousQueue.class, new SynchronousQueue<Object>()); empties.put(ArrayDeque.class, new ArrayDeque<Object>()); empties.put(LinkedBlockingDeque.class, new LinkedBlockingDeque<Object>()); } /** * Returns <code>true</code> if the specified <code>type</code> is a * built-in type. * * @param type The type to be tested. * @return <code>true</code> if the specified <code>type</code> is a * built-in type. */ public static boolean isBuiltinType(Type type) { Class<?> rawType = getRawType(type); return (rawType == null) ? false : builtins.contains(rawType); } /** * Returns <code>true</code> if the specified <code>type</code> is an * instance of {@code Collection}. * * @param type The type to be tested. * @return <code>true</code> if the specified <code>type</code> is an * instance of {@code Collection}. */ public static boolean isCollection(Type type) { Class<?> rawType = getRawType(type); return (rawType == null) ? false : (rawType.equals(Collection.class) || ClassUtils.getAllInterfaces(rawType).contains(Collection.class)); } /** * Returns <code>true</code> if the specified <code>type</code> is an * instance of supported {@code Collection}.<br> * <br> * Supported collections are: * <pre> * java.util.Collection * java.util.List * java.util.Set * java.util.SortedSet * java.util.NavigableSet * java.util.Queue * java.util.Deque * * java.util.ArrayList * java.util.LinkedList * java.util.concurrent.CopyOnWriteArrayList * java.util.Stack * java.util.Vector * java.util.HashSet * java.util.LinkedHashSet * java.util.concurrent.CopyOnWriteArraySet * java.util.TreeSet * java.util.concurrent.ConcurrentSkipListSet * java.util.PriorityQueue * java.util.concurrent.ConcurrentLinkedQueue * java.util.concurrent.PriorityBlockingQueue * java.util.concurrent.DelayQueue * java.util.concurrent.LinkedBlockingQueue * java.util.concurrent.PriorityBlockingQueue * java.util.ArrayDeque * java.util.concurrent.LinkedBlockingDeque * java.util.concurrent.SynchronousQueue * </pre> * * @param type The type to be tested. * @return <code>true</code> if the specified <code>type</code> is an * instance of supported {@code Collection}.<br> */ public static boolean isSupportedCollection(Type type) { Class<?> rawType = getRawType(type); return (rawType == null) ? false : collections.contains(rawType); } /** * Returns <code>true</code> if the specified <code>type</code> is an array * type. * * @param type The type to be tested. * @return <code>true</code> if the specified <code>type</code> is an array * type. */ public static boolean isArray(Type type) { if (type instanceof GenericArrayType) { return true; } else if (type instanceof Class<?>) { return ((Class<?>) type).isArray(); } else { return false; } } /** * Returns the element type of the specified collection type. * The specified type must be collection or array. To make it sure, use * {@code #isCollection(Type)} method or {@code #isArray(Type)} method. * * @param type Collection or array type. * @return The element type of the specified collection or array. * @throws IllegalArgumentException If the specified 'type' is not a * collection or array. */ public static Class<?> getElementType(Type type) { if (isCollection(type)) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return (Class<?>) parameterizedType.getActualTypeArguments()[0]; } else { return Object.class; } } else if (isArray(type)) { if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; return (Class<?>) genericArrayType.getGenericComponentType(); } else { Class<?> clazz = (Class<?>) type; return clazz.getComponentType(); } } else { throw new IllegalArgumentException("'type' must be a collection or array"); } } /** * Returns the default implementation type of the specified collection * interface type. * The specified type must be an supported collection. To make it sure, use * {@code #isSupportedCollection(Type)}. If the specified collection type is * <b>not</b> an interface, this method returns the specified implementation * type directly.<br> * <br> * The default implementations are: * <pre> * java.util.Collection -> java.util.ArrayList * java.util.List -> java.util.ArrayList * java.util.Set -> java.util.HashSet * java.util.SortedSet -> java.util.TreeSet * java.util.NavigableSet -> java.util.TreeSet * java.util.Queue -> java.util.PriorityQueue * java.util.Deque -> java.util.ArrayDeque * </pre> * * @param type Collection type (must be supported type). * @return The default implementation type of the specified collection * interface type. */ public static Class<?> getDefaultImplementationType(Type type) { Class<?> clazz = getRawType(type); return (clazz.isInterface()) ? implementations.get(clazz) : clazz; } /** * Returns the empty instance of the specified collection type. * * @param type The collection type (must be supported type). * @return The empty instance of the specified collection type. */ public static Collection<?> getEmptyCollection(Type type) { return empties.get(getRawType(type)); } /** * Returns <code>true</code> if the specified <code>type</code> is a * supported core value type.<br> * <br> * Supported core value types are: * <pre> * boolean * byte * char * double * float * int * long * short * java.math.BigDecimal * java.math.BigInteger * Boolean * Byte * Character * Double * Float * Integer * Long * Short * String * Class * java.util.Date * java.util.Calendar * java.io.File * java.sql.Date * java.sql.Time * java.sql.Timestamp * java.net.URL * Object * </pre> * * @param type The type to be tested. * @return <code>true</code> if the specified type is supported core value * type. */ public static boolean isCoreValueType(Type type) { Class<?> rawType = getRawType(type); return (rawType == null) ? false : values.contains(rawType); } /** * Returns <code>true</code> if the specified type is an user define value * type. * User defined value type must satisfy either of the following condition. * <ol> * <li>(The class) has a public constructor that takes one String.class parameter.</li> * <li>Has a public static factory method that named 'valueOf' and takes one * String.class parameter.</li> * </ol> * * @param type The type to be tested. * @return <code>true</code> if the specified type is an user define value * type. */ public static boolean isUserDefinedValueType(Type type) { Class<?> rawType = getRawType(type); if (rawType == null) { return false; } for (Constructor<?> constructor : rawType.getConstructors()) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0].equals(String.class)) { return true; } } for (Method method : rawType.getMethods()) { if (method.getName().equals("valueOf") && Modifier.isStatic(method.getModifiers())) { return true; } } return false; } /** * Adds supported core value type. * * @param clazz The core value type. * @param converter Converter for the specified core value type. */ public static void addCoreValueType(Class<?> clazz, Converter converter) { ConvertUtils.register(converter, clazz); values.add(clazz); } /** * Returns <code>true</code> if the specified <code>type</code> is a * primitive type. * * @param type The type to be tested. * @return <code>true</code> if the specified type is a primitive type. */ public static boolean isPrimitive(Type type) { return (type instanceof Class<?>) ? ((Class<?>) type).isPrimitive() : false; } /** * Returns the raw type of the specified type. * This method supports {@code ParameterizedType} or raw {@code Class} * (just returns it directly). The other types such as array type are not * supported. If the specified 'type' is not supported, this method returns * <code>null</code>. * * @param type The type to be tested. * @return The raw type of the specified type. */ public static Class<?> getRawType(Type type) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return (Class<?>) parameterizedType.getRawType(); } else if (type instanceof Class<?>) { Class<?> clazz = (Class<?>) type; return (clazz.isArray()) ? null : clazz; } else { return null; } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-kinesisvideo/src/main/java/com/amazonaws/services/kinesisvideo/model/HLSDisplayFragmentTimestamp.java
1854
/* * Copyright 2017-2022 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.kinesisvideo.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum HLSDisplayFragmentTimestamp { ALWAYS("ALWAYS"), NEVER("NEVER"); private String value; private HLSDisplayFragmentTimestamp(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return HLSDisplayFragmentTimestamp corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static HLSDisplayFragmentTimestamp fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (HLSDisplayFragmentTimestamp enumEntry : HLSDisplayFragmentTimestamp.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
apache-2.0
adaptris/interlok
interlok-core/src/test/java/com/adaptris/interlok/junit/scaffolding/jms/JndiImplementationCase.java
13208
/* * Copyright 2015 Adaptris Ltd. * * 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.adaptris.interlok.junit.scaffolding.jms; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import com.adaptris.core.StandaloneProducer; import com.adaptris.core.jms.JmsConnection; import com.adaptris.core.jms.JmsConnectionConfig; import com.adaptris.core.jms.PasProducer; import com.adaptris.core.jms.VendorImplementation; import com.adaptris.core.jms.activemq.EmbeddedActiveMq; import com.adaptris.core.jms.activemq.RequiresCredentialsBroker; import com.adaptris.core.jms.jndi.BaseJndiImplementation; import com.adaptris.core.jms.jndi.NoOpFactoryConfiguration; import com.adaptris.core.jms.jndi.SimpleFactoryConfiguration; import com.adaptris.core.jms.jndi.StandardJndiImplementation; import com.adaptris.core.util.LifecycleHelper; import com.adaptris.security.password.Password; import com.adaptris.util.KeyValuePair; import com.adaptris.util.KeyValuePairSet; import com.adaptris.util.TimeInterval; public abstract class JndiImplementationCase { protected abstract StandardJndiImplementation createVendorImplementation(); @Rule public TestName testName = new TestName(); private static EmbeddedActiveMq activeMqBroker; @BeforeClass public static void setUpAll() throws Exception { activeMqBroker = new EmbeddedActiveMq(); activeMqBroker.start(); } @AfterClass public static void tearDownAll() throws Exception { if(activeMqBroker != null) activeMqBroker.destroy(); } @Test public void testSetEnableJndiForQueues() throws Exception { BaseJndiImplementation vendorImp = createVendorImplementation(); assertNull(vendorImp.getUseJndiForQueues()); assertFalse(vendorImp.useJndiForQueues()); vendorImp.setUseJndiForQueues(Boolean.TRUE); assertNotNull(vendorImp.getUseJndiForQueues()); assertTrue(vendorImp.useJndiForQueues()); vendorImp.setUseJndiForQueues(null); assertNull(vendorImp.getUseJndiForQueues()); assertFalse(vendorImp.useJndiForQueues()); } @Test public void testSetEnableJndiForTopics() throws Exception { BaseJndiImplementation vendorImp = createVendorImplementation(); assertNull(vendorImp.getUseJndiForTopics()); assertFalse(vendorImp.useJndiForTopics()); vendorImp.setUseJndiForTopics(Boolean.TRUE); assertNotNull(vendorImp.getUseJndiForTopics()); assertTrue(vendorImp.useJndiForTopics()); vendorImp.setUseJndiForTopics(null); assertNull(vendorImp.getUseJndiForTopics()); assertFalse(vendorImp.useJndiForTopics()); } @Test public void testSetEnableEncodedPasswords() throws Exception { BaseJndiImplementation vendorImp = createVendorImplementation(); assertNull(vendorImp.getEnableEncodedPasswords()); assertFalse(vendorImp.enableEncodedPasswords()); vendorImp.setEnableEncodedPasswords(Boolean.TRUE); assertNotNull(vendorImp.getEnableEncodedPasswords()); assertTrue(vendorImp.enableEncodedPasswords()); vendorImp.setEnableEncodedPasswords(null); assertNull(vendorImp.getEnableEncodedPasswords()); assertFalse(vendorImp.enableEncodedPasswords()); } @Test public void testSetNewContextOnException() throws Exception { BaseJndiImplementation jv = createVendorImplementation(); assertNull(jv.getNewContextOnException()); assertFalse(jv.newContextOnException()); jv.setNewContextOnException(Boolean.TRUE); assertEquals(Boolean.TRUE, jv.getNewContextOnException()); assertTrue(jv.newContextOnException()); jv.setNewContextOnException(null); assertNull(jv.getNewContextOnException()); assertFalse(jv.newContextOnException()); } @Test public void testSetJndiName() throws Exception { BaseJndiImplementation jv = createVendorImplementation(); jv.setJndiName("ABCDE"); assertEquals("ABCDE", jv.getJndiName()); try { jv.setJndiName(""); fail(); } catch (IllegalArgumentException expected) { } assertEquals("ABCDE", jv.getJndiName()); try { jv.setJndiName(null); fail(); } catch (IllegalArgumentException expected) { } assertEquals("ABCDE", jv.getJndiName()); } @Test public void testSetExtraConfiguration() throws Exception { BaseJndiImplementation jv = createVendorImplementation(); assertEquals(NoOpFactoryConfiguration.class, jv.getExtraFactoryConfiguration().getClass()); jv.setExtraFactoryConfiguration(new SimpleFactoryConfiguration()); assertEquals(SimpleFactoryConfiguration.class, jv.getExtraFactoryConfiguration().getClass()); try { jv.setExtraFactoryConfiguration(null); fail(); } catch (IllegalArgumentException expected) { } assertEquals(SimpleFactoryConfiguration.class, jv.getExtraFactoryConfiguration().getClass()); } @Test public void testSetJndiParams() throws Exception { BaseJndiImplementation jv = createVendorImplementation(); KeyValuePairSet set = new KeyValuePairSet(); jv.setJndiParams(set); assertEquals(set, jv.getJndiParams()); try { jv.setJndiParams(null); fail(); } catch (IllegalArgumentException expected) { } assertEquals(set, jv.getJndiParams()); } @Test public void testInitialiseDefaultArtemisBroker() throws Exception { String topicName = testName.getMethodName() + "_topic"; PasProducer producer = new PasProducer().withTopic(topicName); JmsConnection c = activeMqBroker.getJmsConnection(); StandaloneProducer standaloneProducer = new StandaloneProducer(c, producer); try { LifecycleHelper.init(standaloneProducer); } finally { LifecycleHelper.close(standaloneProducer); } } @Test public void testInitialiseWithCredentials() throws Exception { String queueName = testName.getMethodName() + "_queue"; String topicName = testName.getMethodName() + "_topic"; PasProducer producer = new PasProducer().withTopic(topicName);; StandardJndiImplementation jv = createVendorImplementation(); JmsConnection c = activeMqBroker.getJndiPasConnection(jv, false, queueName, topicName); jv.getJndiParams().addKeyValuePair(new KeyValuePair("UserName", RequiresCredentialsBroker.DEFAULT_USERNAME)); jv.getJndiParams().addKeyValuePair(new KeyValuePair("Password", RequiresCredentialsBroker.DEFAULT_PASSWORD)); StandaloneProducer standaloneProducer = new StandaloneProducer(c, producer); try { LifecycleHelper.init(standaloneProducer); } finally { LifecycleHelper.close(standaloneProducer); } } @Test public void testInitialiseWithEncryptedPassword_viaEncodedPasswordKeys() throws Exception { RequiresCredentialsBroker broker = new RequiresCredentialsBroker(); String queueName = testName.getMethodName() + "_queue"; String topicName = testName.getMethodName() + "_topic"; PasProducer producer = new PasProducer().withTopic(queueName); StandardJndiImplementation jv = createVendorImplementation(); JmsConnection c = broker.getJndiPasConnection(jv, false, queueName, topicName); jv.getJndiParams().addKeyValuePair(new KeyValuePair("UserName", RequiresCredentialsBroker.DEFAULT_USERNAME)); jv.getJndiParams().addKeyValuePair( new KeyValuePair("Password", Password.encode(RequiresCredentialsBroker.DEFAULT_PASSWORD, Password.PORTABLE_PASSWORD))); jv.setEncodedPasswordKeys("Password"); StandaloneProducer standaloneProducer = new StandaloneProducer(c, producer); try { broker.start(); LifecycleHelper.init(standaloneProducer); } finally { LifecycleHelper.close(standaloneProducer); broker.destroy(); } } @Test public void testInitialiseWithEncryptedPassword_withEnableEncodedPasswords() throws Exception { String queueName = testName.getMethodName() + "_queue"; String topicName = testName.getMethodName() + "_topic"; RequiresCredentialsBroker broker = new RequiresCredentialsBroker(); PasProducer producer = new PasProducer().withTopic(queueName); StandardJndiImplementation jv = createVendorImplementation(); JmsConnection c = broker.getJndiPasConnection(jv, false, queueName, topicName); jv.getJndiParams().addKeyValuePair(new KeyValuePair("UserName", RequiresCredentialsBroker.DEFAULT_USERNAME)); jv.getJndiParams().addKeyValuePair( new KeyValuePair("Password", Password.encode(RequiresCredentialsBroker.DEFAULT_PASSWORD, Password.PORTABLE_PASSWORD))); jv.setEncodedPasswordKeys("Password"); jv.setEnableEncodedPasswords(true); StandaloneProducer standaloneProducer = new StandaloneProducer(c, producer); try { broker.start(); LifecycleHelper.init(standaloneProducer); } finally { LifecycleHelper.close(standaloneProducer); broker.destroy(); } } @Test public void testInitialiseWithEncryptedPasswordNotSupported() throws Exception { RequiresCredentialsBroker broker = new RequiresCredentialsBroker(); String queueName = testName.getMethodName() + "_queue"; String topicName = testName.getMethodName() + "_topic"; PasProducer producer = new PasProducer().withTopic(queueName); StandardJndiImplementation jv = createVendorImplementation(); JmsConnection c = broker.getJndiPasConnection(jv, false, queueName, topicName); jv.getJndiParams().addKeyValuePair(new KeyValuePair("UserName", RequiresCredentialsBroker.DEFAULT_USERNAME)); jv.getJndiParams().addKeyValuePair( new KeyValuePair("Password", Password.encode(RequiresCredentialsBroker.DEFAULT_PASSWORD, Password.PORTABLE_PASSWORD))); StandaloneProducer standaloneProducer = new StandaloneProducer(c, producer); try { broker.start(); LifecycleHelper.init(standaloneProducer); fail("Encrypted password should not be supported, as not explicitly configured"); } catch (Exception e) { // expected } finally { broker.destroy(); } } @Test public void testInitialiseWithTopicConnectionFactoryNotFound() throws Exception { String queueName = testName.getMethodName() + "_queue"; String topicName = testName.getMethodName() + "_topic"; PasProducer producer = new PasProducer().withTopic(queueName); StandardJndiImplementation jv = createVendorImplementation(); JmsConnection c = activeMqBroker.getJndiPasConnection(jv, false, queueName, topicName); c.setConnectionAttempts(1); c.setConnectionRetryInterval(new TimeInterval(100L, TimeUnit.MILLISECONDS.name())); jv.setJndiName("testInitialiseWithTopicConnectionFactoryNotFound"); StandaloneProducer standaloneProducer = new StandaloneProducer(c, producer); try { LifecycleHelper.init(standaloneProducer); fail("Should Fail to lookup 'testInitialiseWithTopicConnectionFactoryNotFound'"); } catch (Exception e) { // expected } } @Test public void testInitialiseWithQueueConnectionFactoryNotFound() throws Exception { String queueName = testName.getMethodName() + "_queue"; String topicName = testName.getMethodName() + "_topic"; PasProducer producer = new PasProducer().withTopic((topicName)); StandardJndiImplementation jv = createVendorImplementation(); JmsConnection c = activeMqBroker.getJndiPtpConnection(jv, false, queueName, topicName); c.setConnectionAttempts(1); c.setConnectionRetryInterval(new TimeInterval(100L, TimeUnit.MILLISECONDS)); jv.setJndiName("testInitialiseWithQueueConnectionFactoryNotFound"); StandaloneProducer standaloneProducer = new StandaloneProducer(c, producer); try { LifecycleHelper.init(standaloneProducer); fail("Should Fail to lookup 'testInitialiseWithQueueConnectionFactoryNotFound'"); } catch (Exception e) { // expected } } protected class StubJndiJmsConnectionConfig implements JmsConnectionConfig { public StubJndiJmsConnectionConfig() { } @Override public String configuredClientId() { return "StubJndiJmsConnectionConfig"; } @Override public String configuredPassword() { return null; } @Override public String configuredUserName() { return null; } @Override public VendorImplementation configuredVendorImplementation() { return new StandardJndiImplementation(); } } }
apache-2.0
ldlood/SpringBoot_Wechat_Sell
src/main/java/com/ldlood/repository/OrderMasterRepository.java
553
package com.ldlood.repository; import com.ldlood.dataobject.OrderMaster; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by Ldlood on 2017/7/21. */ public interface OrderMasterRepository extends JpaRepository<OrderMaster, String> { /** * 通过openid查找订单 * @param buyerOpenid * @param pageable * @return */ Page<OrderMaster> findByBuyerOpenid(String buyerOpenid, Pageable pageable); }
apache-2.0
jmapper-framework/jmapper-test
JMapper Test/src/test/java/com/googlecode/jmapper/integrationtest/configurations/bean/JGlobalMapS2.java
1703
package com.googlecode.jmapper.integrationtest.configurations.bean; public class JGlobalMapS2 { private String field; private String field2; private String field3; public JGlobalMapS2() {} public JGlobalMapS2(String field, String field2, String field3) { super(); this.field = field; this.field2 = field2; this.field3 = field3; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getField2() { return field2; } public void setField2(String field2) { this.field2 = field2; } public String getField3() { return field3; } public void setField3(String field3) { this.field3 = field3; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((field == null) ? 0 : field.hashCode()); result = prime * result + ((field2 == null) ? 0 : field2.hashCode()); result = prime * result + ((field3 == null) ? 0 : field3.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JGlobalMapS2 other = (JGlobalMapS2) obj; if (field == null) { if (other.field != null) return false; } else if (!field.equals(other.field)) return false; if (field2 == null) { if (other.field2 != null) return false; } else if (!field2.equals(other.field2)) return false; if (field3 == null) { if (other.field3 != null) return false; } else if (!field3.equals(other.field3)) return false; return true; } }
apache-2.0
mattxia/spring-2.5-analysis
tiger/src/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessor.java
5423
/* * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.dao.annotation; import java.lang.annotation.Annotation; import org.springframework.aop.framework.Advised; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.AopUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.core.Ordered; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * Bean post-processor that automatically applies persistence exception * translation to any bean that carries the * {@link org.springframework.stereotype.Repository} annotation, * adding a corresponding {@link PersistenceExceptionTranslationAdvisor} * to the exposed proxy (either an existing AOP proxy or a newly generated * proxy that implements all of the target's interfaces). * * <p>Translates native resource exceptions to Spring's * {@link org.springframework.dao.DataAccessException} hierarchy. * Autodetects beans that implement the * {@link org.springframework.dao.support.PersistenceExceptionTranslator} * interface, which are subsequently asked to translate candidate exceptions. * * <p>All of Spring's applicable resource factories implement the * <code>PersistenceExceptionTranslator</code> interface out of the box. * As a consequence, all that is usually needed to enable automatic exception * translation is marking all affected beans (such as DAOs) with the * <code>Repository</code> annotation, along with defining this post-processor * as bean in the application context. * * @author Rod Johnson * @author Juergen Hoeller * @since 2.0 * @see PersistenceExceptionTranslationAdvisor * @see org.springframework.stereotype.Repository * @see org.springframework.dao.DataAccessException * @see org.springframework.dao.support.PersistenceExceptionTranslator */ public class PersistenceExceptionTranslationPostProcessor implements BeanPostProcessor, BeanClassLoaderAware, BeanFactoryAware, Ordered { private Class<? extends Annotation> repositoryAnnotationType = Repository.class; private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); private PersistenceExceptionTranslationAdvisor persistenceExceptionTranslationAdvisor; /** * Set the 'repository' annotation type. * The default required annotation type is the {@link Repository} annotation. * <p>This setter property exists so that developers can provide their own * (non-Spring-specific) annotation type to indicate that a class has a * repository role. * @param repositoryAnnotationType the desired annotation type */ public void setRepositoryAnnotationType(Class<? extends Annotation> repositoryAnnotationType) { Assert.notNull(repositoryAnnotationType, "'requiredAnnotationType' must not be null"); this.repositoryAnnotationType = repositoryAnnotationType; } public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (!(beanFactory instanceof ListableBeanFactory)) { throw new IllegalArgumentException( "Cannot use PersistenceExceptionTranslator autodetection without ListableBeanFactory"); } this.persistenceExceptionTranslationAdvisor = new PersistenceExceptionTranslationAdvisor( (ListableBeanFactory) beanFactory, this.repositoryAnnotationType); } public int getOrder() { // This should run after all other post-processors, so that it can just add // an advisor to existing proxies rather than double-proxy. return LOWEST_PRECEDENCE; } public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { Class<?> targetClass = (bean instanceof Advised ? ((Advised) bean).getTargetSource().getTargetClass() : bean.getClass()); if (targetClass == null) { // Can't do much here return bean; } if (AopUtils.canApply(this.persistenceExceptionTranslationAdvisor, targetClass)) { if (bean instanceof Advised) { ((Advised) bean).addAdvisor(this.persistenceExceptionTranslationAdvisor); return bean; } else { ProxyFactory pf = new ProxyFactory(bean); pf.addAdvisor(this.persistenceExceptionTranslationAdvisor); return pf.getProxy(this.beanClassLoader); } } else { // This is not a repository. return bean; } } }
apache-2.0
osiris-indoor/osiris
osiris-map-services-core/src/acceptance-test/java/com/bitmonlab/osiris/api/core/test/acceptancetest/map/search/SearchFeatureMap.java
3536
package com.bitmonlab.osiris.api.core.test.acceptancetest.map.search; import java.io.IOException; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; import junit.framework.Assert; import com.bitmonlab.osiris.core.assembler.Assembler; import com.bitmonlab.osiris.core.assembler.AssemblyException; import com.bitmonlab.osiris.api.core.map.exceptions.QueryException; import com.bitmonlab.osiris.api.core.map.managers.api.SearchManager; import com.bitmonlab.osiris.api.core.map.transferobject.FeatureDTO; import com.bitmonlab.osiris.api.core.map.transferobject.LayerDTO; import com.bitmonlab.osiris.commons.map.model.geojson.Feature; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class SearchFeatureMap { @Inject private SearchManager searchManager; @Inject @Named("FeatureAssembler") private Assembler<FeatureDTO, Feature> featureAssembler; private Collection<FeatureDTO> collectionFeaturesDTO; public static Exception exceptionCapture; @Given("^I have a map with appId \"([^\"]*)\"$") public void I_a_map_with_appId(String appId) throws IOException{ // Express the Regexp above with the code you wish you had Runtime.getRuntime().exec("mongorestore --db osirisGeolocation --collection map_app_"+appId+" src/acceptance-test/resources/scripts/map_app_1.bson"); } @When("^I invoke a getFeatureByQuery to feature and query \"([^\"]*)\" and applicationIdentifier \"([^\"]*)\"$") public void I_invoke_a_getFeatureByQuery_to_feature_and_query_and_applicationIdentifier(String query, String appID) throws QueryException, AssemblyException{ Collection<Feature> features = null; features = searchManager.getFeaturesByQuery(appID, query, LayerDTO.FEATURES, 0, 20); collectionFeaturesDTO=featureAssembler.createDataTransferObjects(features); } @When("^I invoke a getFeatureByQuery to map and query \"([^\"]*)\" and applicationIdentifier \"([^\"]*)\"$") public void I_invoke_a_getFeatureByQuery_to_map_and_query_and_applicationIdentifier(String query, String appID) throws QueryException, AssemblyException{ Collection<Feature> features = null; features = searchManager.getFeaturesByQuery(appID, query, LayerDTO.MAP, 0, 20); collectionFeaturesDTO=featureAssembler.createDataTransferObjects(features); } @When("^I invoke a getFeatureByQuery to all and query \"([^\"]*)\" and applicationIdentifier \"([^\"]*)\"$") public void I_invoke_a_getFeatureByQuery_to_all_and_query_and_applicationIdentifier(String query, String appID) throws Throwable { try { Collection<Feature> features = null; features = searchManager.getFeaturesByQuery(appID, query, LayerDTO.ALL, 0, 20); collectionFeaturesDTO=featureAssembler.createDataTransferObjects(features); }catch (Exception e){ exceptionCapture = e; } } @Then("^I check that (\\d+) features are returned$") public void I_check_that_geopoints_are_returned(int numFeatures) throws Throwable { // Express the Regexp above with the code you wish you had Assert.assertEquals("Must return " + numFeatures + " features", collectionFeaturesDTO.size(), numFeatures); } @Then("^I receive a QueryException$") public void I_receive_a_QueryException() throws Throwable { Assert.assertEquals(exceptionCapture.getClass() , new QueryException().getClass() ); } }
apache-2.0
peter-tackage/open-secret-santa
open-secret-santa-app/src/main/java/com/moac/android/opensecretsanta/notify/sms/SmsManagerSendReceiver.java
2836
package com.moac.android.opensecretsanta.notify.sms; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import com.moac.android.inject.dagger.InjectingBroadcastReceiver; import com.moac.android.opensecretsanta.activity.Intents; import com.moac.android.opensecretsanta.database.DatabaseManager; import com.moac.android.opensecretsanta.model.Assignment; import com.moac.android.opensecretsanta.model.PersistableObject; import com.moac.android.opensecretsanta.notify.NotifyStatusEvent; import com.squareup.otto.Bus; import javax.inject.Inject; /** * A Receiver will get all events that match the IntentFilter, so we can't * initialise it with an Assignment and assume that the onReceive callback is * for that Assignment receipt. Instead we use the Extra in the Intent * to determine which Assignment is being processed. */ public class SmsManagerSendReceiver extends InjectingBroadcastReceiver { private static final String TAG = SmsManagerSendReceiver.class.getSimpleName(); @Inject DatabaseManager mDb; @Inject Bus mBus; @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); /** * Due to the asynchronous nature of this callback, we need to be defensive. * The entities that were initiated the events may have changed or * even have been removed. * * Note: This callback happens on the main thread */ long assignmentId = intent.getLongExtra(Intents.ASSIGNMENT_ID_INTENT_EXTRA, PersistableObject.UNSET_ID); if(assignmentId <= PersistableObject.UNSET_ID) { Log.e(TAG, "onReceive() - Assignment Id extra not set"); return; } Assignment assignment = mDb.queryById(assignmentId, Assignment.class); if(assignment == null) { Log.e(TAG, "onReceive() - No Assignment found to update, id: " + assignmentId); return; } Log.i(TAG, "onReceive() got message sent notification:" + intent); switch(getResultCode()) { case Activity.RESULT_OK: Log.i(TAG, "onReceive() - Success sending SMS"); assignment.setSendStatus(Assignment.Status.Sent); break; default: Log.i(TAG, "onReceive() - Failure sending SMS: code - " + getResultCode() + " data: " + getResultData()); assignment.setSendStatus(Assignment.Status.Failed); } Log.d(TAG, "OnReceive() - updating Assignment and posting to bus: " + assignment); // Update Assignment with Sent Status mDb.update(assignment); // Post update of Assignment status to Bus. mBus.post(new NotifyStatusEvent(assignment)); } }
apache-2.0
chaupal/jp2p
Workspace/net.jp2p.container/src/net/jp2p/container/Jp2pContainerPropertySource.java
2215
/******************************************************************************* * Copyright (c) 2014 Chaupal. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0.html *******************************************************************************/ package net.jp2p.container; import java.io.File; import net.jp2p.container.IJp2pContainer.ContainerProperties; import net.jp2p.container.context.IJp2pServiceBuilder; import net.jp2p.container.properties.AbstractJp2pWritePropertySource; import net.jp2p.container.properties.IJp2pDirectives; import net.jp2p.container.properties.IJp2pProperties; import net.jp2p.container.properties.IJp2pProperties.Jp2pProperties; import net.jp2p.container.utils.ProjectFolderUtils; public class Jp2pContainerPropertySource extends AbstractJp2pWritePropertySource{ public static final String DEF_HOME_FOLDER = "${user.home}/.jxse/${bundle-id}"; public Jp2pContainerPropertySource( String bundleId, String name ) { super( bundleId, IJp2pServiceBuilder.Components.JP2P_CONTAINER.toString() ); this.setProperty( ContainerProperties.HOME_FOLDER, ProjectFolderUtils.getParsedUserDir(DEF_HOME_FOLDER, bundleId), false); this.setDirective( IJp2pDirectives.Directives.NAME, name); } /** * Get the bundle id * @return */ public String getBundleId(){ return getBundleId( this ); } @Override public Object getDefault( IJp2pProperties id) { if(!( id instanceof ContainerProperties )) return null; ContainerProperties cp = (ContainerProperties )id; String str = null; switch( cp ){ case HOME_FOLDER: String bundle_id = (String) super.getProperty( Jp2pProperties.BUNDLE_ID ); str = ProjectFolderUtils.getParsedUserDir( DEF_HOME_FOLDER, bundle_id ).getPath(); File file = new File( str ); return file.toURI(); default: break; } return null; } @Override public boolean validate( IJp2pProperties id, Object value) { // TODO Auto-generated method stub return false; } }
apache-2.0
Yggard/BrokkGUI
style/src/main/java/net/voxelindustry/brokkgui/style/StyleSource.java
120
package net.voxelindustry.brokkgui.style; public enum StyleSource { USER_AGENT, AUTHOR, INLINE, CODE }
apache-2.0
justinsb/avro
src/java/org/apache/avro/file/DataFileWriter.java
8790
/** * 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.avro.file; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.rmi.server.UID; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.List; import org.apache.avro.Schema; import org.apache.avro.AvroRuntimeException; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.Encoder; import org.apache.avro.io.BinaryEncoder; import org.apache.avro.generic.GenericDatumReader; /** Stores in a file a sequence of data conforming to a schema. The schema is * stored in the file with the data. Each datum in a file is of the same * schema. Data is written with a {@link DatumWriter}. Data is grouped into * <i>blocks</i>. A synchronization marker is written between blocks, so that * files may be split. Blocks may be compressed. Extensible metadata is * stored at the end of the file. Files may be appended to. * @see DataFileReader */ public class DataFileWriter<D> { private Schema schema; private DatumWriter<D> dout; private BufferedFileOutputStream out; private Encoder vout; private Map<String,byte[]> meta = new HashMap<String,byte[]>(); private long count; // # entries in file private int blockCount; // # entries in current block private ByteArrayOutputStream buffer = new ByteArrayOutputStream(DataFileConstants.SYNC_INTERVAL*2); private Encoder bufOut = new BinaryEncoder(buffer); private byte[] sync; // 16 random bytes /** Construct a writer to a new file for data matching a schema. */ public DataFileWriter(Schema schema, File file, DatumWriter<D> dout) throws IOException { this(schema, new FileOutputStream(file), dout); } /** Construct a writer to a new file for data matching a schema. */ public DataFileWriter(Schema schema, OutputStream outs, DatumWriter<D> dout) throws IOException { this.schema = schema; this.sync = generateSync(); setMeta(DataFileConstants.SYNC, sync); setMeta(DataFileConstants.SCHEMA, schema.toString()); setMeta(DataFileConstants.CODEC, DataFileConstants.NULL_CODEC); init(outs, dout); out.write(DataFileConstants.MAGIC); } /** Construct a writer appending to an existing file. */ public DataFileWriter(File file, DatumWriter<D> dout) throws IOException { if (!file.exists()) throw new FileNotFoundException("Not found: "+file); RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileDescriptor fd = raf.getFD(); DataFileReader<D> reader = new DataFileReader<D>(new SeekableFileInput(fd), new GenericDatumReader<D>()); this.schema = reader.getSchema(); this.sync = reader.sync; this.count = reader.getCount(); this.meta.putAll(reader.meta); FileChannel channel = raf.getChannel(); // seek to end channel.position(channel.size()); init(new FileOutputStream(fd), dout); } private void init(OutputStream outs, DatumWriter<D> dout) throws IOException { this.out = new BufferedFileOutputStream(outs); this.vout = new BinaryEncoder(out); this.dout = dout; dout.setSchema(schema); } private static byte[] generateSync() { try { MessageDigest digester = MessageDigest.getInstance("MD5"); long time = System.currentTimeMillis(); digester.update((new UID()+"@"+time).getBytes()); return digester.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } /** Set a metadata property. */ public synchronized void setMeta(String key, byte[] value) { meta.put(key, value); } /** Set a metadata property. */ public synchronized void setMeta(String key, String value) { try { setMeta(key, value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** Set a metadata property. */ public synchronized void setMeta(String key, long value) { setMeta(key, Long.toString(value)); } /** If the schema for this file is a union, add a branch to it. */ public synchronized void addSchema(Schema branch) { if (schema.getType() != Schema.Type.UNION) throw new AvroRuntimeException("Not a union schema: "+schema); List<Schema> types = schema.getTypes(); types.add(branch); this.schema = Schema.createUnion(types); this.dout.setSchema(schema); setMeta(DataFileConstants.SCHEMA, schema.toString()); } /** Append a datum to the file. */ public synchronized void append(D datum) throws IOException { dout.write(datum, bufOut); blockCount++; count++; if (buffer.size() >= DataFileConstants.SYNC_INTERVAL) writeBlock(); } private void writeBlock() throws IOException { if (blockCount > 0) { out.write(sync); writeBlockHeader(vout, blockCount); buffer.writeTo(out); buffer.reset(); blockCount = 0; } } protected void writeBlockHeader(Encoder encoder, int blockCount) throws IOException { vout.writeLong(blockCount); } /** Return the current position as a value that may be passed to {@link * DataFileReader#seek(long)}. Forces the end of the current block, * emitting a synchronization marker. */ public synchronized long sync() throws IOException { writeBlock(); return out.tell(); } /** Flush the current state of the file, including metadata. */ public synchronized void flush() throws IOException { writeFooter(); out.flush(); } /** Close the file. */ public synchronized void close() throws IOException { flush(); out.close(); } /** Expose the current buffer position */ protected int getBufferSize() { return buffer.size(); } private void writeFooter() throws IOException { writeBlock(); // flush any data setMeta(DataFileConstants.COUNT, count); // update count bufOut.writeMapStart(); // write meta entries bufOut.setItemCount(meta.size()); for (Map.Entry<String,byte[]> entry : meta.entrySet()) { bufOut.startItem(); bufOut.writeString(entry.getKey()); bufOut.writeBytes(entry.getValue()); } bufOut.writeMapEnd(); int size = buffer.size()+4; out.write(sync); vout.writeLong(DataFileConstants.FOOTER_BLOCK); // tag the block vout.writeLong(size); buffer.writeTo(out); buffer.reset(); out.write((byte)(size >>> 24)); out.write((byte)(size >>> 16)); out.write((byte)(size >>> 8)); out.write((byte)(size >>> 0)); } private class BufferedFileOutputStream extends BufferedOutputStream { private long position; // start of buffer private class PositionFilter extends FilterOutputStream { public PositionFilter(OutputStream out) throws IOException { super(out); } @Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); position += len; // update on write } @Override public void write(int b) throws IOException { out.write(b); position += 1; // update on write } } public BufferedFileOutputStream(OutputStream out) throws IOException { super(null); this.out = new PositionFilter(out); } public long tell() { return position+count; } } }
apache-2.0
Banno/sbt-plantuml-plugin
src/main/java/net/sourceforge/plantuml/salt/Dictionary.java
2292
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2017, Arnaud Roques * * Project Info: http://plantuml.com * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.salt; import java.util.HashMap; import java.util.Map; import net.sourceforge.plantuml.ISkinSimple; import net.sourceforge.plantuml.SpriteContainer; import net.sourceforge.plantuml.creole.CommandCreoleMonospaced; import net.sourceforge.plantuml.graphic.HtmlColorSetSimple; import net.sourceforge.plantuml.graphic.IHtmlColorSet; import net.sourceforge.plantuml.salt.element.Element; import net.sourceforge.plantuml.salt.element.WrappedElement; import net.sourceforge.plantuml.ugraphic.sprite.Sprite; public class Dictionary implements SpriteContainer, ISkinSimple { private final Map<String, Element> data = new HashMap<String, Element>(); public void put(String name, Element element) { data.put(name, element); } public Element get(String name) { final Element result = data.get(name); if (result == null) { throw new IllegalArgumentException(); } return new WrappedElement(result); } public Sprite getSprite(String name) { return null; } public String getValue(String key) { return null; } public double getPadding() { return 0; } public boolean useGuillemet() { return true; } public String getMonospacedFamily() { return CommandCreoleMonospaced.MONOSPACED; } public int getTabSize() { return 8; } public IHtmlColorSet getIHtmlColorSet() { return new HtmlColorSetSimple(); } }
apache-2.0
floodlight/loxigen-artifacts
openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/OFFlowMonitorEntry.java
2439
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_interface.java // Do not modify package org.projectfloodlight.openflow.protocol; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import java.util.Set; import io.netty.buffer.ByteBuf; public interface OFFlowMonitorEntry extends OFObject { long getMonitorId(); long getOutPort(); long getOutGroup(); Set<OFFlowMonitorFlags> getFlags(); TableId getTableId(); OFFlowMonitorCommand getCommand(); Match getMatch(); OFVersion getVersion(); void writeTo(ByteBuf channelBuffer); Builder createBuilder(); public interface Builder { OFFlowMonitorEntry build(); long getMonitorId(); Builder setMonitorId(long monitorId); long getOutPort(); Builder setOutPort(long outPort); long getOutGroup(); Builder setOutGroup(long outGroup); Set<OFFlowMonitorFlags> getFlags(); Builder setFlags(Set<OFFlowMonitorFlags> flags); TableId getTableId(); Builder setTableId(TableId tableId); OFFlowMonitorCommand getCommand(); Builder setCommand(OFFlowMonitorCommand command); Match getMatch(); Builder setMatch(Match match); OFVersion getVersion(); } }
apache-2.0
Banno/sbt-plantuml-plugin
src/main/java/net/sourceforge/plantuml/FileFormatOption.java
7360
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2017, Arnaud Roques * * Project Info: http://plantuml.com * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.geom.Dimension2D; import java.awt.image.BufferedImage; import java.io.Serializable; import net.sourceforge.plantuml.eps.EpsStrategy; import net.sourceforge.plantuml.graphic.HtmlColor; import net.sourceforge.plantuml.graphic.HtmlColorGradient; import net.sourceforge.plantuml.graphic.HtmlColorSimple; import net.sourceforge.plantuml.graphic.HtmlColorTransparent; import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.ugraphic.ColorMapper; import net.sourceforge.plantuml.ugraphic.ColorMapperIdentity; import net.sourceforge.plantuml.ugraphic.UChangeBackColor; import net.sourceforge.plantuml.ugraphic.UGraphic2; import net.sourceforge.plantuml.ugraphic.URectangle; import net.sourceforge.plantuml.ugraphic.eps.UGraphicEps; import net.sourceforge.plantuml.ugraphic.g2d.UGraphicG2d; import net.sourceforge.plantuml.ugraphic.html5.UGraphicHtml5; import net.sourceforge.plantuml.ugraphic.svg.UGraphicSvg; import net.sourceforge.plantuml.ugraphic.tikz.UGraphicTikz; import net.sourceforge.plantuml.ugraphic.visio.UGraphicVdx; /** * A FileFormat with some parameters. * * * @author Arnaud Roques * */ public class FileFormatOption implements Serializable { private final FileFormat fileFormat; private final AffineTransform affineTransform; private final boolean withMetadata; private final boolean useRedForError; private final String svgLinkTarget; public FileFormatOption(FileFormat fileFormat) { this(fileFormat, null, true, false, "_top", false); } public StringBounder getDefaultStringBounder() { return fileFormat.getDefaultStringBounder(); } public String getSvgLinkTarget() { return svgLinkTarget; } public final boolean isWithMetadata() { return withMetadata; } public FileFormatOption(FileFormat fileFormat, boolean withMetadata) { this(fileFormat, null, false, false, "_top", false); } private FileFormatOption(FileFormat fileFormat, AffineTransform at, boolean withMetadata, boolean useRedForError, String svgLinkTarget, boolean debugsvek) { this.fileFormat = fileFormat; this.affineTransform = at; this.withMetadata = withMetadata; this.useRedForError = useRedForError; this.svgLinkTarget = svgLinkTarget; this.debugsvek = debugsvek; } public FileFormatOption withUseRedForError() { return new FileFormatOption(fileFormat, affineTransform, withMetadata, true, svgLinkTarget, debugsvek); } public FileFormatOption withSvgLinkTarget(String target) { return new FileFormatOption(fileFormat, affineTransform, withMetadata, useRedForError, target, debugsvek); } @Override public String toString() { return fileFormat.toString() + " " + affineTransform; } public final FileFormat getFileFormat() { return fileFormat; } public AffineTransform getAffineTransform() { return affineTransform; } /** * Create a UGraphic corresponding to this FileFormatOption * * @param colorMapper * @param dpiFactor * 1.0 for a standard dot per inch * @param dim * @param mybackcolor * @param rotation * @return */ public UGraphic2 createUGraphic(ColorMapper colorMapper, double dpiFactor, final Dimension2D dim, HtmlColor mybackcolor, boolean rotation) { switch (fileFormat) { case PNG: return createUGraphicPNG(colorMapper, dpiFactor, dim, mybackcolor, rotation); case SVG: return createUGraphicSVG(colorMapper, dpiFactor, dim, mybackcolor, rotation); case EPS: return new UGraphicEps(colorMapper, EpsStrategy.getDefault2()); case EPS_TEXT: return new UGraphicEps(colorMapper, EpsStrategy.WITH_MACRO_AND_TEXT); case HTML5: return new UGraphicHtml5(colorMapper); case VDX: return new UGraphicVdx(colorMapper); case LATEX: return new UGraphicTikz(colorMapper, true); case LATEX_NO_PREAMBLE: return new UGraphicTikz(colorMapper, false); default: throw new UnsupportedOperationException(fileFormat.toString()); } } public UGraphic2 createUGraphic(final Dimension2D dim) { return createUGraphic(new ColorMapperIdentity(), 1.0, dim, null, false); } private UGraphic2 createUGraphicSVG(ColorMapper colorMapper, double scale, Dimension2D dim, HtmlColor mybackcolor, boolean rotation) { Color backColor = Color.WHITE; if (mybackcolor instanceof HtmlColorSimple) { backColor = colorMapper.getMappedColor(mybackcolor); } final UGraphicSvg ug; if (mybackcolor instanceof HtmlColorGradient) { ug = new UGraphicSvg(colorMapper, (HtmlColorGradient) mybackcolor, false, scale, getSvgLinkTarget()); } else if (backColor == null || backColor.equals(Color.WHITE)) { ug = new UGraphicSvg(colorMapper, false, scale, getSvgLinkTarget()); } else { ug = new UGraphicSvg(colorMapper, StringUtils.getAsHtml(backColor), false, scale, getSvgLinkTarget()); } return ug; } private UGraphic2 createUGraphicPNG(ColorMapper colorMapper, double dpiFactor, final Dimension2D dim, HtmlColor mybackcolor, boolean rotation) { Color backColor = Color.WHITE; if (mybackcolor instanceof HtmlColorSimple) { backColor = colorMapper.getMappedColor(mybackcolor); } else if (mybackcolor instanceof HtmlColorTransparent) { backColor = null; } final EmptyImageBuilder builder; final Graphics2D graphics2D; if (rotation) { builder = new EmptyImageBuilder((int) (dim.getHeight() * dpiFactor), (int) (dim.getWidth() * dpiFactor), backColor); graphics2D = builder.getGraphics2D(); graphics2D.rotate(-Math.PI / 2); graphics2D.translate(-builder.getBufferedImage().getHeight(), 0); } else { builder = new EmptyImageBuilder((int) (dim.getWidth() * dpiFactor), (int) (dim.getHeight() * dpiFactor), backColor); graphics2D = builder.getGraphics2D(); } final UGraphicG2d ug = new UGraphicG2d(colorMapper, graphics2D, dpiFactor); ug.setBufferedImage(builder.getBufferedImage()); final BufferedImage im = ((UGraphicG2d) ug).getBufferedImage(); if (mybackcolor instanceof HtmlColorGradient) { ug.apply(new UChangeBackColor(mybackcolor)).draw(new URectangle(im.getWidth(), im.getHeight())); } return ug; } public final boolean isUseRedForError() { return useRedForError; } private boolean debugsvek = false; public void setDebugSvek(boolean debugsvek) { this.debugsvek = debugsvek; } public boolean isDebugSvek() { return debugsvek; } }
apache-2.0
pbuda/intellij-pony
jps-plugin/src/me/piotrbuda/intellij/pony/jps/PonyJspInterface.java
2735
/* * Copyright 2015 Piotr Buda * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.piotrbuda.intellij.pony.jps; import java.io.File; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import me.piotrbuda.intellij.pony.jps.model.JpsPonySdkType; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.incremental.CompileContext; import org.jetbrains.jps.incremental.ProjectBuildException; import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.CompilerMessage; import org.jetbrains.jps.model.JpsDummyElement; import org.jetbrains.jps.model.library.sdk.JpsSdk; import org.jetbrains.jps.model.module.JpsModule; public class PonyJspInterface { public static final Logger LOG = Logger.getInstance(PonyJspInterface.class); @NotNull private final File rootDir; private final File compilerFileName; PonyJspInterface(@NotNull JpsModule module, @NotNull CompileContext context) throws ProjectBuildException { final String moduleRoot = module.getContentRootsList().getUrls().get(0).substring("file://".length()); this.rootDir = new File(moduleRoot); JpsSdk<JpsDummyElement> sdk = module.getSdk(JpsPonySdkType.INSTANCE); if (sdk == null) { String errorMessage = "No SDK for module " + module.getName(); context.processMessage(new CompilerMessage("PonyBuilder", BuildMessage.Kind.ERROR, errorMessage)); throw new ProjectBuildException(errorMessage); } compilerFileName = new File(sdk.getHomePath(), SystemInfo.isWindows ? "\\bin\\ponyc.exe" : "/bin/ponyc"); } public GeneralCommandLine buildCommandLine(@NotNull final File outputDirectory) throws ProjectBuildException { final GeneralCommandLine commandLine = new GeneralCommandLine(); commandLine.withWorkDirectory(rootDir.getPath()); commandLine.setRedirectErrorStream(true); commandLine.setExePath(compilerFileName.getAbsolutePath()); commandLine.addParameter("--output=" + outputDirectory.getPath()); return commandLine; } }
apache-2.0
KEOpenSource/Simulyn
src/simulyn/math/FindMax.java
1579
/* FindMax -- an class within the Machine Artificial Vision Network(Machine Artificial Vision Network) Copyright (C) 2012, Kaleb Kircher. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package simulyn.math; /** * A class that contains methods to find the maximum value contained * in a collection. * @author Kaleb */ public class FindMax { /** * Find the max value in a double array containing doubles. * @param numbers the double array * @return the maximum value in the array */ public static double getMaxValue(double[][] numbers) { double maxValue = numbers[0][0]; for (int i = 0; i < numbers.length; i++) { for (int j = 0; j < numbers[i].length; j++) { if (numbers[i][j] > maxValue) { maxValue = Math.abs(numbers[i][j]); } } } return maxValue; } }
apache-2.0
OrienteerBAP/Orienteer
orienteer-core/src/main/java/org/orienteer/core/util/ODocumentChoiceProvider.java
3381
package org.orienteer.core.util; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.util.string.Strings; import org.orienteer.core.OrienteerWebApplication; import org.orienteer.core.service.IOClassIntrospector; import org.wicketstuff.select2.ChoiceProvider; import org.wicketstuff.select2.Response; import ru.ydn.wicket.wicketorientdb.model.OClassModel; import ru.ydn.wicket.wicketorientdb.model.OPropertyModel; import ru.ydn.wicket.wicketorientdb.model.OQueryModel; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * * Choice provider for Select2 control * * @param <M> type of main object for ChoiceProvider: should be subtype of {@link OIdentifiable} */ public class ODocumentChoiceProvider<M extends OIdentifiable> extends ChoiceProvider<M> { private static final long serialVersionUID = 1L; private IModel<OClass> classModel; private transient IOClassIntrospector oClassIntrospector; public ODocumentChoiceProvider(IModel<OClass> classModel) { this.classModel = classModel; } public ODocumentChoiceProvider(OClass oClass) { this(new OClassModel(oClass)); } protected IOClassIntrospector getOClassIntrospector() { if (oClassIntrospector == null) { oClassIntrospector = OrienteerWebApplication.get().getOClassIntrospector(); } return oClassIntrospector; } @Override public String getDisplayValue(M document) { return getOClassIntrospector().getDocumentName(document.getRecord()); } @Override public String getIdValue(M document) { return document.getIdentity().toString(); } @Override public void query(String query, int i, Response<M> response) { OClass oClass = classModel.getObject(); if(oClass==null) return; OProperty property = getOClassIntrospector().getNameProperty(oClass); if(property==null) return; StringBuilder sql = new StringBuilder("SELECT FROM ").append(oClass.getName()); if (!Strings.isEmpty(query)) { sql.append(" WHERE ") .append(property.getName()); if(!OType.STRING.equals(property.getType())) sql.append(".asString()"); sql.append(" CONTAINSTEXT :query"); } sql.append(" LIMIT 20"); OQueryModel<ODocument> choicesModel = new OQueryModel<ODocument>(sql.toString()); choicesModel.setParameter("query", new Model<String>(query)); response.addAll((List<M>)choicesModel.getObject()); } @Override public Collection<M> toChoices(Collection<String> ids) { ArrayList<M> documents = new ArrayList<M>(); for (String id : ids) { ORecordId rid = new ORecordId(id); documents.add(rid.getRecord()); } return documents; } @Override public void detach() { super.detach(); if(classModel!=null) classModel.detach(); } }
apache-2.0
mikeyxkcd/butterknife
butterknife-sample/src/main/java/com/example/butterknife/SimpleActivity.java
1323
package com.example.butterknife; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import butterknife.InjectView; import butterknife.Views; import static android.view.View.OnClickListener; import static android.widget.Toast.LENGTH_SHORT; public class SimpleActivity extends Activity { @InjectView(R.id.title) TextView title; @InjectView(R.id.subtitle) TextView subtitle; @InjectView(R.id.hello) Button hello; @InjectView(R.id.list_of_things) ListView listOfThings; @InjectView(R.id.footer) TextView footer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); Views.inject(this); // Contrived code to use the "injected" views. title.setText("Butter Knife"); subtitle.setText("View \"injection\" for Android."); footer.setText("by Jake Wharton"); hello.setText("Say Hello"); hello.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(SimpleActivity.this, "Hello, views!", LENGTH_SHORT).show(); } }); listOfThings.setAdapter(new SimpleAdapter(this)); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/http/exception/HttpRequestTimeoutException.java
1288
/* * Copyright 2015-2022 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.http.exception; import java.io.IOException; /** * Signals that the http request could not complete within the specified timeout. */ public class HttpRequestTimeoutException extends IOException { private static final long serialVersionUID = -2588353895012259837L; public HttpRequestTimeoutException(String message) { super(message); } public HttpRequestTimeoutException(Throwable throwable) { this("Request did not complete before the request timeout configuration.", throwable); } public HttpRequestTimeoutException(String message, Throwable throwable) { super(message, throwable); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-ec2instanceconnect/src/main/java/com/amazonaws/services/ec2instanceconnect/model/transform/SendSSHPublicKeyRequestProtocolMarshaller.java
2752
/* * Copyright 2017-2022 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.ec2instanceconnect.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.ec2instanceconnect.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * SendSSHPublicKeyRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class SendSSHPublicKeyRequestProtocolMarshaller implements Marshaller<Request<SendSSHPublicKeyRequest>, SendSSHPublicKeyRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("AWSEC2InstanceConnectService.SendSSHPublicKey").serviceName("AWSEC2InstanceConnect").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public SendSSHPublicKeyRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<SendSSHPublicKeyRequest> marshall(SendSSHPublicKeyRequest sendSSHPublicKeyRequest) { if (sendSSHPublicKeyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<SendSSHPublicKeyRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, sendSSHPublicKeyRequest); protocolMarshaller.startMarshalling(); SendSSHPublicKeyRequestMarshaller.getInstance().marshall(sendSSHPublicKeyRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
LoveGoogleLoveAndroid/design-pattern
app/src/main/java/com/sky/hsf1002/designpattern/Mediator/Component.java
200
package com.sky.hsf1002.designpattern.Mediator; public abstract class Component { protected IMidiator midiator; Component(IMidiator midiator) { this.midiator = midiator; } }
apache-2.0
consulo/consulo
modules/base/platform-api/src/main/java/com/intellij/openapi/MnemonicWrapper.java
9377
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi; import com.intellij.ide.ui.UISettings; import consulo.logging.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.util.ui.UIUtil; import javax.swing.*; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * @author Sergey.Malenkov */ abstract class MnemonicWrapper<T extends JComponent> implements Runnable, PropertyChangeListener { public static MnemonicWrapper getWrapper(Component component) { if (component == null || component.getClass().getName().equals("com.intellij.openapi.wm.impl.StripeButton")) { return null; } for (PropertyChangeListener listener : component.getPropertyChangeListeners()) { if (listener instanceof MnemonicWrapper) { MnemonicWrapper wrapper = (MnemonicWrapper)listener; wrapper.run(); // update mnemonics immediately return wrapper; } } if (component instanceof JMenuItem) { return new MenuWrapper((AbstractButton)component); } if (component instanceof AbstractButton) { return new ButtonWrapper((AbstractButton)component); } if (component instanceof JLabel) { return new LabelWrapper((JLabel)component); } return null; } final T myComponent; // direct access from inner classes private final String myTextProperty; private final String myCodeProperty; private final String myIndexProperty; private int myCode; private int myIndex; private boolean myFocusable; private boolean myEvent; private boolean myTextChanged; private Runnable myRunnable; private MnemonicWrapper(T component, String text, String code, String index) { myComponent = component; myTextProperty = text; myCodeProperty = code; myIndexProperty = index; if (!updateText()) { // assume that it is already set myCode = getMnemonicCode(); myIndex = getMnemonicIndex(); } myFocusable = isFocusable(); myComponent.addPropertyChangeListener(this); run(); // update mnemonics immediately } @Override public final void run() { boolean disabled = isDisabled(); try { myEvent = true; if (myTextChanged) updateText(); // update mnemonic code only if changed int code = disabled ? KeyEvent.VK_UNDEFINED : myCode; if (code != getMnemonicCode()) setMnemonicCode(code); // update input map to support Alt-based mnemonics if (SystemInfo.isMac && Registry.is("ide.mac.alt.mnemonic.without.ctrl", true)) { InputMap map = myComponent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); if (map != null) updateInputMap(map, code); } // update mnemonic index only if changed int index = disabled ? -1 : myIndex; if (index != getMnemonicIndex()) { try { setMnemonicIndex(index); } catch (IllegalArgumentException cause) { // EA-94674 - IAE: AbstractButton.setDisplayedMnemonicIndex StringBuilder sb = new StringBuilder("cannot set mnemonic index "); if (myTextChanged) sb.append("if text changed "); String message = sb.append(myComponent).toString(); Logger.getInstance(MnemonicWrapper.class).warn(message, cause); } } Component component = getFocusableComponent(); if (component != null) { component.setFocusable(disabled || myFocusable); } } finally { myEvent = false; myTextChanged = false; myRunnable = null; } } @Override public final void propertyChange(PropertyChangeEvent event) { if (!myEvent) { String property = event.getPropertyName(); if (myTextProperty.equals(property)) { // it is needed to update text later because // this listener is notified before Swing updates mnemonics myTextChanged = true; updateRequest(); } else if (myCodeProperty.equals(property)) { myCode = getMnemonicCode(); updateRequest(); } else if (myIndexProperty.equals(property)) { myIndex = getMnemonicIndex(); updateRequest(); } else if ("focusable".equals(property) || "labelFor".equals(property)) { myFocusable = isFocusable(); updateRequest(); } } } private boolean updateText() { String text = getText(); if (text != null) { int code = KeyEvent.VK_UNDEFINED; int index = -1; int length = text.length(); StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { char ch = text.charAt(i); if (ch != UIUtil.MNEMONIC) { sb.append(ch); } else if (i + 1 < length) { code = KeyEvent.getExtendedKeyCodeForChar(text.charAt(i + 1)); index = sb.length(); } } if (code != KeyEvent.VK_UNDEFINED) { try { myEvent = true; setText(sb.toString()); } finally { myEvent = false; } myCode = code; myIndex = index; return true; } } return false; } private void updateRequest() { if (myRunnable == null) { myRunnable = this; // run once //noinspection SSBasedInspection SwingUtilities.invokeLater(this); } } private boolean isFocusable() { Component component = getFocusableComponent(); return component == null || component.isFocusable(); } Component getFocusableComponent() { return myComponent; } boolean isDisabled() { return UISettings.getShadowInstance().getDisableMnemonicsInControls(); } abstract String getText(); abstract void setText(String text); abstract int getMnemonicCode(); abstract void setMnemonicCode(int code); abstract int getMnemonicIndex(); abstract void setMnemonicIndex(int index); abstract void updateInputMap(InputMap map, int code); static KeyStroke fixMacKeyStroke(KeyStroke stroke, InputMap map, int code, boolean onKeyRelease, String action) { if (stroke != null && code != stroke.getKeyCode()) { map.remove(stroke); stroke = null; } if (stroke == null && code != KeyEvent.VK_UNDEFINED) { stroke = KeyStroke.getKeyStroke(code, InputEvent.ALT_MASK | InputEvent.ALT_DOWN_MASK, onKeyRelease); map.put(stroke, action); } return stroke; } private static class MenuWrapper extends AbstractButtonWrapper { private KeyStroke myStrokePressed; private MenuWrapper(AbstractButton component) { super(component); } @Override void updateInputMap(InputMap map, int code) { myStrokePressed = fixMacKeyStroke(myStrokePressed, map, code, false, "selectMenu"); } } private static class ButtonWrapper extends AbstractButtonWrapper { private KeyStroke myStrokePressed; private KeyStroke myStrokeReleased; private ButtonWrapper(AbstractButton component) { super(component); } @Override void updateInputMap(InputMap map, int code) { myStrokePressed = fixMacKeyStroke(myStrokePressed, map, code, false, "pressed"); myStrokeReleased = fixMacKeyStroke(myStrokeReleased, map, code, true, "released"); } } private static abstract class AbstractButtonWrapper extends MnemonicWrapper<AbstractButton> { private AbstractButtonWrapper(AbstractButton component) { super(component, "text", "mnemonic", "displayedMnemonicIndex"); } @Override String getText() { return myComponent.getText(); } @Override void setText(String text) { myComponent.setText(text); } @Override int getMnemonicCode() { return myComponent.getMnemonic(); } @Override void setMnemonicCode(int code) { myComponent.setMnemonic(code); } @Override int getMnemonicIndex() { return myComponent.getDisplayedMnemonicIndex(); } @Override void setMnemonicIndex(int index) { myComponent.setDisplayedMnemonicIndex(index); } } private static class LabelWrapper extends MnemonicWrapper<JLabel> { private KeyStroke myStrokeRelease; private LabelWrapper(JLabel component) { super(component, "text", "displayedMnemonic", "displayedMnemonicIndex"); } @Override void updateInputMap(InputMap map, int code) { myStrokeRelease = fixMacKeyStroke(myStrokeRelease, map, code, true, "release"); } @Override String getText() { return myComponent.getText(); } @Override void setText(String text) { myComponent.setText(text); } @Override int getMnemonicCode() { return myComponent.getDisplayedMnemonic(); } @Override void setMnemonicCode(int code) { myComponent.setDisplayedMnemonic(code); } @Override int getMnemonicIndex() { return myComponent.getDisplayedMnemonicIndex(); } @Override void setMnemonicIndex(int index) { myComponent.setDisplayedMnemonicIndex(index); } @Override Component getFocusableComponent() { return myComponent.getLabelFor(); } } }
apache-2.0
valerifabio/alfresco-mvn-testing-webscripts
src/test/java/org/alfresco/demoamp/test/DemoWebscriptTest.java
1606
package org.alfresco.demoamp.test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.alfresco.repo.web.scripts.BaseWebScriptTest; import org.apache.log4j.Logger; import org.springframework.extensions.webscripts.TestWebScriptServer; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import org.springframework.extensions.webscripts.Status; /** * * @author Fabio Valeri */ public class DemoWebscriptTest extends BaseWebScriptTest { static Logger log = Logger.getLogger(DemoWebscriptTest.class); private static final String ADMIN_USER_NAME = "admin"; private static final String DEMO_WEBSCRIPT_URL = "/demowebscript"; private static final Map<String, String> DEMO_WEBSCRIPT_ARGS = new HashMap<String, String>() { { put("message", "Hello"); } }; private static final TestWebScriptServer.Request DEMO_WEBSCRIPT_REQUEST = new TestWebScriptServer.GetRequest(DEMO_WEBSCRIPT_URL).setArgs(DEMO_WEBSCRIPT_ARGS); private static final String JSON_RESULT = "result"; public DemoWebscriptTest() { super(); } @Test public void testDemoWebscript() { log.debug("DemoWebscriptTest.testDemoWebscript"); try { TestWebScriptServer.Response response = sendRequest(DEMO_WEBSCRIPT_REQUEST, Status.STATUS_OK, ADMIN_USER_NAME); assertEquals("Hello from Demo Webscript", new JSONObject(response.getContentAsString()).getString(JSON_RESULT)); } catch (IOException ex) { log.warn("IOException", ex); } catch (JSONException ex) { log.warn("JSONException", ex); } } }
apache-2.0
Duke1/SmileLib
Sample/src/main/java/xyz/openhh/bean/Department.java
788
package xyz.openhh.bean; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; /** * Created by HH . */ @DatabaseTable(tableName = "Department") public class Department { public Department(String name, String abbreviation, int manager) { this.name = name; this.abbreviation = abbreviation; this.manager = manager; } public Department() { } @DatabaseField(generatedId = true, columnName = "DepartmentId", canBeNull = false) public int departmentId; @DatabaseField(columnName = "Name") public String name; /** * 缩写 */ @DatabaseField(columnName = "Abbreviation") public String abbreviation; @DatabaseField( columnName = "Manager") public int manager; }
apache-2.0
sdmcraft/sling
bundles/extensions/serviceusermapper/src/main/java/org/apache/sling/serviceusermapping/impl/Mapping.java
4440
/* * 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.sling.serviceusermapping.impl; /** * The <code>Mapping</code> class defines the mapping of a service's name and * optional service information to a user name. */ class Mapping implements Comparable<Mapping> { /** * The name of the osgi property holding the service name. */ static String SERVICENAME = ".serviceName"; private final String serviceName; private final String subServiceName; private final String userName; /** * Creates a mapping entry for the entry specification of the form: * * <pre> * spec = serviceName [ ":" subServiceName ] "=" userName . * </pre> * * @param spec The mapping specification. * @throws NullPointerException if {@code spec} is {@code null}. * @throws IllegalArgumentException if {@code spec} does not match the * expected pattern. */ Mapping(final String spec) { final int colon = spec.indexOf(':'); final int equals = spec.indexOf('='); if (colon == 0 || equals <= 0) { throw new IllegalArgumentException("serviceName is required"); } else if (equals == spec.length() - 1) { throw new IllegalArgumentException("userName is required"); } else if (colon + 1 == equals) { throw new IllegalArgumentException("serviceInfo must not be empty"); } if (colon < 0 || colon > equals) { this.serviceName = spec.substring(0, equals); this.subServiceName = null; } else { this.serviceName = spec.substring(0, colon); this.subServiceName = spec.substring(colon + 1, equals); } this.userName = spec.substring(equals + 1); } /** * Returns the user name if the {@code serviceName} and the * {@code serviceInfo} match. Otherwise {@code null} is returned. * * @param serviceName The name of the service to match. If this is * {@code null} this mapping will not match. * @param subServiceName The Subservice Name to match. This may be * {@code null}. * @return The user name if this mapping matches or {@code null} otherwise. */ String map(final String serviceName, final String subServiceName) { if (this.serviceName.equals(serviceName) && equals(this.subServiceName, subServiceName)) { return userName; } return null; } private boolean equals(String str1, String str2) { return ((str1 == null) ? str2 == null : str1.equals(str2)); } @Override public String toString() { return "Mapping [serviceName=" + serviceName + ", subServiceName=" + subServiceName + ", userName=" + userName + "]"; } public String getServiceName() { return serviceName; } public String getSubServiceName() { return subServiceName; } public int compareTo(Mapping o) { if (o == null) { return -1; } int result = compare(this.serviceName, o.serviceName); if (result == 0) { result = compare(this.subServiceName, o.subServiceName); if (result == 0) { result = compare(this.userName, o.userName); } } return result; } private int compare(String str1, String str2) { if (str1 == str2) { return 0; } if (str1 == null) { return -1; } if (str2 == null) { return 1; } return str1.hashCode() - str2.hashCode(); } }
apache-2.0
VirtualGamer/SnowEngine
Dependencies/opengl/src/org/lwjgl/opengl/GL41.java
140930
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengl; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.JNI.*; import static org.lwjgl.system.MemoryStack.*; import static org.lwjgl.system.MemoryUtil.*; /** * The core OpenGL 4.1 functionality. OpenGL 4.1 implementations support revision 4.10 of the OpenGL Shading Language. * * <p>Extensions promoted to core in this release:</p> * * <ul> * <li><a href="http://www.opengl.org/registry/specs/ARB/ES2_compatibility.txt">ARB_ES2_compatibility</a></li> * <li><a href="http://www.opengl.org/registry/specs/ARB/get_program_binary.txt">ARB_get_program_binary</a></li> * <li><a href="http://www.opengl.org/registry/specs/ARB/separate_shader_objects.txt">ARB_separate_shader_objects</a></li> * <li><a href="http://www.opengl.org/registry/specs/ARB/shader_precision.txt">ARB_shader_precision</a></li> * <li><a href="http://www.opengl.org/registry/specs/ARB/vertex_attrib_64bit.txt">ARB_vertex_attrib_64bit</a></li> * <li><a href="http://www.opengl.org/registry/specs/ARB/viewport_array.txt">ARB_viewport_array</a></li> * </ul> */ public class GL41 { /** Accepted by the {@code value} parameter of GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev. */ public static final int GL_SHADER_COMPILER = 0x8DFA, GL_SHADER_BINARY_FORMATS = 0x8DF8, GL_NUM_SHADER_BINARY_FORMATS = 0x8DF9, GL_MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB, GL_MAX_VARYING_VECTORS = 0x8DFC, GL_MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD, GL_IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A, GL_IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B; /** Accepted by the {@code type} parameter of VertexAttribPointer. */ public static final int GL_FIXED = 0x140C; /** Accepted by the {@code precisiontype} parameter of GetShaderPrecisionFormat. */ public static final int GL_LOW_FLOAT = 0x8DF0, GL_MEDIUM_FLOAT = 0x8DF1, GL_HIGH_FLOAT = 0x8DF2, GL_LOW_INT = 0x8DF3, GL_MEDIUM_INT = 0x8DF4, GL_HIGH_INT = 0x8DF5; /** Accepted by the {@code format} parameter of most commands taking sized internal formats. */ public static final int GL_RGB565 = 0x8D62; /** Accepted by the {@code pname} parameter of ProgramParameteri and GetProgramiv. */ public static final int GL_PROGRAM_BINARY_RETRIEVABLE_HINT = 0x8257; /** Accepted by the {@code pname} parameter of GetProgramiv. */ public static final int GL_PROGRAM_BINARY_LENGTH = 0x8741; /** Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv and GetDoublev. */ public static final int GL_NUM_PROGRAM_BINARY_FORMATS = 0x87FE, GL_PROGRAM_BINARY_FORMATS = 0x87FF; /** Accepted by {@code stages} parameter to UseProgramStages. */ public static final int GL_VERTEX_SHADER_BIT = 0x1, GL_FRAGMENT_SHADER_BIT = 0x2, GL_GEOMETRY_SHADER_BIT = 0x4, GL_TESS_CONTROL_SHADER_BIT = 0x8, GL_TESS_EVALUATION_SHADER_BIT = 0x10, GL_ALL_SHADER_BITS = 0xFFFFFFFF; /** Accepted by the {@code pname} parameter of ProgramParameteri and GetProgramiv. */ public static final int GL_PROGRAM_SEPARABLE = 0x8258; /** Accepted by {@code type} parameter to GetProgramPipelineiv. */ public static final int GL_ACTIVE_PROGRAM = 0x8259; /** Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev. */ public static final int GL_PROGRAM_PIPELINE_BINDING = 0x825A; /** Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, GetDoublev and GetInteger64v. */ public static final int GL_MAX_VIEWPORTS = 0x825B, GL_VIEWPORT_SUBPIXEL_BITS = 0x825C, GL_VIEWPORT_BOUNDS_RANGE = 0x825D, GL_LAYER_PROVOKING_VERTEX = 0x825E, GL_VIEWPORT_INDEX_PROVOKING_VERTEX = 0x825F; /** Returned in the {@code data} parameter from a Get query with a {@code pname} of LAYER_PROVOKING_VERTEX or VIEWPORT_INDEX_PROVOKING_VERTEX. */ public static final int GL_UNDEFINED_VERTEX = 0x8260; protected GL41() { throw new UnsupportedOperationException(); } static boolean isAvailable(GLCapabilities caps) { return checkFunctions( caps.glReleaseShaderCompiler, caps.glShaderBinary, caps.glGetShaderPrecisionFormat, caps.glDepthRangef, caps.glClearDepthf, caps.glGetProgramBinary, caps.glProgramBinary, caps.glProgramParameteri, caps.glUseProgramStages, caps.glActiveShaderProgram, caps.glCreateShaderProgramv, caps.glBindProgramPipeline, caps.glDeleteProgramPipelines, caps.glGenProgramPipelines, caps.glIsProgramPipeline, caps.glGetProgramPipelineiv, caps.glProgramUniform1i, caps.glProgramUniform2i, caps.glProgramUniform3i, caps.glProgramUniform4i, caps.glProgramUniform1ui, caps.glProgramUniform2ui, caps.glProgramUniform3ui, caps.glProgramUniform4ui, caps.glProgramUniform1f, caps.glProgramUniform2f, caps.glProgramUniform3f, caps.glProgramUniform4f, caps.glProgramUniform1d, caps.glProgramUniform2d, caps.glProgramUniform3d, caps.glProgramUniform4d, caps.glProgramUniform1iv, caps.glProgramUniform2iv, caps.glProgramUniform3iv, caps.glProgramUniform4iv, caps.glProgramUniform1uiv, caps.glProgramUniform2uiv, caps.glProgramUniform3uiv, caps.glProgramUniform4uiv, caps.glProgramUniform1fv, caps.glProgramUniform2fv, caps.glProgramUniform3fv, caps.glProgramUniform4fv, caps.glProgramUniform1dv, caps.glProgramUniform2dv, caps.glProgramUniform3dv, caps.glProgramUniform4dv, caps.glProgramUniformMatrix2fv, caps.glProgramUniformMatrix3fv, caps.glProgramUniformMatrix4fv, caps.glProgramUniformMatrix2dv, caps.glProgramUniformMatrix3dv, caps.glProgramUniformMatrix4dv, caps.glProgramUniformMatrix2x3fv, caps.glProgramUniformMatrix3x2fv, caps.glProgramUniformMatrix2x4fv, caps.glProgramUniformMatrix4x2fv, caps.glProgramUniformMatrix3x4fv, caps.glProgramUniformMatrix4x3fv, caps.glProgramUniformMatrix2x3dv, caps.glProgramUniformMatrix3x2dv, caps.glProgramUniformMatrix2x4dv, caps.glProgramUniformMatrix4x2dv, caps.glProgramUniformMatrix3x4dv, caps.glProgramUniformMatrix4x3dv, caps.glValidateProgramPipeline, caps.glGetProgramPipelineInfoLog, caps.glVertexAttribL1d, caps.glVertexAttribL2d, caps.glVertexAttribL3d, caps.glVertexAttribL4d, caps.glVertexAttribL1dv, caps.glVertexAttribL2dv, caps.glVertexAttribL3dv, caps.glVertexAttribL4dv, caps.glVertexAttribLPointer, caps.glGetVertexAttribLdv, caps.glViewportArrayv, caps.glViewportIndexedf, caps.glViewportIndexedfv, caps.glScissorArrayv, caps.glScissorIndexed, caps.glScissorIndexedv, caps.glDepthRangeArrayv, caps.glDepthRangeIndexed, caps.glGetFloati_v, caps.glGetDoublei_v ); } // --- [ glReleaseShaderCompiler ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glReleaseShaderCompiler.xhtml">OpenGL SDK Reference</a></p> * * Releases resources allocated by the shader compiler. This is a hint from the application, and does not prevent later use of the shader compiler. */ public static void glReleaseShaderCompiler() { long __functionAddress = GL.getCapabilities().glReleaseShaderCompiler; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress); } // --- [ glShaderBinary ] --- /** * Unsafe version of: {@link #glShaderBinary ShaderBinary} * * @param count the number of shader object handles contained in {@code shaders} * @param length the length of the array whose address is given in binary */ public static void nglShaderBinary(int count, long shaders, int binaryformat, long binary, int length) { long __functionAddress = GL.getCapabilities().glShaderBinary; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPPV(__functionAddress, count, shaders, binaryformat, binary, length); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glShaderBinary.xhtml">OpenGL SDK Reference</a></p> * * Loads pre-compiled shader binaries. * * @param shaders an array of shader handles into which to load pre-compiled shader binaries * @param binaryformat the format of the shader binaries contained in {@code binary} * @param binary an array of bytes containing pre-compiled binary shader code */ public static void glShaderBinary(IntBuffer shaders, int binaryformat, ByteBuffer binary) { nglShaderBinary(shaders.remaining(), memAddress(shaders), binaryformat, memAddress(binary), binary.remaining()); } // --- [ glGetShaderPrecisionFormat ] --- /** Unsafe version of: {@link #glGetShaderPrecisionFormat GetShaderPrecisionFormat} */ public static void nglGetShaderPrecisionFormat(int shadertype, int precisiontype, long range, long precision) { long __functionAddress = GL.getCapabilities().glGetShaderPrecisionFormat; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPPV(__functionAddress, shadertype, precisiontype, range, precision); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetShaderPrecisionFormat.xhtml">OpenGL SDK Reference</a></p> * * Retrieves the range and precision for numeric formats supported by the shader compiler. * * @param shadertype the type of shader whose precision to query. One of:<br><table><tr><td>{@link GL20#GL_VERTEX_SHADER VERTEX_SHADER}</td><td>{@link GL20#GL_FRAGMENT_SHADER FRAGMENT_SHADER}</td></tr></table> * @param precisiontype the numeric format whose precision and range to query * @param range the address of array of two integers into which encodings of the implementation's numeric range are returned * @param precision the address of an integer into which the numeric precision of the implementation is written */ public static void glGetShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, IntBuffer precision) { if ( CHECKS ) { checkBuffer(range, 2); checkBuffer(precision, 1); } nglGetShaderPrecisionFormat(shadertype, precisiontype, memAddress(range), memAddress(precision)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetShaderPrecisionFormat.xhtml">OpenGL SDK Reference</a></p> * * Retrieves the range and precision for numeric formats supported by the shader compiler. * * @param shadertype the type of shader whose precision to query. One of:<br><table><tr><td>{@link GL20#GL_VERTEX_SHADER VERTEX_SHADER}</td><td>{@link GL20#GL_FRAGMENT_SHADER FRAGMENT_SHADER}</td></tr></table> * @param precisiontype the numeric format whose precision and range to query * @param range the address of array of two integers into which encodings of the implementation's numeric range are returned */ public static int glGetShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range) { if ( CHECKS ) checkBuffer(range, 2); MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer precision = stack.callocInt(1); nglGetShaderPrecisionFormat(shadertype, precisiontype, memAddress(range), memAddress(precision)); return precision.get(0); } finally { stack.setPointer(stackPointer); } } // --- [ glDepthRangef ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/DepthRange.xhtml">OpenGL SDK Reference</a></p> * * Specifies mapping of depth values from normalized device coordinates to window coordinates * * @param zNear the mapping of the near clipping plane to window coordinates. The initial value is 0.0f. * @param zFar the mapping of the far clipping plane to window coordinates. The initial value is 1.0f. */ public static void glDepthRangef(float zNear, float zFar) { long __functionAddress = GL.getCapabilities().glDepthRangef; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, zNear, zFar); } // --- [ glClearDepthf ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glClearDepthf.xhtml">OpenGL SDK Reference</a></p> * * Specifies the clear value for the depth buffer * * @param depth the depth value used when the depth buffer is cleared. The initial value is 1.0f. */ public static void glClearDepthf(float depth) { long __functionAddress = GL.getCapabilities().glClearDepthf; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, depth); } // --- [ glGetProgramBinary ] --- /** * Unsafe version of: {@link #glGetProgramBinary GetProgramBinary} * * @param bufSize the size of the buffer whose address is given by {@code binary} */ public static void nglGetProgramBinary(int program, int bufSize, long length, long binaryFormat, long binary) { long __functionAddress = GL.getCapabilities().glGetProgramBinary; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPPPV(__functionAddress, program, bufSize, length, binaryFormat, binary); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetProgramBinary.xhtml">OpenGL SDK Reference</a></p> * * Returns a binary representation of a program object's compiled and linked executable source. * * @param program the name of a program object whose binary representation to retrieve * @param length the address of a variable to receive the number of bytes written into {@code binary} * @param binaryFormat a variable to receive a token indicating the format of the binary data returned by the GL * @param binary an array into which the GL will return {@code program}'s binary representation */ public static void glGetProgramBinary(int program, IntBuffer length, IntBuffer binaryFormat, ByteBuffer binary) { if ( CHECKS ) { checkBufferSafe(length, 1); checkBuffer(binaryFormat, 1); } nglGetProgramBinary(program, binary.remaining(), memAddressSafe(length), memAddress(binaryFormat), memAddress(binary)); } // --- [ glProgramBinary ] --- /** * Unsafe version of: {@link #glProgramBinary ProgramBinary} * * @param length the number of bytes contained in {@code binary} */ public static void nglProgramBinary(int program, int binaryFormat, long binary, int length) { long __functionAddress = GL.getCapabilities().glProgramBinary; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, binaryFormat, binary, length); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramBinary.xhtml">OpenGL SDK Reference</a></p> * * Loads a program object with a program binary. * * @param program the name of a program object into which to load a program binary * @param binaryFormat the format of the binary data in binary * @param binary an array containing the binary to be loaded into {@code program} */ public static void glProgramBinary(int program, int binaryFormat, ByteBuffer binary) { nglProgramBinary(program, binaryFormat, memAddress(binary), binary.remaining()); } // --- [ glProgramParameteri ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramParameter.xhtml">OpenGL SDK Reference</a></p> * * Specifies the integer value of a program object parameter. * * @param program the name of a program object whose parameter to modify * @param pname the name of the parameter to modify. One of:<br><table><tr><td>{@link #GL_PROGRAM_BINARY_RETRIEVABLE_HINT PROGRAM_BINARY_RETRIEVABLE_HINT}</td><td>{@link #GL_PROGRAM_SEPARABLE PROGRAM_SEPARABLE}</td></tr></table> * @param value the new value of the parameter specified by {@code pname} for {@code program} */ public static void glProgramParameteri(int program, int pname, int value) { long __functionAddress = GL.getCapabilities().glProgramParameteri; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, pname, value); } // --- [ glUseProgramStages ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glUseProgramStages.xhtml">OpenGL SDK Reference</a></p> * * Binds stages of a program object to a program pipeline. * * @param pipeline the program pipeline object to which to bind stages from {@code program} * @param stages a set of program stages to bind to the program pipeline object * @param program the program object containing the shader executables to use in {@code pipeline} */ public static void glUseProgramStages(int pipeline, int stages, int program) { long __functionAddress = GL.getCapabilities().glUseProgramStages; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, pipeline, stages, program); } // --- [ glActiveShaderProgram ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glActiveShaderProgram.xhtml">OpenGL SDK Reference</a></p> * * Sets the active program object for a program pipeline object. * * @param pipeline the program pipeline object to set the active program object for * @param program the program object to set as the active program pipeline object {@code pipeline} */ public static void glActiveShaderProgram(int pipeline, int program) { long __functionAddress = GL.getCapabilities().glActiveShaderProgram; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, pipeline, program); } // --- [ glCreateShaderProgramv ] --- /** * Unsafe version of: {@link #glCreateShaderProgramv CreateShaderProgramv} * * @param count the number of source code strings in the array {@code strings} */ public static int nglCreateShaderProgramv(int type, int count, long strings) { long __functionAddress = GL.getCapabilities().glCreateShaderProgramv; if ( CHECKS ) checkFunctionAddress(__functionAddress); return callPI(__functionAddress, type, count, strings); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glCreateShaderProgram.xhtml">OpenGL SDK Reference</a></p> * * Creates a stand-alone program from an array of null-terminated source code strings. * * <p>{@code glCreateShaderProgram} is equivalent (assuming no errors are generated) to:</p> * * <pre><code>const GLuint shader = glCreateShader(type); if (shader) { glShaderSource(shader, count, strings, NULL); glCompileShader(shader); const GLuint program = glCreateProgram(); if (program) { GLint compiled = GL_FALSE; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); glProgramParameteri(program, GL_PROGRAM_SEPARABLE, GL_TRUE); if (compiled) { glAttachShader(program, shader); glLinkProgram(program); glDetachShader(program, shader); } // append-shader-info-log-to-program-info-log } glDeleteShader(shader); return program; } else { return 0; }</code></pre> * * <p>The program object created by glCreateShaderProgram has its GL_PROGRAM_SEPARABLE status set to GL_TRUE.</p> * * @param type the type of shader to create * @param strings an array of pointers to source code strings from which to create the program object */ public static int glCreateShaderProgramv(int type, PointerBuffer strings) { return nglCreateShaderProgramv(type, strings.remaining(), memAddress(strings)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glCreateShaderProgram.xhtml">OpenGL SDK Reference</a></p> * * Creates a stand-alone program from an array of null-terminated source code strings. * * <p>{@code glCreateShaderProgram} is equivalent (assuming no errors are generated) to:</p> * * <pre><code>const GLuint shader = glCreateShader(type); if (shader) { glShaderSource(shader, count, strings, NULL); glCompileShader(shader); const GLuint program = glCreateProgram(); if (program) { GLint compiled = GL_FALSE; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); glProgramParameteri(program, GL_PROGRAM_SEPARABLE, GL_TRUE); if (compiled) { glAttachShader(program, shader); glLinkProgram(program); glDetachShader(program, shader); } // append-shader-info-log-to-program-info-log } glDeleteShader(shader); return program; } else { return 0; }</code></pre> * * <p>The program object created by glCreateShaderProgram has its GL_PROGRAM_SEPARABLE status set to GL_TRUE.</p> * * @param type the type of shader to create * @param strings an array of pointers to source code strings from which to create the program object */ public static int glCreateShaderProgramv(int type, CharSequence... strings) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { long stringsAddress = org.lwjgl.system.APIUtil.apiArray(stack, MemoryUtil::memUTF8, strings); int __result = nglCreateShaderProgramv(type, strings.length, stringsAddress); org.lwjgl.system.APIUtil.apiArrayFree(stringsAddress, strings.length); return __result; } finally { stack.setPointer(stackPointer); } } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glCreateShaderProgram.xhtml">OpenGL SDK Reference</a></p> * * Creates a stand-alone program from an array of null-terminated source code strings. * * <p>{@code glCreateShaderProgram} is equivalent (assuming no errors are generated) to:</p> * * <pre><code>const GLuint shader = glCreateShader(type); if (shader) { glShaderSource(shader, count, strings, NULL); glCompileShader(shader); const GLuint program = glCreateProgram(); if (program) { GLint compiled = GL_FALSE; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); glProgramParameteri(program, GL_PROGRAM_SEPARABLE, GL_TRUE); if (compiled) { glAttachShader(program, shader); glLinkProgram(program); glDetachShader(program, shader); } // append-shader-info-log-to-program-info-log } glDeleteShader(shader); return program; } else { return 0; }</code></pre> * * <p>The program object created by glCreateShaderProgram has its GL_PROGRAM_SEPARABLE status set to GL_TRUE.</p> * * @param type the type of shader to create */ public static int glCreateShaderProgramv(int type, CharSequence string) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { long stringsAddress = org.lwjgl.system.APIUtil.apiArray(stack, MemoryUtil::memUTF8, string); int __result = nglCreateShaderProgramv(type, 1, stringsAddress); org.lwjgl.system.APIUtil.apiArrayFree(stringsAddress, 1); return __result; } finally { stack.setPointer(stackPointer); } } // --- [ glBindProgramPipeline ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glBindProgramPipeline.xhtml">OpenGL SDK Reference</a></p> * * Binds a program pipeline to the current context. * * @param pipeline the name of the pipeline object to bind to the context */ public static void glBindProgramPipeline(int pipeline) { long __functionAddress = GL.getCapabilities().glBindProgramPipeline; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, pipeline); } // --- [ glDeleteProgramPipelines ] --- /** * Unsafe version of: {@link #glDeleteProgramPipelines DeleteProgramPipelines} * * @param n the number of program pipeline objects to delete */ public static void nglDeleteProgramPipelines(int n, long pipelines) { long __functionAddress = GL.getCapabilities().glDeleteProgramPipelines; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, n, pipelines); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glDeleteProgramPipelines.xhtml">OpenGL SDK Reference</a></p> * * Deletes program pipeline objects. * * @param pipelines an array of names of program pipeline objects to delete */ public static void glDeleteProgramPipelines(IntBuffer pipelines) { nglDeleteProgramPipelines(pipelines.remaining(), memAddress(pipelines)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glDeleteProgramPipelines.xhtml">OpenGL SDK Reference</a></p> * * Deletes program pipeline objects. */ public static void glDeleteProgramPipelines(int pipeline) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer pipelines = stack.ints(pipeline); nglDeleteProgramPipelines(1, memAddress(pipelines)); } finally { stack.setPointer(stackPointer); } } // --- [ glGenProgramPipelines ] --- /** * Unsafe version of: {@link #glGenProgramPipelines GenProgramPipelines} * * @param n the number of program pipeline object names to reserve */ public static void nglGenProgramPipelines(int n, long pipelines) { long __functionAddress = GL.getCapabilities().glGenProgramPipelines; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, n, pipelines); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGenProgramPipelines.xhtml">OpenGL SDK Reference</a></p> * * Reserves program pipeline object names. * * @param pipelines an array of into which the reserved names will be written */ public static void glGenProgramPipelines(IntBuffer pipelines) { nglGenProgramPipelines(pipelines.remaining(), memAddress(pipelines)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGenProgramPipelines.xhtml">OpenGL SDK Reference</a></p> * * Reserves program pipeline object names. */ public static int glGenProgramPipelines() { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer pipelines = stack.callocInt(1); nglGenProgramPipelines(1, memAddress(pipelines)); return pipelines.get(0); } finally { stack.setPointer(stackPointer); } } // --- [ glIsProgramPipeline ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glIsProgramPipeline.xhtml">OpenGL SDK Reference</a></p> * * Determines if a name corresponds to a program pipeline object. * * @param pipeline a value that may be the name of a program pipeline object */ public static boolean glIsProgramPipeline(int pipeline) { long __functionAddress = GL.getCapabilities().glIsProgramPipeline; if ( CHECKS ) checkFunctionAddress(__functionAddress); return callZ(__functionAddress, pipeline); } // --- [ glGetProgramPipelineiv ] --- /** Unsafe version of: {@link #glGetProgramPipelineiv GetProgramPipelineiv} */ public static void nglGetProgramPipelineiv(int pipeline, int pname, long params) { long __functionAddress = GL.getCapabilities().glGetProgramPipelineiv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, pipeline, pname, params); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetProgramPipeline.xhtml">OpenGL SDK Reference</a></p> * * Retrieves properties of a program pipeline object. * * @param pipeline the name of a program pipeline object whose parameter retrieve * @param pname the name of the parameter to retrieve. One of:<br><table><tr><td>{@link #GL_ACTIVE_PROGRAM ACTIVE_PROGRAM}</td><td>{@link GL20#GL_INFO_LOG_LENGTH INFO_LOG_LENGTH}</td><td>{@link GL20#GL_VERTEX_SHADER VERTEX_SHADER}</td><td>{@link GL20#GL_FRAGMENT_SHADER FRAGMENT_SHADER}</td><td>{@link GL32#GL_GEOMETRY_SHADER GEOMETRY_SHADER}</td></tr><tr><td>{@link GL40#GL_TESS_CONTROL_SHADER TESS_CONTROL_SHADER}</td><td>{@link GL40#GL_TESS_EVALUATION_SHADER TESS_EVALUATION_SHADER}</td></tr></table> * @param params a variable into which will be written the value or values of {@code pname} for {@code pipeline} */ public static void glGetProgramPipelineiv(int pipeline, int pname, IntBuffer params) { if ( CHECKS ) checkBuffer(params, 1); nglGetProgramPipelineiv(pipeline, pname, memAddress(params)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetProgramPipeline.xhtml">OpenGL SDK Reference</a></p> * * Retrieves properties of a program pipeline object. * * @param pipeline the name of a program pipeline object whose parameter retrieve * @param pname the name of the parameter to retrieve. One of:<br><table><tr><td>{@link #GL_ACTIVE_PROGRAM ACTIVE_PROGRAM}</td><td>{@link GL20#GL_INFO_LOG_LENGTH INFO_LOG_LENGTH}</td><td>{@link GL20#GL_VERTEX_SHADER VERTEX_SHADER}</td><td>{@link GL20#GL_FRAGMENT_SHADER FRAGMENT_SHADER}</td><td>{@link GL32#GL_GEOMETRY_SHADER GEOMETRY_SHADER}</td></tr><tr><td>{@link GL40#GL_TESS_CONTROL_SHADER TESS_CONTROL_SHADER}</td><td>{@link GL40#GL_TESS_EVALUATION_SHADER TESS_EVALUATION_SHADER}</td></tr></table> */ public static int glGetProgramPipelinei(int pipeline, int pname) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer params = stack.callocInt(1); nglGetProgramPipelineiv(pipeline, pname, memAddress(params)); return params.get(0); } finally { stack.setPointer(stackPointer); } } // --- [ glProgramUniform1i ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of an int uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value */ public static void glProgramUniform1i(int program, int location, int x) { long __functionAddress = GL.getCapabilities().glProgramUniform1i; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x); } // --- [ glProgramUniform2i ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of an ivec2 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value */ public static void glProgramUniform2i(int program, int location, int x, int y) { long __functionAddress = GL.getCapabilities().glProgramUniform2i; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y); } // --- [ glProgramUniform3i ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of an ivec3 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value * @param z the uniform z value */ public static void glProgramUniform3i(int program, int location, int x, int y, int z) { long __functionAddress = GL.getCapabilities().glProgramUniform3i; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y, z); } // --- [ glProgramUniform4i ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of an ivec4 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value * @param z the uniform z value * @param w the uniform w value */ public static void glProgramUniform4i(int program, int location, int x, int y, int z, int w) { long __functionAddress = GL.getCapabilities().glProgramUniform4i; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y, z, w); } // --- [ glProgramUniform1ui ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a uint uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value */ public static void glProgramUniform1ui(int program, int location, int x) { long __functionAddress = GL.getCapabilities().glProgramUniform1ui; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x); } // --- [ glProgramUniform2ui ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a uvec2 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value */ public static void glProgramUniform2ui(int program, int location, int x, int y) { long __functionAddress = GL.getCapabilities().glProgramUniform2ui; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y); } // --- [ glProgramUniform3ui ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a uvec3 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value * @param z the uniform z value */ public static void glProgramUniform3ui(int program, int location, int x, int y, int z) { long __functionAddress = GL.getCapabilities().glProgramUniform3ui; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y, z); } // --- [ glProgramUniform4ui ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a uvec4 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value * @param z the uniform z value * @param w the uniform w value */ public static void glProgramUniform4ui(int program, int location, int x, int y, int z, int w) { long __functionAddress = GL.getCapabilities().glProgramUniform4ui; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y, z, w); } // --- [ glProgramUniform1f ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a float uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value */ public static void glProgramUniform1f(int program, int location, float x) { long __functionAddress = GL.getCapabilities().glProgramUniform1f; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x); } // --- [ glProgramUniform2f ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a vec2 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value */ public static void glProgramUniform2f(int program, int location, float x, float y) { long __functionAddress = GL.getCapabilities().glProgramUniform2f; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y); } // --- [ glProgramUniform3f ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a vec3 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value * @param z the uniform z value */ public static void glProgramUniform3f(int program, int location, float x, float y, float z) { long __functionAddress = GL.getCapabilities().glProgramUniform3f; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y, z); } // --- [ glProgramUniform4f ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a vec4 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value * @param z the uniform z value * @param w the uniform w value */ public static void glProgramUniform4f(int program, int location, float x, float y, float z, float w) { long __functionAddress = GL.getCapabilities().glProgramUniform4f; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y, z, w); } // --- [ glProgramUniform1d ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a double uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value */ public static void glProgramUniform1d(int program, int location, double x) { long __functionAddress = GL.getCapabilities().glProgramUniform1d; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x); } // --- [ glProgramUniform2d ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a dvec2 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value */ public static void glProgramUniform2d(int program, int location, double x, double y) { long __functionAddress = GL.getCapabilities().glProgramUniform2d; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y); } // --- [ glProgramUniform3d ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a dvec3 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value * @param z the uniform z value */ public static void glProgramUniform3d(int program, int location, double x, double y, double z) { long __functionAddress = GL.getCapabilities().glProgramUniform3d; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y, z); } // --- [ glProgramUniform4d ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a dvec4 uniform variable for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param x the uniform x value * @param y the uniform y value * @param z the uniform z value * @param w the uniform w value */ public static void glProgramUniform4d(int program, int location, double x, double y, double z, double w) { long __functionAddress = GL.getCapabilities().glProgramUniform4d; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, program, location, x, y, z, w); } // --- [ glProgramUniform1iv ] --- /** * Unsafe version of: {@link #glProgramUniform1iv ProgramUniform1iv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform1iv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform1iv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single float uniform variable or a float uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform1iv(int program, int location, IntBuffer value) { nglProgramUniform1iv(program, location, value.remaining(), memAddress(value)); } // --- [ glProgramUniform2iv ] --- /** * Unsafe version of: {@link #glProgramUniform2iv ProgramUniform2iv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform2iv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform2iv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single ivec2 uniform variable or an ivec2 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform2iv(int program, int location, IntBuffer value) { nglProgramUniform2iv(program, location, value.remaining() >> 1, memAddress(value)); } // --- [ glProgramUniform3iv ] --- /** * Unsafe version of: {@link #glProgramUniform3iv ProgramUniform3iv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform3iv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform3iv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single ivec3 uniform variable or an ivec3 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform3iv(int program, int location, IntBuffer value) { nglProgramUniform3iv(program, location, value.remaining() / 3, memAddress(value)); } // --- [ glProgramUniform4iv ] --- /** * Unsafe version of: {@link #glProgramUniform4iv ProgramUniform4iv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform4iv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform4iv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single ivec4 uniform variable or an ivec4 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform4iv(int program, int location, IntBuffer value) { nglProgramUniform4iv(program, location, value.remaining() >> 2, memAddress(value)); } // --- [ glProgramUniform1uiv ] --- /** * Unsafe version of: {@link #glProgramUniform1uiv ProgramUniform1uiv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform1uiv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform1uiv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single uint uniform variable or a uint uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform1uiv(int program, int location, IntBuffer value) { nglProgramUniform1uiv(program, location, value.remaining(), memAddress(value)); } // --- [ glProgramUniform2uiv ] --- /** * Unsafe version of: {@link #glProgramUniform2uiv ProgramUniform2uiv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform2uiv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform2uiv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single uvec2 uniform variable or a uvec2 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform2uiv(int program, int location, IntBuffer value) { nglProgramUniform2uiv(program, location, value.remaining() >> 1, memAddress(value)); } // --- [ glProgramUniform3uiv ] --- /** * Unsafe version of: {@link #glProgramUniform3uiv ProgramUniform3uiv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform3uiv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform3uiv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single uvec3 uniform variable or a uvec3 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform3uiv(int program, int location, IntBuffer value) { nglProgramUniform3uiv(program, location, value.remaining() / 3, memAddress(value)); } // --- [ glProgramUniform4uiv ] --- /** * Unsafe version of: {@link #glProgramUniform4uiv ProgramUniform4uiv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform4uiv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform4uiv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single uvec4 uniform variable or a uvec4 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform4uiv(int program, int location, IntBuffer value) { nglProgramUniform4uiv(program, location, value.remaining() >> 2, memAddress(value)); } // --- [ glProgramUniform1fv ] --- /** * Unsafe version of: {@link #glProgramUniform1fv ProgramUniform1fv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform1fv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform1fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single float uniform variable or a float uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform1fv(int program, int location, FloatBuffer value) { nglProgramUniform1fv(program, location, value.remaining(), memAddress(value)); } // --- [ glProgramUniform2fv ] --- /** * Unsafe version of: {@link #glProgramUniform2fv ProgramUniform2fv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform2fv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform2fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single vec2 uniform variable or a vec2 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform2fv(int program, int location, FloatBuffer value) { nglProgramUniform2fv(program, location, value.remaining() >> 1, memAddress(value)); } // --- [ glProgramUniform3fv ] --- /** * Unsafe version of: {@link #glProgramUniform3fv ProgramUniform3fv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform3fv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform3fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single vec3 uniform variable or a vec3 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform3fv(int program, int location, FloatBuffer value) { nglProgramUniform3fv(program, location, value.remaining() / 3, memAddress(value)); } // --- [ glProgramUniform4fv ] --- /** * Unsafe version of: {@link #glProgramUniform4fv ProgramUniform4fv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform4fv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform4fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single vec4 uniform variable or a vec4 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform4fv(int program, int location, FloatBuffer value) { nglProgramUniform4fv(program, location, value.remaining() >> 2, memAddress(value)); } // --- [ glProgramUniform1dv ] --- /** * Unsafe version of: {@link #glProgramUniform1dv ProgramUniform1dv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform1dv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform1dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single double uniform variable or a double uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform1dv(int program, int location, DoubleBuffer value) { nglProgramUniform1dv(program, location, value.remaining(), memAddress(value)); } // --- [ glProgramUniform2dv ] --- /** * Unsafe version of: {@link #glProgramUniform2dv ProgramUniform2dv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform2dv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform2dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dvec2 uniform variable or a dvec2 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform2dv(int program, int location, DoubleBuffer value) { nglProgramUniform2dv(program, location, value.remaining() >> 1, memAddress(value)); } // --- [ glProgramUniform3dv ] --- /** * Unsafe version of: {@link #glProgramUniform3dv ProgramUniform3dv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform3dv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform3dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dvec3 uniform variable or a dvec3 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform3dv(int program, int location, DoubleBuffer value) { nglProgramUniform3dv(program, location, value.remaining() / 3, memAddress(value)); } // --- [ glProgramUniform4dv ] --- /** * Unsafe version of: {@link #glProgramUniform4dv ProgramUniform4dv} * * @param count the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array. */ public static void nglProgramUniform4dv(int program, int location, int count, long value) { long __functionAddress = GL.getCapabilities().glProgramUniform4dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dvec4 uniform variable or a dvec4 uniform variable array for a specified program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param value an array of {@code count} values that will be used to update the specified uniform variable */ public static void glProgramUniform4dv(int program, int location, DoubleBuffer value) { nglProgramUniform4dv(program, location, value.remaining() >> 2, memAddress(value)); } // --- [ glProgramUniformMatrix2fv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix2fv ProgramUniformMatrix2fv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix2fv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single mat2 uniform variable or a mat2 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix2fv(int program, int location, boolean transpose, FloatBuffer value) { nglProgramUniformMatrix2fv(program, location, value.remaining() >> 2, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix3fv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix3fv ProgramUniformMatrix3fv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix3fv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single mat3 uniform variable or a mat3 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix3fv(int program, int location, boolean transpose, FloatBuffer value) { nglProgramUniformMatrix3fv(program, location, value.remaining() / 9, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix4fv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix4fv ProgramUniformMatrix4fv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix4fv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single mat4 uniform variable or a mat4 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix4fv(int program, int location, boolean transpose, FloatBuffer value) { nglProgramUniformMatrix4fv(program, location, value.remaining() >> 4, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix2dv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix2dv ProgramUniformMatrix2dv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix2dv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dmat2 uniform variable or a dmat2 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix2dv(int program, int location, boolean transpose, DoubleBuffer value) { nglProgramUniformMatrix2dv(program, location, value.remaining() >> 2, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix3dv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix3dv ProgramUniformMatrix3dv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix3dv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dmat3 uniform variable or a dmat3 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix3dv(int program, int location, boolean transpose, DoubleBuffer value) { nglProgramUniformMatrix3dv(program, location, value.remaining() / 9, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix4dv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix4dv ProgramUniformMatrix4dv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix4dv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dmat4 uniform variable or a dmat4 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix4dv(int program, int location, boolean transpose, DoubleBuffer value) { nglProgramUniformMatrix4dv(program, location, value.remaining() >> 4, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix2x3fv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix2x3fv ProgramUniformMatrix2x3fv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix2x3fv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2x3fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single mat2x3 uniform variable or a mat2x3 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix2x3fv(int program, int location, boolean transpose, FloatBuffer value) { nglProgramUniformMatrix2x3fv(program, location, value.remaining() / 6, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix3x2fv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix3x2fv ProgramUniformMatrix3x2fv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix3x2fv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3x2fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single mat3x2 uniform variable or a mat3x2 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix3x2fv(int program, int location, boolean transpose, FloatBuffer value) { nglProgramUniformMatrix3x2fv(program, location, value.remaining() / 6, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix2x4fv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix2x4fv ProgramUniformMatrix2x4fv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix2x4fv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2x4fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single mat2x4 uniform variable or a mat2x4 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix2x4fv(int program, int location, boolean transpose, FloatBuffer value) { nglProgramUniformMatrix2x4fv(program, location, value.remaining() >> 3, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix4x2fv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix4x2fv ProgramUniformMatrix4x2fv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix4x2fv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4x2fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single mat4x2 uniform variable or a mat4x2 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix4x2fv(int program, int location, boolean transpose, FloatBuffer value) { nglProgramUniformMatrix4x2fv(program, location, value.remaining() >> 3, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix3x4fv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix3x4fv ProgramUniformMatrix3x4fv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix3x4fv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3x4fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single mat3x4 uniform variable or a mat3x4 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix3x4fv(int program, int location, boolean transpose, FloatBuffer value) { nglProgramUniformMatrix3x4fv(program, location, value.remaining() / 12, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix4x3fv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix4x3fv ProgramUniformMatrix4x3fv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix4x3fv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4x3fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single mat4x3 uniform variable or a mat4x3 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix4x3fv(int program, int location, boolean transpose, FloatBuffer value) { nglProgramUniformMatrix4x3fv(program, location, value.remaining() / 12, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix2x3dv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix2x3dv ProgramUniformMatrix2x3dv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix2x3dv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2x3dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dmat2x3 uniform variable or a dmat2x3 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix2x3dv(int program, int location, boolean transpose, DoubleBuffer value) { nglProgramUniformMatrix2x3dv(program, location, value.remaining() / 6, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix3x2dv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix3x2dv ProgramUniformMatrix3x2dv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix3x2dv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3x2dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dmat3x2 uniform variable or a dmat3x2 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix3x2dv(int program, int location, boolean transpose, DoubleBuffer value) { nglProgramUniformMatrix3x2dv(program, location, value.remaining() / 6, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix2x4dv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix2x4dv ProgramUniformMatrix2x4dv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix2x4dv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2x4dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dmat2x4 uniform variable or a dmat2x4 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix2x4dv(int program, int location, boolean transpose, DoubleBuffer value) { nglProgramUniformMatrix2x4dv(program, location, value.remaining() >> 3, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix4x2dv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix4x2dv ProgramUniformMatrix4x2dv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix4x2dv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4x2dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dmat4x2 uniform variable or a dmat4x2 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix4x2dv(int program, int location, boolean transpose, DoubleBuffer value) { nglProgramUniformMatrix4x2dv(program, location, value.remaining() >> 3, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix3x4dv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix3x4dv ProgramUniformMatrix3x4dv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix3x4dv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3x4dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dmat3x4 uniform variable or a dmat3x4 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix3x4dv(int program, int location, boolean transpose, DoubleBuffer value) { nglProgramUniformMatrix3x4dv(program, location, value.remaining() / 12, transpose, memAddress(value)); } // --- [ glProgramUniformMatrix4x3dv ] --- /** * Unsafe version of: {@link #glProgramUniformMatrix4x3dv ProgramUniformMatrix4x3dv} * * @param count the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices. */ public static void nglProgramUniformMatrix4x3dv(int program, int location, int count, boolean transpose, long value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4x3dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, count, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a single dmat4x3 uniform variable or a dmat4x3 uniform variable array for the current program object. * * @param program the handle of the program containing the uniform variable to be modified * @param location the location of the uniform variable to be modified * @param transpose whether to transpose the matrix as the values are loaded into the uniform variable * @param value an array of {@code count} values that will be used to update the specified uniform matrix variable */ public static void glProgramUniformMatrix4x3dv(int program, int location, boolean transpose, DoubleBuffer value) { nglProgramUniformMatrix4x3dv(program, location, value.remaining() / 12, transpose, memAddress(value)); } // --- [ glValidateProgramPipeline ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glValidateProgramPipeline.xhtml">OpenGL SDK Reference</a></p> * * Validates a program pipeline object against current GL state. * * @param pipeline the name of a program pipeline object to validate */ public static void glValidateProgramPipeline(int pipeline) { long __functionAddress = GL.getCapabilities().glValidateProgramPipeline; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, pipeline); } // --- [ glGetProgramPipelineInfoLog ] --- /** * Unsafe version of: {@link #glGetProgramPipelineInfoLog GetProgramPipelineInfoLog} * * @param bufSize the maximum number of characters, including the null terminator, that may be written into {@code infoLog} */ public static void nglGetProgramPipelineInfoLog(int pipeline, int bufSize, long length, long infoLog) { long __functionAddress = GL.getCapabilities().glGetProgramPipelineInfoLog; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPPV(__functionAddress, pipeline, bufSize, length, infoLog); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetProgramPipelineInfoLog.xhtml">OpenGL SDK Reference</a></p> * * Retrieves the info log string from a program pipeline object. * * @param pipeline the name of a program pipeline object from which to retrieve the info log * @param length a variable into which will be written the number of characters written into {@code infoLog} * @param infoLog an array of characters into which will be written the info log for {@code pipeline} */ public static void glGetProgramPipelineInfoLog(int pipeline, IntBuffer length, ByteBuffer infoLog) { if ( CHECKS ) checkBufferSafe(length, 1); nglGetProgramPipelineInfoLog(pipeline, infoLog.remaining(), memAddressSafe(length), memAddress(infoLog)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetProgramPipelineInfoLog.xhtml">OpenGL SDK Reference</a></p> * * Retrieves the info log string from a program pipeline object. * * @param pipeline the name of a program pipeline object from which to retrieve the info log * @param bufSize the maximum number of characters, including the null terminator, that may be written into {@code infoLog} */ public static String glGetProgramPipelineInfoLog(int pipeline, int bufSize) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); ByteBuffer infoLog = memAlloc(bufSize); try { IntBuffer length = stack.ints(0); nglGetProgramPipelineInfoLog(pipeline, bufSize, memAddress(length), memAddress(infoLog)); return memUTF8(infoLog, length.get(0)); } finally { memFree(infoLog); stack.setPointer(stackPointer); } } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetProgramPipelineInfoLog.xhtml">OpenGL SDK Reference</a></p> * * Retrieves the info log string from a program pipeline object. * * @param pipeline the name of a program pipeline object from which to retrieve the info log */ public static String glGetProgramPipelineInfoLog(int pipeline) { int bufSize = glGetProgramPipelinei(pipeline, GL20.GL_INFO_LOG_LENGTH); MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); ByteBuffer infoLog = memAlloc(bufSize); try { IntBuffer length = stack.ints(0); nglGetProgramPipelineInfoLog(pipeline, bufSize, memAddress(length), memAddress(infoLog)); return memUTF8(infoLog, length.get(0)); } finally { memFree(infoLog); stack.setPointer(stackPointer); } } // --- [ glVertexAttribL1d ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a generic vertex attribute. The y and z components are implicitly set to 0.0 and w to 1.0. * * @param index the index of the generic vertex attribute to be modified * @param x the vertex attribute x component */ public static void glVertexAttribL1d(int index, double x) { long __functionAddress = GL.getCapabilities().glVertexAttribL1d; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, x); } // --- [ glVertexAttribL2d ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a generic vertex attribute. The y component is implicitly set to 0.0 and w to 1.0. * * @param index the index of the generic vertex attribute to be modified * @param x the vertex attribute x component * @param y the vertex attribute y component */ public static void glVertexAttribL2d(int index, double x, double y) { long __functionAddress = GL.getCapabilities().glVertexAttribL2d; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, x, y); } // --- [ glVertexAttribL3d ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a generic vertex attribute. The w is implicitly set to 1.0. * * @param index the index of the generic vertex attribute to be modified * @param x the vertex attribute x component * @param y the vertex attribute y component * @param z the vertex attribute z component */ public static void glVertexAttribL3d(int index, double x, double y, double z) { long __functionAddress = GL.getCapabilities().glVertexAttribL3d; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, x, y, z); } // --- [ glVertexAttribL4d ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Specifies the value of a generic vertex attribute. * * @param index the index of the generic vertex attribute to be modified * @param x the vertex attribute x component * @param y the vertex attribute y component * @param z the vertex attribute z component * @param w the vertex attribute w component */ public static void glVertexAttribL4d(int index, double x, double y, double z, double w) { long __functionAddress = GL.getCapabilities().glVertexAttribL4d; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, x, y, z, w); } // --- [ glVertexAttribL1dv ] --- /** Unsafe version of: {@link #glVertexAttribL1dv VertexAttribL1dv} */ public static void nglVertexAttribL1dv(int index, long v) { long __functionAddress = GL.getCapabilities().glVertexAttribL1dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Pointer version of {@link #glVertexAttribL1d VertexAttribL1d}. * * @param index the index of the generic vertex attribute to be modified * @param v the vertex attribute buffer */ public static void glVertexAttribL1dv(int index, DoubleBuffer v) { if ( CHECKS ) checkBuffer(v, 1); nglVertexAttribL1dv(index, memAddress(v)); } // --- [ glVertexAttribL2dv ] --- /** Unsafe version of: {@link #glVertexAttribL2dv VertexAttribL2dv} */ public static void nglVertexAttribL2dv(int index, long v) { long __functionAddress = GL.getCapabilities().glVertexAttribL2dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Pointer version of {@link #glVertexAttribL2d VertexAttribL2d}. * * @param index the index of the generic vertex attribute to be modified * @param v the vertex attribute buffer */ public static void glVertexAttribL2dv(int index, DoubleBuffer v) { if ( CHECKS ) checkBuffer(v, 2); nglVertexAttribL2dv(index, memAddress(v)); } // --- [ glVertexAttribL3dv ] --- /** Unsafe version of: {@link #glVertexAttribL3dv VertexAttribL3dv} */ public static void nglVertexAttribL3dv(int index, long v) { long __functionAddress = GL.getCapabilities().glVertexAttribL3dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Pointer version of {@link #glVertexAttribL3d VertexAttribL3d}. * * @param index the index of the generic vertex attribute to be modified * @param v the vertex attribute buffer */ public static void glVertexAttribL3dv(int index, DoubleBuffer v) { if ( CHECKS ) checkBuffer(v, 3); nglVertexAttribL3dv(index, memAddress(v)); } // --- [ glVertexAttribL4dv ] --- /** Unsafe version of: {@link #glVertexAttribL4dv VertexAttribL4dv} */ public static void nglVertexAttribL4dv(int index, long v) { long __functionAddress = GL.getCapabilities().glVertexAttribL4dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Pointer version of {@link #glVertexAttribL4d VertexAttribL4d}. * * @param index the index of the generic vertex attribute to be modified * @param v the vertex attribute buffer */ public static void glVertexAttribL4dv(int index, DoubleBuffer v) { if ( CHECKS ) checkBuffer(v, 4); nglVertexAttribL4dv(index, memAddress(v)); } // --- [ glVertexAttribLPointer ] --- /** * Unsafe version of: {@link #glVertexAttribLPointer VertexAttribLPointer} * * @param type the data type of each component in the array. Must be:<br><table><tr><td>{@link GL11#GL_DOUBLE DOUBLE}</td></tr></table> */ public static void nglVertexAttribLPointer(int index, int size, int type, int stride, long pointer) { long __functionAddress = GL.getCapabilities().glVertexAttribLPointer; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, size, type, stride, pointer); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttribPointer.xhtml">OpenGL SDK Reference</a></p> * * Specifies the location and organization of a 64-bit vertex attribute array. * * @param index the index of the generic vertex attribute to be modified * @param size the number of values per vertex that are stored in the array. The initial value is 4. One of:<br><table><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>{@link GL12#GL_BGRA BGRA}</td></tr></table> * @param type the data type of each component in the array. Must be:<br><table><tr><td>{@link GL11#GL_DOUBLE DOUBLE}</td></tr></table> * @param stride the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in * the array. The initial value is 0. * @param pointer the vertex attribute data or the offset of the first component of the first generic vertex attribute in the array in the data store of the buffer * currently bound to the {@link GL15#GL_ARRAY_BUFFER ARRAY_BUFFER} target. The initial value is 0. */ public static void glVertexAttribLPointer(int index, int size, int type, int stride, ByteBuffer pointer) { nglVertexAttribLPointer(index, size, type, stride, memAddress(pointer)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttribPointer.xhtml">OpenGL SDK Reference</a></p> * * Specifies the location and organization of a 64-bit vertex attribute array. * * @param index the index of the generic vertex attribute to be modified * @param size the number of values per vertex that are stored in the array. The initial value is 4. One of:<br><table><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>{@link GL12#GL_BGRA BGRA}</td></tr></table> * @param type the data type of each component in the array. Must be:<br><table><tr><td>{@link GL11#GL_DOUBLE DOUBLE}</td></tr></table> * @param stride the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in * the array. The initial value is 0. * @param pointer the vertex attribute data or the offset of the first component of the first generic vertex attribute in the array in the data store of the buffer * currently bound to the {@link GL15#GL_ARRAY_BUFFER ARRAY_BUFFER} target. The initial value is 0. */ public static void glVertexAttribLPointer(int index, int size, int type, int stride, long pointer) { nglVertexAttribLPointer(index, size, type, stride, pointer); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttribPointer.xhtml">OpenGL SDK Reference</a></p> * * Specifies the location and organization of a 64-bit vertex attribute array. * * @param index the index of the generic vertex attribute to be modified * @param size the number of values per vertex that are stored in the array. The initial value is 4. One of:<br><table><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>{@link GL12#GL_BGRA BGRA}</td></tr></table> * @param stride the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in * the array. The initial value is 0. * @param pointer the vertex attribute data or the offset of the first component of the first generic vertex attribute in the array in the data store of the buffer * currently bound to the {@link GL15#GL_ARRAY_BUFFER ARRAY_BUFFER} target. The initial value is 0. */ public static void glVertexAttribLPointer(int index, int size, int stride, DoubleBuffer pointer) { nglVertexAttribLPointer(index, size, GL11.GL_DOUBLE, stride, memAddress(pointer)); } // --- [ glGetVertexAttribLdv ] --- /** Unsafe version of: {@link #glGetVertexAttribLdv GetVertexAttribLdv} */ public static void nglGetVertexAttribLdv(int index, int pname, long params) { long __functionAddress = GL.getCapabilities().glGetVertexAttribLdv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, pname, params); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Double version of {@link GL20#glGetVertexAttribi GetVertexAttribi}. * * @param index the generic vertex attribute parameter to be queried * @param pname the symbolic name of the vertex attribute parameter to be queried * @param params the requested data */ public static void glGetVertexAttribLdv(int index, int pname, DoubleBuffer params) { nglGetVertexAttribLdv(index, pname, memAddress(params)); } // --- [ glViewportArrayv ] --- /** * Unsafe version of: {@link #glViewportArrayv ViewportArrayv} * * @param count the number of viewports to set */ public static void nglViewportArrayv(int first, int count, long v) { long __functionAddress = GL.getCapabilities().glViewportArrayv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, first, count, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glViewportArray.xhtml">OpenGL SDK Reference</a></p> * * Sets multiple viewports. * * @param first the first viewport to set * @param v an array containing the viewport parameters */ public static void glViewportArrayv(int first, FloatBuffer v) { nglViewportArrayv(first, v.remaining() >> 2, memAddress(v)); } // --- [ glViewportIndexedf ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glViewportIndexed.xhtml">OpenGL SDK Reference</a></p> * * Sets a specified viewport. * * @param index the viewport to set * @param x the left viewport coordinate * @param y the bottom viewport coordinate * @param w the viewport width * @param h the viewport height */ public static void glViewportIndexedf(int index, float x, float y, float w, float h) { long __functionAddress = GL.getCapabilities().glViewportIndexedf; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, x, y, w, h); } // --- [ glViewportIndexedfv ] --- /** Unsafe version of: {@link #glViewportIndexedfv ViewportIndexedfv} */ public static void nglViewportIndexedfv(int index, long v) { long __functionAddress = GL.getCapabilities().glViewportIndexedfv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glViewportIndexed.xhtml">OpenGL SDK Reference</a></p> * * Pointer version of {@link #glViewportIndexedf ViewportIndexedf}. * * @param index the viewport to set * @param v the viewport parameters */ public static void glViewportIndexedfv(int index, FloatBuffer v) { if ( CHECKS ) checkBuffer(v, 4); nglViewportIndexedfv(index, memAddress(v)); } // --- [ glScissorArrayv ] --- /** * Unsafe version of: {@link #glScissorArrayv ScissorArrayv} * * @param count the number of scissor boxes to modify */ public static void nglScissorArrayv(int first, int count, long v) { long __functionAddress = GL.getCapabilities().glScissorArrayv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, first, count, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glScissorArray.xhtml">OpenGL SDK Reference</a></p> * * Defines the scissor box for multiple viewports. * * @param first the index of the first viewport whose scissor box to modify * @param v an array containing the left, bottom, width and height of each scissor box, in that order */ public static void glScissorArrayv(int first, IntBuffer v) { nglScissorArrayv(first, v.remaining() >> 2, memAddress(v)); } // --- [ glScissorIndexed ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glScissorIndexed.xhtml">OpenGL SDK Reference</a></p> * * Defines the scissor box for a specific viewport. * * @param index the index of the viewport whose scissor box to modify * @param left the left scissor box coordinate * @param bottom the bottom scissor box coordinate * @param width the scissor box width * @param height the scissor box height */ public static void glScissorIndexed(int index, int left, int bottom, int width, int height) { long __functionAddress = GL.getCapabilities().glScissorIndexed; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, left, bottom, width, height); } // --- [ glScissorIndexedv ] --- /** Unsafe version of: {@link #glScissorIndexedv ScissorIndexedv} */ public static void nglScissorIndexedv(int index, long v) { long __functionAddress = GL.getCapabilities().glScissorIndexedv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glScissorIndexed.xhtml">OpenGL SDK Reference</a></p> * * Pointer version of {@link #glScissorIndexed ScissorIndexed}. * * @param index the index of the viewport whose scissor box to modify * @param v an array containing the left, bottom, width and height of each scissor box, in that order */ public static void glScissorIndexedv(int index, IntBuffer v) { if ( CHECKS ) checkBuffer(v, 4); nglScissorIndexedv(index, memAddress(v)); } // --- [ glDepthRangeArrayv ] --- /** * Unsafe version of: {@link #glDepthRangeArrayv DepthRangeArrayv} * * @param count the number of viewports whose depth range to update */ public static void nglDepthRangeArrayv(int first, int count, long v) { long __functionAddress = GL.getCapabilities().glDepthRangeArrayv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, first, count, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glDepthRangeArray.xhtml">OpenGL SDK Reference</a></p> * * Specifies mapping of depth values from normalized device coordinates to window coordinates for a specified set of viewports. * * @param first the index of the first viewport whose depth range to update * @param v n array containing the near and far values for the depth range of each modified viewport */ public static void glDepthRangeArrayv(int first, DoubleBuffer v) { nglDepthRangeArrayv(first, v.remaining() >> 1, memAddress(v)); } // --- [ glDepthRangeIndexed ] --- /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glDepthRangeIndexed.xhtml">OpenGL SDK Reference</a></p> * * Specifies mapping of depth values from normalized device coordinates to window coordinates for a specified viewport. * * @param index the index of the viewport whose depth range to update * @param zNear the mapping of the near clipping plane to window coordinates. The initial value is 0. * @param zFar the mapping of the far clipping plane to window coordinates. The initial value is 1. */ public static void glDepthRangeIndexed(int index, double zNear, double zFar) { long __functionAddress = GL.getCapabilities().glDepthRangeIndexed; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, zNear, zFar); } // --- [ glGetFloati_v ] --- /** Unsafe version of: {@link #glGetFloati_v GetFloati_v} */ public static void nglGetFloati_v(int target, int index, long data) { long __functionAddress = GL.getCapabilities().glGetFloati_v; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, target, index, data); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetFloati.xhtml">OpenGL SDK Reference</a></p> * * Queries the float value of an indexed state variable. * * @param target the indexed state to query * @param index the index of the element being queried * @param data a scalar or buffer in which to place the returned data */ public static void glGetFloati_v(int target, int index, FloatBuffer data) { if ( CHECKS ) checkBuffer(data, 1); nglGetFloati_v(target, index, memAddress(data)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetFloati.xhtml">OpenGL SDK Reference</a></p> * * Queries the float value of an indexed state variable. * * @param target the indexed state to query * @param index the index of the element being queried */ public static float glGetFloati(int target, int index) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { FloatBuffer data = stack.callocFloat(1); nglGetFloati_v(target, index, memAddress(data)); return data.get(0); } finally { stack.setPointer(stackPointer); } } // --- [ glGetDoublei_v ] --- /** Unsafe version of: {@link #glGetDoublei_v GetDoublei_v} */ public static void nglGetDoublei_v(int target, int index, long data) { long __functionAddress = GL.getCapabilities().glGetDoublei_v; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, target, index, data); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetDoublei.xhtml">OpenGL SDK Reference</a></p> * * Queries the double value of an indexed state variable. * * @param target the indexed state to query * @param index the index of the element being queried * @param data a scalar or buffer in which to place the returned data */ public static void glGetDoublei_v(int target, int index, DoubleBuffer data) { if ( CHECKS ) checkBuffer(data, 1); nglGetDoublei_v(target, index, memAddress(data)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetDoublei.xhtml">OpenGL SDK Reference</a></p> * * Queries the double value of an indexed state variable. * * @param target the indexed state to query * @param index the index of the element being queried */ public static double glGetDoublei(int target, int index) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { DoubleBuffer data = stack.callocDouble(1); nglGetDoublei_v(target, index, memAddress(data)); return data.get(0); } finally { stack.setPointer(stackPointer); } } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glShaderBinary.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glShaderBinary ShaderBinary} */ public static void glShaderBinary(int[] shaders, int binaryformat, ByteBuffer binary) { long __functionAddress = GL.getCapabilities().glShaderBinary; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPPV(__functionAddress, shaders.length, shaders, binaryformat, memAddress(binary), binary.remaining()); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetShaderPrecisionFormat.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glGetShaderPrecisionFormat GetShaderPrecisionFormat} */ public static void glGetShaderPrecisionFormat(int shadertype, int precisiontype, int[] range, int[] precision) { long __functionAddress = GL.getCapabilities().glGetShaderPrecisionFormat; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(range, 2); checkBuffer(precision, 1); } callPPV(__functionAddress, shadertype, precisiontype, range, precision); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetProgramBinary.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glGetProgramBinary GetProgramBinary} */ public static void glGetProgramBinary(int program, int[] length, int[] binaryFormat, ByteBuffer binary) { long __functionAddress = GL.getCapabilities().glGetProgramBinary; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBufferSafe(length, 1); checkBuffer(binaryFormat, 1); } callPPPV(__functionAddress, program, binary.remaining(), length, binaryFormat, memAddress(binary)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glDeleteProgramPipelines.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glDeleteProgramPipelines DeleteProgramPipelines} */ public static void glDeleteProgramPipelines(int[] pipelines) { long __functionAddress = GL.getCapabilities().glDeleteProgramPipelines; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, pipelines.length, pipelines); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGenProgramPipelines.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glGenProgramPipelines GenProgramPipelines} */ public static void glGenProgramPipelines(int[] pipelines) { long __functionAddress = GL.getCapabilities().glGenProgramPipelines; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, pipelines.length, pipelines); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetProgramPipeline.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glGetProgramPipelineiv GetProgramPipelineiv} */ public static void glGetProgramPipelineiv(int pipeline, int pname, int[] params) { long __functionAddress = GL.getCapabilities().glGetProgramPipelineiv; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(params, 1); } callPV(__functionAddress, pipeline, pname, params); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform1iv ProgramUniform1iv} */ public static void glProgramUniform1iv(int program, int location, int[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform1iv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform2iv ProgramUniform2iv} */ public static void glProgramUniform2iv(int program, int location, int[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform2iv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 1, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform3iv ProgramUniform3iv} */ public static void glProgramUniform3iv(int program, int location, int[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform3iv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 3, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform4iv ProgramUniform4iv} */ public static void glProgramUniform4iv(int program, int location, int[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform4iv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 2, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform1uiv ProgramUniform1uiv} */ public static void glProgramUniform1uiv(int program, int location, int[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform1uiv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform2uiv ProgramUniform2uiv} */ public static void glProgramUniform2uiv(int program, int location, int[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform2uiv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 1, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform3uiv ProgramUniform3uiv} */ public static void glProgramUniform3uiv(int program, int location, int[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform3uiv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 3, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform4uiv ProgramUniform4uiv} */ public static void glProgramUniform4uiv(int program, int location, int[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform4uiv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 2, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform1fv ProgramUniform1fv} */ public static void glProgramUniform1fv(int program, int location, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform1fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform2fv ProgramUniform2fv} */ public static void glProgramUniform2fv(int program, int location, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform2fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 1, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform3fv ProgramUniform3fv} */ public static void glProgramUniform3fv(int program, int location, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform3fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 3, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform4fv ProgramUniform4fv} */ public static void glProgramUniform4fv(int program, int location, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform4fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 2, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform1dv ProgramUniform1dv} */ public static void glProgramUniform1dv(int program, int location, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform1dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform2dv ProgramUniform2dv} */ public static void glProgramUniform2dv(int program, int location, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform2dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 1, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform3dv ProgramUniform3dv} */ public static void glProgramUniform3dv(int program, int location, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform3dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 3, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniform4dv ProgramUniform4dv} */ public static void glProgramUniform4dv(int program, int location, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniform4dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 2, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix2fv ProgramUniformMatrix2fv} */ public static void glProgramUniformMatrix2fv(int program, int location, boolean transpose, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 2, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix3fv ProgramUniformMatrix3fv} */ public static void glProgramUniformMatrix3fv(int program, int location, boolean transpose, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 9, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix4fv ProgramUniformMatrix4fv} */ public static void glProgramUniformMatrix4fv(int program, int location, boolean transpose, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 4, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix2dv ProgramUniformMatrix2dv} */ public static void glProgramUniformMatrix2dv(int program, int location, boolean transpose, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 2, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix3dv ProgramUniformMatrix3dv} */ public static void glProgramUniformMatrix3dv(int program, int location, boolean transpose, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 9, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix4dv ProgramUniformMatrix4dv} */ public static void glProgramUniformMatrix4dv(int program, int location, boolean transpose, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 4, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix2x3fv ProgramUniformMatrix2x3fv} */ public static void glProgramUniformMatrix2x3fv(int program, int location, boolean transpose, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2x3fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 6, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix3x2fv ProgramUniformMatrix3x2fv} */ public static void glProgramUniformMatrix3x2fv(int program, int location, boolean transpose, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3x2fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 6, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix2x4fv ProgramUniformMatrix2x4fv} */ public static void glProgramUniformMatrix2x4fv(int program, int location, boolean transpose, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2x4fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 3, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix4x2fv ProgramUniformMatrix4x2fv} */ public static void glProgramUniformMatrix4x2fv(int program, int location, boolean transpose, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4x2fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 3, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix3x4fv ProgramUniformMatrix3x4fv} */ public static void glProgramUniformMatrix3x4fv(int program, int location, boolean transpose, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3x4fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 12, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix4x3fv ProgramUniformMatrix4x3fv} */ public static void glProgramUniformMatrix4x3fv(int program, int location, boolean transpose, float[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4x3fv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 12, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix2x3dv ProgramUniformMatrix2x3dv} */ public static void glProgramUniformMatrix2x3dv(int program, int location, boolean transpose, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2x3dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 6, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix3x2dv ProgramUniformMatrix3x2dv} */ public static void glProgramUniformMatrix3x2dv(int program, int location, boolean transpose, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3x2dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 6, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix2x4dv ProgramUniformMatrix2x4dv} */ public static void glProgramUniformMatrix2x4dv(int program, int location, boolean transpose, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix2x4dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 3, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix4x2dv ProgramUniformMatrix4x2dv} */ public static void glProgramUniformMatrix4x2dv(int program, int location, boolean transpose, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4x2dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length >> 3, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix3x4dv ProgramUniformMatrix3x4dv} */ public static void glProgramUniformMatrix3x4dv(int program, int location, boolean transpose, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix3x4dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 12, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glProgramUniform.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glProgramUniformMatrix4x3dv ProgramUniformMatrix4x3dv} */ public static void glProgramUniformMatrix4x3dv(int program, int location, boolean transpose, double[] value) { long __functionAddress = GL.getCapabilities().glProgramUniformMatrix4x3dv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, program, location, value.length / 12, transpose, value); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetProgramPipelineInfoLog.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glGetProgramPipelineInfoLog GetProgramPipelineInfoLog} */ public static void glGetProgramPipelineInfoLog(int pipeline, int[] length, ByteBuffer infoLog) { long __functionAddress = GL.getCapabilities().glGetProgramPipelineInfoLog; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBufferSafe(length, 1); } callPPV(__functionAddress, pipeline, infoLog.remaining(), length, memAddress(infoLog)); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glVertexAttribL1dv VertexAttribL1dv} */ public static void glVertexAttribL1dv(int index, double[] v) { long __functionAddress = GL.getCapabilities().glVertexAttribL1dv; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(v, 1); } callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glVertexAttribL2dv VertexAttribL2dv} */ public static void glVertexAttribL2dv(int index, double[] v) { long __functionAddress = GL.getCapabilities().glVertexAttribL2dv; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(v, 2); } callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glVertexAttribL3dv VertexAttribL3dv} */ public static void glVertexAttribL3dv(int index, double[] v) { long __functionAddress = GL.getCapabilities().glVertexAttribL3dv; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(v, 3); } callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glVertexAttribL4dv VertexAttribL4dv} */ public static void glVertexAttribL4dv(int index, double[] v) { long __functionAddress = GL.getCapabilities().glVertexAttribL4dv; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(v, 4); } callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetVertexAttrib.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glGetVertexAttribLdv GetVertexAttribLdv} */ public static void glGetVertexAttribLdv(int index, int pname, double[] params) { long __functionAddress = GL.getCapabilities().glGetVertexAttribLdv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, pname, params); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glViewportArray.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glViewportArrayv ViewportArrayv} */ public static void glViewportArrayv(int first, float[] v) { long __functionAddress = GL.getCapabilities().glViewportArrayv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, first, v.length >> 2, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glViewportIndexed.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glViewportIndexedfv ViewportIndexedfv} */ public static void glViewportIndexedfv(int index, float[] v) { long __functionAddress = GL.getCapabilities().glViewportIndexedfv; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(v, 4); } callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glScissorArray.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glScissorArrayv ScissorArrayv} */ public static void glScissorArrayv(int first, int[] v) { long __functionAddress = GL.getCapabilities().glScissorArrayv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, first, v.length >> 2, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glScissorIndexed.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glScissorIndexedv ScissorIndexedv} */ public static void glScissorIndexedv(int index, int[] v) { long __functionAddress = GL.getCapabilities().glScissorIndexedv; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(v, 4); } callPV(__functionAddress, index, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glDepthRangeArray.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glDepthRangeArrayv DepthRangeArrayv} */ public static void glDepthRangeArrayv(int first, double[] v) { long __functionAddress = GL.getCapabilities().glDepthRangeArrayv; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, first, v.length >> 1, v); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetFloati.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glGetFloati_v GetFloati_v} */ public static void glGetFloati_v(int target, int index, float[] data) { long __functionAddress = GL.getCapabilities().glGetFloati_v; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(data, 1); } callPV(__functionAddress, target, index, data); } /** * <p><a href="http://www.opengl.org/sdk/docs/man/html/glGetDoublei.xhtml">OpenGL SDK Reference</a></p> * * Array version of: {@link #glGetDoublei_v GetDoublei_v} */ public static void glGetDoublei_v(int target, int index, double[] data) { long __functionAddress = GL.getCapabilities().glGetDoublei_v; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(data, 1); } callPV(__functionAddress, target, index, data); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-connect/src/main/java/com/amazonaws/services/connect/model/ListAgentStatusesResult.java
6988
/* * Copyright 2017-2022 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.connect.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/ListAgentStatuses" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListAgentStatusesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * If there are additional results, this is the token for the next set of results. * </p> */ private String nextToken; /** * <p> * A summary of agent statuses. * </p> */ private java.util.List<AgentStatusSummary> agentStatusSummaryList; /** * <p> * If there are additional results, this is the token for the next set of results. * </p> * * @param nextToken * If there are additional results, this is the token for the next set of results. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * If there are additional results, this is the token for the next set of results. * </p> * * @return If there are additional results, this is the token for the next set of results. */ public String getNextToken() { return this.nextToken; } /** * <p> * If there are additional results, this is the token for the next set of results. * </p> * * @param nextToken * If there are additional results, this is the token for the next set of results. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAgentStatusesResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * A summary of agent statuses. * </p> * * @return A summary of agent statuses. */ public java.util.List<AgentStatusSummary> getAgentStatusSummaryList() { return agentStatusSummaryList; } /** * <p> * A summary of agent statuses. * </p> * * @param agentStatusSummaryList * A summary of agent statuses. */ public void setAgentStatusSummaryList(java.util.Collection<AgentStatusSummary> agentStatusSummaryList) { if (agentStatusSummaryList == null) { this.agentStatusSummaryList = null; return; } this.agentStatusSummaryList = new java.util.ArrayList<AgentStatusSummary>(agentStatusSummaryList); } /** * <p> * A summary of agent statuses. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setAgentStatusSummaryList(java.util.Collection)} or * {@link #withAgentStatusSummaryList(java.util.Collection)} if you want to override the existing values. * </p> * * @param agentStatusSummaryList * A summary of agent statuses. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAgentStatusesResult withAgentStatusSummaryList(AgentStatusSummary... agentStatusSummaryList) { if (this.agentStatusSummaryList == null) { setAgentStatusSummaryList(new java.util.ArrayList<AgentStatusSummary>(agentStatusSummaryList.length)); } for (AgentStatusSummary ele : agentStatusSummaryList) { this.agentStatusSummaryList.add(ele); } return this; } /** * <p> * A summary of agent statuses. * </p> * * @param agentStatusSummaryList * A summary of agent statuses. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAgentStatusesResult withAgentStatusSummaryList(java.util.Collection<AgentStatusSummary> agentStatusSummaryList) { setAgentStatusSummaryList(agentStatusSummaryList); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getAgentStatusSummaryList() != null) sb.append("AgentStatusSummaryList: ").append(getAgentStatusSummaryList()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListAgentStatusesResult == false) return false; ListAgentStatusesResult other = (ListAgentStatusesResult) obj; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getAgentStatusSummaryList() == null ^ this.getAgentStatusSummaryList() == null) return false; if (other.getAgentStatusSummaryList() != null && other.getAgentStatusSummaryList().equals(this.getAgentStatusSummaryList()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getAgentStatusSummaryList() == null) ? 0 : getAgentStatusSummaryList().hashCode()); return hashCode; } @Override public ListAgentStatusesResult clone() { try { return (ListAgentStatusesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
ishark/incubator-apex-core
engine/src/main/java/com/datatorrent/stram/StreamingContainerManager.java
132209
/** * 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.datatorrent.stram; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nullable; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.mutable.MutableInt; import org.apache.commons.lang3.mutable.MutableLong; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Options; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.SystemClock; import org.apache.hadoop.yarn.webapp.NotFoundException; import com.esotericsoftware.kryo.KryoException; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.datatorrent.api.Attribute; import com.datatorrent.api.AutoMetric; import com.datatorrent.api.Component; import com.datatorrent.api.Context; import com.datatorrent.api.Context.OperatorContext; import com.datatorrent.api.Operator; import com.datatorrent.api.Operator.InputPort; import com.datatorrent.api.Operator.OutputPort; import com.datatorrent.api.Stats.OperatorStats; import com.datatorrent.api.StatsListener; import com.datatorrent.api.StorageAgent; import com.datatorrent.api.StreamCodec; import com.datatorrent.api.StringCodec; import com.datatorrent.api.annotation.Stateless; import com.datatorrent.bufferserver.auth.AuthManager; import com.datatorrent.bufferserver.util.Codec; import com.datatorrent.common.experimental.AppData; import com.datatorrent.common.util.AsyncFSStorageAgent; import com.datatorrent.common.util.FSStorageAgent; import com.datatorrent.common.util.NumberAggregate; import com.datatorrent.common.util.Pair; import com.datatorrent.stram.Journal.Recoverable; import com.datatorrent.stram.StreamingContainerAgent.ContainerStartRequest; import com.datatorrent.stram.api.AppDataSource; import com.datatorrent.stram.api.Checkpoint; import com.datatorrent.stram.api.ContainerContext; import com.datatorrent.stram.api.OperatorDeployInfo; import com.datatorrent.stram.api.StramEvent; import com.datatorrent.stram.api.StramToNodeChangeLoggersRequest; import com.datatorrent.stram.api.StramToNodeGetPropertyRequest; import com.datatorrent.stram.api.StramToNodeSetPropertyRequest; import com.datatorrent.stram.api.StramToNodeStartRecordingRequest; import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.ContainerHeartbeat; import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse; import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.ContainerStats; import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.OperatorHeartbeat; import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.StramToNodeRequest; import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.StreamingContainerContext; import com.datatorrent.stram.engine.OperatorResponse; import com.datatorrent.stram.engine.StreamingContainer; import com.datatorrent.stram.engine.WindowGenerator; import com.datatorrent.stram.plan.logical.LogicalOperatorStatus; import com.datatorrent.stram.plan.logical.LogicalPlan; import com.datatorrent.stram.plan.logical.LogicalPlan.InputPortMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.ModuleMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.OperatorMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.OutputPortMeta; import com.datatorrent.stram.plan.logical.LogicalPlanConfiguration; import com.datatorrent.stram.plan.logical.Operators; import com.datatorrent.stram.plan.logical.Operators.PortContextPair; import com.datatorrent.stram.plan.logical.requests.LogicalPlanRequest; import com.datatorrent.stram.plan.physical.OperatorStatus; import com.datatorrent.stram.plan.physical.OperatorStatus.PortStatus; import com.datatorrent.stram.plan.physical.PTContainer; import com.datatorrent.stram.plan.physical.PTOperator; import com.datatorrent.stram.plan.physical.PTOperator.PTInput; import com.datatorrent.stram.plan.physical.PTOperator.PTOutput; import com.datatorrent.stram.plan.physical.PTOperator.State; import com.datatorrent.stram.plan.physical.PhysicalPlan; import com.datatorrent.stram.plan.physical.PhysicalPlan.PlanContext; import com.datatorrent.stram.plan.physical.PlanModifier; import com.datatorrent.stram.util.ConfigUtils; import com.datatorrent.stram.util.FSJsonLineFile; import com.datatorrent.stram.util.MovingAverage.MovingAverageLong; import com.datatorrent.stram.util.SharedPubSubWebSocketClient; import com.datatorrent.stram.util.WebServicesClient; import com.datatorrent.stram.webapp.ContainerInfo; import com.datatorrent.stram.webapp.LogicalOperatorInfo; import com.datatorrent.stram.webapp.OperatorAggregationInfo; import com.datatorrent.stram.webapp.OperatorInfo; import com.datatorrent.stram.webapp.PortInfo; import com.datatorrent.stram.webapp.StreamInfo; import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.bus.config.BusConfiguration; /** * Tracks topology provisioning/allocation to containers<p> * <br> * The tasks include<br> * Provisioning operators one container at a time. Each container gets assigned the operators, streams and its context<br> * Monitors run time operations including heartbeat protocol and node status<br> * Operator recovery and restart<br> * <br> * * @since 0.3.2 */ public class StreamingContainerManager implements PlanContext { private static final Logger LOG = LoggerFactory.getLogger(StreamingContainerManager.class); public static final String GATEWAY_LOGIN_URL_PATH = "/ws/v2/login"; public static final String BUILTIN_APPDATA_URL = "builtin"; public static final String CONTAINERS_INFO_FILENAME_FORMAT = "containers_%d.json"; public static final String OPERATORS_INFO_FILENAME_FORMAT = "operators_%d.json"; public static final String APP_META_FILENAME = "meta.json"; public static final String APP_META_KEY_ATTRIBUTES = "attributes"; public static final String APP_META_KEY_METRICS = "metrics"; public static final String EMBEDDABLE_QUERY_NAME_SUFFIX = ".query"; public static final Recoverable SET_OPERATOR_PROPERTY = new SetOperatorProperty(); public static final Recoverable SET_PHYSICAL_OPERATOR_PROPERTY = new SetPhysicalOperatorProperty(); public static final int METRIC_QUEUE_SIZE = 1000; private final FinalVars vars; private final PhysicalPlan plan; private final Clock clock; private SharedPubSubWebSocketClient wsClient; private FSStatsRecorder statsRecorder; private FSEventRecorder eventRecorder; protected final Map<String, String> containerStopRequests = new ConcurrentHashMap<>(); protected final ConcurrentLinkedQueue<ContainerStartRequest> containerStartRequests = new ConcurrentLinkedQueue<>(); protected boolean forcedShutdown = false; private final ConcurrentLinkedQueue<Runnable> eventQueue = new ConcurrentLinkedQueue<>(); private final AtomicBoolean eventQueueProcessing = new AtomicBoolean(); private final HashSet<PTContainer> pendingAllocation = Sets.newLinkedHashSet(); protected String shutdownDiagnosticsMessage = ""; private long lastResourceRequest = 0; private final Map<String, StreamingContainerAgent> containers = new ConcurrentHashMap<>(); private final List<Pair<PTOperator, Long>> purgeCheckpoints = new ArrayList<>(); private Map<OperatorMeta, Set<OperatorMeta>> checkpointGroups; private final Map<Long, Set<PTOperator>> shutdownOperators = new HashMap<>(); private CriticalPathInfo criticalPathInfo; private final ConcurrentMap<PTOperator, PTOperator> reportStats = new ConcurrentHashMap<>(); private final AtomicBoolean deployChangeInProgress = new AtomicBoolean(); private int deployChangeCnt; private MBassador<StramEvent> eventBus; // event bus for publishing stram events private final Journal journal; private RecoveryHandler recoveryHandler; // window id to node id to end window stats private final ConcurrentSkipListMap<Long, Map<Integer, EndWindowStats>> endWindowStatsOperatorMap = new ConcurrentSkipListMap<>(); private final ConcurrentMap<PTOperator, PTOperator> slowestUpstreamOp = new ConcurrentHashMap<>(); private long committedWindowId; // (operator id, port name) to timestamp private final Map<Pair<Integer, String>, Long> operatorPortLastEndWindowTimestamps = Maps.newConcurrentMap(); private final Map<Integer, Long> operatorLastEndWindowTimestamps = Maps.newConcurrentMap(); private long lastStatsTimestamp = System.currentTimeMillis(); private long currentEndWindowStatsWindowId; private long completeEndWindowStatsWindowId; private final ConcurrentHashMap<String, MovingAverageLong> rpcLatencies = new ConcurrentHashMap<>(); private final AtomicLong nodeToStramRequestIds = new AtomicLong(1); private int allocatedMemoryMB = 0; private List<AppDataSource> appDataSources = null; private final Cache<Long, Object> commandResponse = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build(); private transient ExecutorService poolExecutor; private FileContext fileContext; //logic operator name to a queue of logical metrics. this gets cleared periodically private final Map<String, Queue<Pair<Long, Map<String, Object>>>> logicalMetrics = Maps.newConcurrentMap(); //logical operator name to latest logical metrics. private final Map<String, Map<String, Object>> latestLogicalMetrics = Maps.newHashMap(); //logical operator name to latest counters. exists for backward compatibility. private final Map<String, Object> latestLogicalCounters = Maps.newHashMap(); private final LinkedHashMap<String, ContainerInfo> completedContainers = new LinkedHashMap<String, ContainerInfo>() { private static final long serialVersionUID = 201405281500L; @Override protected boolean removeEldestEntry(Map.Entry<String, ContainerInfo> eldest) { long expireTime = System.currentTimeMillis() - 30 * 60 * 60; Iterator<Map.Entry<String, ContainerInfo>> iterator = entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, ContainerInfo> entry = iterator.next(); if (entry.getValue().finishedTime < expireTime) { iterator.remove(); } } return false; } }; private FSJsonLineFile containerFile; private FSJsonLineFile operatorFile; private final long startTime = System.currentTimeMillis(); private static class EndWindowStats { long emitTimestamp = -1; HashMap<String, Long> dequeueTimestamps = new HashMap<>(); // input port name to end window dequeue time Object counters; Map<String, Object> metrics; } public static class CriticalPathInfo { long latency; final LinkedList<Integer> path; public CriticalPathInfo() { this.path = new LinkedList<>(); } private CriticalPathInfo(long latency, LinkedList<Integer> path) { this.latency = latency; this.path = path; } @Override protected Object clone() throws CloneNotSupportedException { return new CriticalPathInfo(this.latency, (LinkedList<Integer>)this.path.clone()); } } private static class SetOperatorProperty implements Recoverable { private final String operatorName; private final String propertyName; private final String propertyValue; private SetOperatorProperty() { this(null, null, null); } private SetOperatorProperty(String operatorName, String propertyName, String propertyValue) { this.operatorName = operatorName; this.propertyName = propertyName; this.propertyValue = propertyValue; } @Override public void read(final Object object, final Input in) throws KryoException { final StreamingContainerManager scm = (StreamingContainerManager)object; final String operatorName = in.readString(); final String propertyName = in.readString(); final String propertyValue = in.readString(); final OperatorMeta logicalOperator = scm.plan.getLogicalPlan().getOperatorMeta(operatorName); if (logicalOperator == null) { throw new IllegalArgumentException("Unknown operator " + operatorName); } scm.setOperatorProperty(logicalOperator, propertyName, propertyValue); } @Override public void write(final Output out) throws KryoException { out.writeString(operatorName); out.writeString(propertyName); out.writeString(propertyValue); } } private static class SetPhysicalOperatorProperty implements Recoverable { private final int operatorId; private final String propertyName; private final String propertyValue; private SetPhysicalOperatorProperty() { this(-1, null, null); } private SetPhysicalOperatorProperty(int operatorId, String propertyName, String propertyValue) { this.operatorId = operatorId; this.propertyName = propertyName; this.propertyValue = propertyValue; } @Override public void read(final Object object, final Input in) throws KryoException { final StreamingContainerManager scm = (StreamingContainerManager)object; final int operatorId = in.readInt(); final String propertyName = in.readString(); final String propertyValue = in.readString(); final PTOperator o = scm.plan.getAllOperators().get(operatorId); if (o == null) { throw new IllegalArgumentException("Unknown physical operator " + operatorId); } scm.setPhysicalOperatorProperty(o, propertyName, propertyValue); } @Override public void write(final Output out) throws KryoException { out.writeInt(operatorId); out.writeString(propertyName); out.writeString(propertyValue); } } public StreamingContainerManager(LogicalPlan dag, Clock clock) { this(dag, false, clock); } public StreamingContainerManager(LogicalPlan dag) { this(dag, false, new SystemClock()); } public StreamingContainerManager(LogicalPlan dag, boolean enableEventRecording, Clock clock) { this.clock = clock; this.vars = new FinalVars(dag, clock.getTime()); poolExecutor = Executors.newFixedThreadPool(4); // setup prior to plan creation for event recording if (enableEventRecording) { this.eventBus = new MBassador<>(BusConfiguration.Default(1, 1, 1)); } this.plan = new PhysicalPlan(dag, this); this.journal = new Journal(this); init(enableEventRecording); } private StreamingContainerManager(CheckpointState checkpointedState, boolean enableEventRecording) { this.vars = checkpointedState.finals; this.clock = new SystemClock(); poolExecutor = Executors.newFixedThreadPool(4); this.plan = checkpointedState.physicalPlan; this.eventBus = new MBassador<>(BusConfiguration.Default(1, 1, 1)); this.journal = new Journal(this); init(enableEventRecording); } private void init(boolean enableEventRecording) { setupWsClient(); setupRecording(enableEventRecording); setupStringCodecs(); try { Path file = new Path(this.vars.appPath); URI uri = file.toUri(); Configuration config = new YarnConfiguration(); fileContext = uri.getScheme() == null ? FileContext.getFileContext(config) : FileContext.getFileContext(uri, config); saveMetaInfo(); String fileName = String.format(CONTAINERS_INFO_FILENAME_FORMAT, plan.getLogicalPlan().getValue(LogicalPlan.APPLICATION_ATTEMPT_ID)); this.containerFile = new FSJsonLineFile(fileContext, new Path(this.vars.appPath, fileName), FsPermission.getDefault()); this.containerFile.append(getAppMasterContainerInfo()); fileName = String.format(OPERATORS_INFO_FILENAME_FORMAT, plan.getLogicalPlan().getValue(LogicalPlan.APPLICATION_ATTEMPT_ID)); this.operatorFile = new FSJsonLineFile(fileContext, new Path(this.vars.appPath, fileName), FsPermission.getDefault()); } catch (IOException ex) { throw Throwables.propagate(ex); } } public Journal getJournal() { return journal; } public final ContainerInfo getAppMasterContainerInfo() { ContainerInfo ci = new ContainerInfo(); ci.id = System.getenv(ApplicationConstants.Environment.CONTAINER_ID.toString()); String nmHost = System.getenv(ApplicationConstants.Environment.NM_HOST.toString()); String nmPort = System.getenv(ApplicationConstants.Environment.NM_PORT.toString()); String nmHttpPort = System.getenv(ApplicationConstants.Environment.NM_HTTP_PORT.toString()); ci.state = "ACTIVE"; ci.jvmName = ManagementFactory.getRuntimeMXBean().getName(); ci.numOperators = 0; YarnConfiguration conf = new YarnConfiguration(); if (nmHost != null) { if (nmPort != null) { ci.host = nmHost + ":" + nmPort; } if (nmHttpPort != null) { String nodeHttpAddress = nmHost + ":" + nmHttpPort; if (allocatedMemoryMB == 0) { String url = ConfigUtils.getSchemePrefix(conf) + nodeHttpAddress + "/ws/v1/node/containers/" + ci.id; WebServicesClient webServicesClient = new WebServicesClient(); try { String content = webServicesClient.process(url, String.class, new WebServicesClient.GetWebServicesHandler<String>()); JSONObject json = new JSONObject(content); int totalMemoryNeededMB = json.getJSONObject("container").getInt("totalMemoryNeededMB"); if (totalMemoryNeededMB > 0) { allocatedMemoryMB = totalMemoryNeededMB; } else { LOG.warn("Could not determine the memory allocated for the streaming application master. Node manager is reporting {} MB from {}", totalMemoryNeededMB, url); } } catch (Exception ex) { LOG.warn("Could not determine the memory allocated for the streaming application master", ex); } } ci.containerLogsUrl = ConfigUtils.getSchemePrefix(conf) + nodeHttpAddress + "/node/containerlogs/" + ci.id + "/" + System.getenv(ApplicationConstants.Environment.USER.toString()); ci.rawContainerLogsUrl = ConfigUtils.getRawContainerLogsUrl(conf, nodeHttpAddress, plan.getLogicalPlan().getAttributes().get(LogicalPlan.APPLICATION_ID), ci.id); } } ci.memoryMBAllocated = allocatedMemoryMB; ci.memoryMBFree = ((int)(Runtime.getRuntime().freeMemory() / (1024 * 1024))); ci.lastHeartbeat = -1; ci.startedTime = startTime; ci.finishedTime = -1; return ci; } public void updateRPCLatency(String containerId, long latency) { if (vars.rpcLatencyCompensationSamples > 0) { MovingAverageLong latencyMA = rpcLatencies.get(containerId); if (latencyMA == null) { final MovingAverageLong val = new MovingAverageLong(vars.rpcLatencyCompensationSamples); latencyMA = rpcLatencies.putIfAbsent(containerId, val); if (latencyMA == null) { latencyMA = val; } } latencyMA.add(latency); } } private void setupRecording(boolean enableEventRecording) { if (this.vars.enableStatsRecording) { statsRecorder = new FSStatsRecorder(); statsRecorder.setBasePath(this.vars.appPath + "/" + LogicalPlan.SUBDIR_STATS); statsRecorder.setup(); } if (enableEventRecording) { eventRecorder = new FSEventRecorder(plan.getLogicalPlan().getValue(LogicalPlan.APPLICATION_ID)); eventRecorder.setBasePath(this.vars.appPath + "/" + LogicalPlan.SUBDIR_EVENTS); eventRecorder.setWebSocketClient(wsClient); eventRecorder.setup(); eventBus.subscribe(eventRecorder); } } private void setupStringCodecs() { Map<Class<?>, Class<? extends StringCodec<?>>> codecs = this.plan.getLogicalPlan().getAttributes().get(Context.DAGContext.STRING_CODECS); StringCodecs.loadConverters(codecs); } private void setupWsClient() { String gatewayAddress = plan.getLogicalPlan().getValue(LogicalPlan.GATEWAY_CONNECT_ADDRESS); boolean gatewayUseSsl = plan.getLogicalPlan().getValue(LogicalPlan.GATEWAY_USE_SSL); String gatewayUserName = plan.getLogicalPlan().getValue(LogicalPlan.GATEWAY_USER_NAME); String gatewayPassword = plan.getLogicalPlan().getValue(LogicalPlan.GATEWAY_PASSWORD); int timeout = plan.getLogicalPlan().getValue(LogicalPlan.PUBSUB_CONNECT_TIMEOUT_MILLIS); if (gatewayAddress != null) { try { wsClient = new SharedPubSubWebSocketClient((gatewayUseSsl ? "wss://" : "ws://") + gatewayAddress + "/pubsub", timeout); if (gatewayUserName != null && gatewayPassword != null) { wsClient.setLoginUrl((gatewayUseSsl ? "https://" : "http://") + gatewayAddress + GATEWAY_LOGIN_URL_PATH); wsClient.setUserName(gatewayUserName); wsClient.setPassword(gatewayPassword); } wsClient.setup(); } catch (Exception ex) { LOG.warn("Cannot establish websocket connection to {}", gatewayAddress, ex); } } } public void teardown() { if (eventBus != null) { eventBus.shutdown(); } if (eventRecorder != null) { eventRecorder.teardown(); } if (statsRecorder != null) { statsRecorder.teardown(); } IOUtils.closeQuietly(containerFile); IOUtils.closeQuietly(operatorFile); if (poolExecutor != null) { poolExecutor.shutdown(); } } public void subscribeToEvents(Object listener) { if (eventBus != null) { eventBus.subscribe(listener); } } public PhysicalPlan getPhysicalPlan() { return plan; } public long getCommittedWindowId() { return committedWindowId; } public boolean isGatewayConnected() { return wsClient != null && wsClient.isConnectionOpen(); } public SharedPubSubWebSocketClient getWsClient() { return wsClient; } private String convertAppDataUrl(String url) { if (BUILTIN_APPDATA_URL.equals(url)) { return url; } /*else if (url != null) { String messageProxyUrl = this.plan.getLogicalPlan().getAttributes().get(Context.DAGContext.APPLICATION_DATA_MESSAGE_PROXY_URL); if (messageProxyUrl != null) { StringBuilder convertedUrl = new StringBuilder(messageProxyUrl); convertedUrl.append("?url="); try { convertedUrl.append(URLEncoder.encode(url, "UTF-8")); return convertedUrl.toString(); } catch (UnsupportedEncodingException ex) { LOG.warn("URL {} cannot be encoded", url); } } } */ LOG.warn("App Data URL {} cannot be converted for the client.", url); return url; } private final Object appDataSourcesLock = new Object(); public List<AppDataSource> getAppDataSources() { synchronized (appDataSourcesLock) { if (appDataSources == null) { appDataSources = new ArrayList<>(); operators: for (LogicalPlan.OperatorMeta operatorMeta : plan.getLogicalPlan().getAllOperators()) { Map<LogicalPlan.InputPortMeta, LogicalPlan.StreamMeta> inputStreams = operatorMeta.getInputStreams(); Map<LogicalPlan.OutputPortMeta, LogicalPlan.StreamMeta> outputStreams = operatorMeta.getOutputStreams(); String queryOperatorName = null; String queryUrl = null; String queryTopic = null; boolean hasEmbeddedQuery = false; //Discover embeddable query connectors if (operatorMeta.getOperator() instanceof AppData.Store<?>) { AppData.Store<?> store = (AppData.Store<?>)operatorMeta.getOperator(); AppData.EmbeddableQueryInfoProvider<?> embeddableQuery = store.getEmbeddableQueryInfoProvider(); if (embeddableQuery != null) { hasEmbeddedQuery = true; queryOperatorName = operatorMeta.getName() + EMBEDDABLE_QUERY_NAME_SUFFIX; queryUrl = embeddableQuery.getAppDataURL(); queryTopic = embeddableQuery.getTopic(); } } //Discover separate query operators LOG.debug("Looking at operator {} {}", operatorMeta.getName(), Thread.currentThread().getId()); for (Map.Entry<LogicalPlan.InputPortMeta, LogicalPlan.StreamMeta> entry : inputStreams.entrySet()) { LogicalPlan.InputPortMeta portMeta = entry.getKey(); if (portMeta.isAppDataQueryPort()) { if (queryUrl == null) { OperatorMeta queryOperatorMeta = entry.getValue().getSource().getOperatorMeta(); if (queryOperatorMeta.getOperator() instanceof AppData.ConnectionInfoProvider) { if (!hasEmbeddedQuery) { AppData.ConnectionInfoProvider queryOperator = (AppData.ConnectionInfoProvider)queryOperatorMeta.getOperator(); queryOperatorName = queryOperatorMeta.getName(); queryUrl = queryOperator.getAppDataURL(); queryTopic = queryOperator.getTopic(); } else { LOG.warn("An embeddable query connector and the {} query operator were discovered. The query operator will be ignored and the embeddable query connector will be used instead.", operatorMeta.getName()); } } } else { LOG.warn("Multiple query ports found in operator {}. Ignoring the App Data Source.", operatorMeta.getName()); continue operators; } } } for (Map.Entry<LogicalPlan.OutputPortMeta, LogicalPlan.StreamMeta> entry : outputStreams.entrySet()) { LogicalPlan.OutputPortMeta portMeta = entry.getKey(); LOG.debug("Looking at port {} {}", portMeta.getPortName(), Thread.currentThread().getId()); if (portMeta.isAppDataResultPort()) { AppDataSource appDataSource = new AppDataSource(); appDataSource.setType(AppDataSource.Type.DAG); appDataSource.setOperatorName(operatorMeta.getName()); appDataSource.setPortName(portMeta.getPortName()); if (queryOperatorName == null) { LOG.warn("There is no query operator for the App Data Source {}.{}. Ignoring the App Data Source.", operatorMeta.getName(), portMeta.getPortName()); continue; } appDataSource.setQueryOperatorName(queryOperatorName); appDataSource.setQueryTopic(queryTopic); appDataSource.setQueryUrl(convertAppDataUrl(queryUrl)); List<LogicalPlan.InputPortMeta> sinks = entry.getValue().getSinks(); if (sinks.isEmpty()) { LOG.warn("There is no result operator for the App Data Source {}.{}. Ignoring the App Data Source.", operatorMeta.getName(), portMeta.getPortName()); continue; } if (sinks.size() > 1) { LOG.warn("There are multiple result operators for the App Data Source {}.{}. Ignoring the App Data Source.", operatorMeta.getName(), portMeta.getPortName()); continue; } OperatorMeta resultOperatorMeta = sinks.get(0).getOperatorWrapper(); if (resultOperatorMeta.getOperator() instanceof AppData.ConnectionInfoProvider) { AppData.ConnectionInfoProvider resultOperator = (AppData.ConnectionInfoProvider)resultOperatorMeta.getOperator(); appDataSource.setResultOperatorName(resultOperatorMeta.getName()); appDataSource.setResultTopic(resultOperator.getTopic()); appDataSource.setResultUrl(convertAppDataUrl(resultOperator.getAppDataURL())); AppData.AppendQueryIdToTopic queryIdAppended = resultOperator.getClass().getAnnotation(AppData.AppendQueryIdToTopic.class); if (queryIdAppended != null && queryIdAppended.value()) { appDataSource.setResultAppendQIDTopic(true); } } else { LOG.warn("Result operator for the App Data Source {}.{} does not implement the right interface. Ignoring the App Data Source.", operatorMeta.getName(), portMeta.getPortName()); continue; } LOG.debug("Adding appDataSource {} {}", appDataSource.getName(), Thread.currentThread().getId()); appDataSources.add(appDataSource); } } } } } return appDataSources; } public Map<String, Map<String, Object>> getLatestLogicalMetrics() { return latestLogicalMetrics; } /** * Check periodically that deployed containers phone home. * Run from the master main loop (single threaded access). */ public void monitorHeartbeat() { long currentTms = clock.getTime(); // look for resource allocation timeout if (!pendingAllocation.isEmpty()) { // look for resource allocation timeout if (lastResourceRequest + plan.getLogicalPlan().getValue(LogicalPlan.RESOURCE_ALLOCATION_TIMEOUT_MILLIS) < currentTms) { String msg = String.format("Shutdown due to resource allocation timeout (%s ms) waiting for %s containers", currentTms - lastResourceRequest, pendingAllocation.size()); LOG.warn(msg); for (PTContainer c : pendingAllocation) { LOG.warn("Waiting for resource: {}m priority: {} {}", c.getRequiredMemoryMB(), c.getResourceRequestPriority(), c); } shutdownAllContainers(msg); this.forcedShutdown = true; } else { for (PTContainer c : pendingAllocation) { LOG.debug("Waiting for resource: {}m {}", c.getRequiredMemoryMB(), c); } } } // monitor currently deployed containers for (StreamingContainerAgent sca : containers.values()) { PTContainer c = sca.container; if (!pendingAllocation.contains(c) && c.getExternalId() != null) { if (sca.lastHeartbeatMillis == 0) { //LOG.debug("{} {} {}", c.getExternalId(), currentTms - sca.createdMillis, this.vars.heartbeatTimeoutMillis); // container allocated but process was either not launched or is not able to phone home if (currentTms - sca.createdMillis > 2 * this.vars.heartbeatTimeoutMillis) { LOG.info("Container {}@{} startup timeout ({} ms).", c.getExternalId(), c.host, currentTms - sca.createdMillis); containerStopRequests.put(c.getExternalId(), c.getExternalId()); } } else { if (currentTms - sca.lastHeartbeatMillis > this.vars.heartbeatTimeoutMillis) { if (!isApplicationIdle()) { // request stop (kill) as process may still be hanging around (would have been detected by Yarn otherwise) LOG.info("Container {}@{} heartbeat timeout ({} ms).", c.getExternalId(), c.host, currentTms - sca.lastHeartbeatMillis); containerStopRequests.put(c.getExternalId(), c.getExternalId()); } } } } } // events that may modify the plan processEvents(); committedWindowId = updateCheckpoints(false); calculateEndWindowStats(); if (this.vars.enableStatsRecording) { recordStats(currentTms); } } private void recordStats(long currentTms) { try { statsRecorder.recordContainers(containers, currentTms); statsRecorder.recordOperators(getOperatorInfoList(), currentTms); } catch (Exception ex) { LOG.warn("Exception caught when recording stats", ex); } } private void calculateEndWindowStats() { if (!endWindowStatsOperatorMap.isEmpty()) { Set<Integer> allCurrentOperators = plan.getAllOperators().keySet(); if (endWindowStatsOperatorMap.size() > this.vars.maxWindowsBehindForStats) { LOG.warn("Some operators are behind for more than {} windows! Trimming the end window stats map", this.vars.maxWindowsBehindForStats); while (endWindowStatsOperatorMap.size() > this.vars.maxWindowsBehindForStats) { LOG.debug("Removing incomplete end window stats for window id {}. Collected operator set: {}. Complete set: {}", endWindowStatsOperatorMap.firstKey(), endWindowStatsOperatorMap.get(endWindowStatsOperatorMap.firstKey()).keySet(), allCurrentOperators); endWindowStatsOperatorMap.remove(endWindowStatsOperatorMap.firstKey()); } } //logicalMetrics.clear(); int numOperators = allCurrentOperators.size(); Long windowId = endWindowStatsOperatorMap.firstKey(); while (windowId != null) { Map<Integer, EndWindowStats> endWindowStatsMap = endWindowStatsOperatorMap.get(windowId); Set<Integer> endWindowStatsOperators = endWindowStatsMap.keySet(); aggregateMetrics(windowId, endWindowStatsMap); criticalPathInfo = findCriticalPath(); if (allCurrentOperators.containsAll(endWindowStatsOperators)) { if (endWindowStatsMap.size() < numOperators) { if (windowId < completeEndWindowStatsWindowId) { LOG.debug("Disregarding stale end window stats for window {}", windowId); endWindowStatsOperatorMap.remove(windowId); } else { break; } } else { endWindowStatsOperatorMap.remove(windowId); currentEndWindowStatsWindowId = windowId; } } else { // the old stats contains operators that do not exist any more // this is probably right after a partition happens. LOG.debug("Stats for non-existent operators detected. Disregarding end window stats for window {}", windowId); endWindowStatsOperatorMap.remove(windowId); } windowId = endWindowStatsOperatorMap.higherKey(windowId); } } } private void aggregateMetrics(long windowId, Map<Integer, EndWindowStats> endWindowStatsMap) { Collection<OperatorMeta> logicalOperators = getLogicalPlan().getAllOperators(); //for backward compatibility for (OperatorMeta operatorMeta : logicalOperators) { @SuppressWarnings("deprecation") Context.CountersAggregator aggregator = operatorMeta.getValue(OperatorContext.COUNTERS_AGGREGATOR); if (aggregator == null) { continue; } Collection<PTOperator> physicalOperators = plan.getAllOperators(operatorMeta); List<Object> counters = Lists.newArrayList(); for (PTOperator operator : physicalOperators) { EndWindowStats stats = endWindowStatsMap.get(operator.getId()); if (stats != null && stats.counters != null) { counters.add(stats.counters); } } if (counters.size() > 0) { @SuppressWarnings("deprecation") Object aggregate = aggregator.aggregate(counters); latestLogicalCounters.put(operatorMeta.getName(), aggregate); } } for (OperatorMeta operatorMeta : logicalOperators) { AutoMetric.Aggregator aggregator = operatorMeta.getMetricAggregatorMeta() != null ? operatorMeta.getMetricAggregatorMeta().getAggregator() : null; if (aggregator == null) { continue; } Collection<PTOperator> physicalOperators = plan.getAllOperators(operatorMeta); List<AutoMetric.PhysicalMetricsContext> metricPool = Lists.newArrayList(); for (PTOperator operator : physicalOperators) { EndWindowStats stats = endWindowStatsMap.get(operator.getId()); if (stats != null && stats.metrics != null) { PhysicalMetricsContextImpl physicalMetrics = new PhysicalMetricsContextImpl(operator.getId(), stats.metrics); metricPool.add(physicalMetrics); } } if (metricPool.isEmpty()) { //nothing to aggregate continue; } Map<String, Object> lm = aggregator.aggregate(windowId, metricPool); if (lm != null && lm.size() > 0) { Queue<Pair<Long, Map<String, Object>>> windowMetrics = logicalMetrics.get(operatorMeta.getName()); if (windowMetrics == null) { windowMetrics = new LinkedBlockingQueue<Pair<Long, Map<String, Object>>>(METRIC_QUEUE_SIZE) { private static final long serialVersionUID = 1L; @Override public boolean add(Pair<Long, Map<String, Object>> longMapPair) { if (remainingCapacity() <= 1) { remove(); } return super.add(longMapPair); } }; logicalMetrics.put(operatorMeta.getName(), windowMetrics); } LOG.debug("Adding to logical metrics for {}", operatorMeta.getName()); windowMetrics.add(new Pair<>(windowId, lm)); Map<String, Object> oldValue = latestLogicalMetrics.put(operatorMeta.getName(), lm); if (oldValue == null) { try { saveMetaInfo(); } catch (IOException ex) { LOG.error("Cannot save application meta info to DFS. App data sources will not be available.", ex); } } } } } /** * This method is for saving meta information about this application in HDFS -- the meta information that generally * does not change across multiple attempts */ private void saveMetaInfo() throws IOException { Path file = new Path(this.vars.appPath, APP_META_FILENAME + "." + System.nanoTime()); try (FSDataOutputStream os = fileContext.create(file, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), Options.CreateOpts.CreateParent.createParent())) { JSONObject top = new JSONObject(); JSONObject attributes = new JSONObject(); for (Map.Entry<Attribute<?>, Object> entry : this.plan.getLogicalPlan().getAttributes().entrySet()) { attributes.put(entry.getKey().getSimpleName(), entry.getValue()); } JSONObject autoMetrics = new JSONObject(); for (Map.Entry<String, Map<String, Object>> entry : latestLogicalMetrics.entrySet()) { autoMetrics.put(entry.getKey(), new JSONArray(entry.getValue().keySet())); } top.put(APP_META_KEY_ATTRIBUTES, attributes); top.put(APP_META_KEY_METRICS, autoMetrics); os.write(top.toString().getBytes()); } catch (JSONException ex) { throw new RuntimeException(ex); } Path origPath = new Path(this.vars.appPath, APP_META_FILENAME); fileContext.rename(file, origPath, Options.Rename.OVERWRITE); } public Queue<Pair<Long, Map<String, Object>>> getWindowMetrics(String operatorName) { return logicalMetrics.get(operatorName); } private CriticalPathInfo findCriticalPath() { CriticalPathInfo result = null; List<PTOperator> leafOperators = plan.getLeafOperators(); Map<PTOperator, CriticalPathInfo> cache = new HashMap<>(); for (PTOperator leafOperator : leafOperators) { CriticalPathInfo cpi = findCriticalPathHelper(leafOperator, cache); if (result == null || result.latency < cpi.latency) { result = cpi; } } return result; } private CriticalPathInfo findCriticalPathHelper(PTOperator operator, Map<PTOperator, CriticalPathInfo> cache) { CriticalPathInfo cpi = cache.get(operator); if (cpi != null) { return cpi; } PTOperator slowestUpstreamOperator = slowestUpstreamOp.get(operator); if (slowestUpstreamOperator != null) { cpi = findCriticalPathHelper(slowestUpstreamOperator, cache); try { cpi = (CriticalPathInfo)cpi.clone(); } catch (CloneNotSupportedException ex) { throw new RuntimeException(); } } else { cpi = new CriticalPathInfo(); } cpi.latency += operator.stats.getLatencyMA(); cpi.path.addLast(operator.getId()); cache.put(operator, cpi); return cpi; } public int processEvents() { for (PTOperator o : reportStats.keySet()) { List<OperatorStats> stats = o.stats.listenerStats.poll(); if (stats != null) { // append into single list List<OperatorStats> moreStats; while ((moreStats = o.stats.listenerStats.poll()) != null) { stats.addAll(moreStats); } } o.stats.lastWindowedStats = stats; o.stats.operatorResponses = null; if (!o.stats.responses.isEmpty()) { o.stats.operatorResponses = new ArrayList<>(); StatsListener.OperatorResponse operatorResponse; while ((operatorResponse = o.stats.responses.poll()) != null) { o.stats.operatorResponses.add(operatorResponse); } } if (o.stats.lastWindowedStats != null) { // call listeners only with non empty window list if (o.statsListeners != null) { plan.onStatusUpdate(o); } } reportStats.remove(o); } if (!this.shutdownOperators.isEmpty()) { synchronized (this.shutdownOperators) { Iterator<Map.Entry<Long, Set<PTOperator>>> it = shutdownOperators.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Long, Set<PTOperator>> windowAndOpers = it.next(); if (windowAndOpers.getKey().longValue() <= this.committedWindowId || checkDownStreamOperators(windowAndOpers)) { LOG.info("Removing inactive operators at window {} {}", Codec.getStringWindowId(windowAndOpers.getKey()), windowAndOpers.getValue()); for (PTOperator oper : windowAndOpers.getValue()) { plan.removeTerminatedPartition(oper); } it.remove(); } } } } if (!eventQueue.isEmpty()) { for (PTOperator oper : plan.getAllOperators().values()) { if (oper.getState() != PTOperator.State.ACTIVE) { LOG.debug("Skipping plan updates due to inactive operator {} {}", oper, oper.getState()); return 0; } } } int count = 0; Runnable command; while ((command = this.eventQueue.poll()) != null) { eventQueueProcessing.set(true); try { command.run(); count++; } catch (Exception e) { // TODO: handle error LOG.error("Failed to execute {}", command, e); } eventQueueProcessing.set(false); } if (count > 0) { try { checkpoint(); } catch (Exception e) { throw new RuntimeException("Failed to checkpoint state.", e); } } return count; } private boolean checkDownStreamOperators(Map.Entry<Long, Set<PTOperator>> windowAndOpers) { // Check if all downStream operators are at higher window Ids, then operator can be removed from dag Set<PTOperator> downStreamOperators = getPhysicalPlan().getDependents(windowAndOpers.getValue()); for (PTOperator oper : downStreamOperators) { long windowId = oper.stats.currentWindowId.get(); if (windowId < windowAndOpers.getKey().longValue()) { return false; } } return true; } /** * Schedule container restart. Called by Stram after a container was terminated * and requires recovery (killed externally, or after heartbeat timeout). <br> * Recovery will resolve affected operators (within the container and * everything downstream with respective recovery checkpoint states). * Dependent operators will be undeployed and buffer server connections reset prior to * redeploy to recovery checkpoint. * * @param containerId */ public void scheduleContainerRestart(String containerId) { StreamingContainerAgent cs = this.getContainerAgent(containerId); if (cs == null || cs.shutdownRequested) { // the container is no longer used / was released by us return; } LOG.info("Initiating recovery for {}@{}", containerId, cs.container.host); cs.container.setState(PTContainer.State.KILLED); cs.container.bufferServerAddress = null; cs.container.setResourceRequestPriority(-1); cs.container.setAllocatedMemoryMB(0); cs.container.setAllocatedVCores(0); // resolve dependencies UpdateCheckpointsContext ctx = new UpdateCheckpointsContext(clock, false, getCheckpointGroups()); for (PTOperator oper : cs.container.getOperators()) { updateRecoveryCheckpoints(oper, ctx); } includeLocalUpstreamOperators(ctx); // redeploy cycle for all affected operators LOG.info("Affected operators {}", ctx.visited); deploy(Collections.<PTContainer>emptySet(), ctx.visited, Sets.newHashSet(cs.container), ctx.visited); } /** * Transitively add operators that are container local to the dependency set. * (All downstream operators were traversed during checkpoint update.) * * @param ctx */ private void includeLocalUpstreamOperators(UpdateCheckpointsContext ctx) { Set<PTOperator> newOperators = Sets.newHashSet(); // repeat until no more local upstream operators are found do { newOperators.clear(); for (PTOperator oper : ctx.visited) { for (PTInput input : oper.getInputs()) { if (input.source.source.getContainer() == oper.getContainer()) { if (!ctx.visited.contains(input.source.source)) { newOperators.add(input.source.source); } } } } if (!newOperators.isEmpty()) { for (PTOperator oper : newOperators) { updateRecoveryCheckpoints(oper, ctx); } } } while (!newOperators.isEmpty()); } public void removeContainerAgent(String containerId) { LOG.debug("Removing container agent {}", containerId); StreamingContainerAgent containerAgent = containers.remove(containerId); if (containerAgent != null) { // record operator stop for this container for (PTOperator oper : containerAgent.container.getOperators()) { StramEvent ev = new StramEvent.StopOperatorEvent(oper.getName(), oper.getId(), containerId); recordEventAsync(ev); } containerAgent.container.setFinishedTime(System.currentTimeMillis()); containerAgent.container.setState(PTContainer.State.KILLED); completedContainers.put(containerId, containerAgent.getContainerInfo()); } } public Collection<ContainerInfo> getCompletedContainerInfo() { return Collections.unmodifiableCollection(completedContainers.values()); } public static class ContainerResource { public final String containerId; public final String host; public final int memoryMB; public final int vCores; public final int priority; public final String nodeHttpAddress; public ContainerResource(int priority, String containerId, String host, int memoryMB, int vCores, String nodeHttpAddress) { this.containerId = containerId; this.host = host; this.memoryMB = memoryMB; this.vCores = vCores; this.priority = priority; this.nodeHttpAddress = nodeHttpAddress; } /** * @return String */ @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("containerId", this.containerId) .append("host", this.host) .append("memoryMB", this.memoryMB) .toString(); } } /** * Assign operators to allocated container resource. * * @param resource * @param bufferServerAddr * @return streaming container agent */ public StreamingContainerAgent assignContainer(ContainerResource resource, InetSocketAddress bufferServerAddr) { PTContainer container = null; // match container waiting for resource for (PTContainer c : pendingAllocation) { if (c.getState() == PTContainer.State.NEW || c.getState() == PTContainer.State.KILLED) { if (c.getResourceRequestPriority() == resource.priority) { container = c; break; } } } if (container == null) { LOG.debug("No container matching allocated resource {}", resource); LOG.debug("Containers waiting for allocation {}", pendingAllocation); return null; } pendingAllocation.remove(container); container.setState(PTContainer.State.ALLOCATED); if (container.getExternalId() != null) { LOG.info("Removing container agent {}", container.getExternalId()); this.containers.remove(container.getExternalId()); } container.setExternalId(resource.containerId); container.host = resource.host; container.bufferServerAddress = bufferServerAddr; if (UserGroupInformation.isSecurityEnabled()) { byte[] token = AuthManager.generateToken(); container.setBufferServerToken(token); } container.nodeHttpAddress = resource.nodeHttpAddress; container.setAllocatedMemoryMB(resource.memoryMB); container.setAllocatedVCores(resource.vCores); container.setStartedTime(-1); container.setFinishedTime(-1); writeJournal(container.getSetContainerState()); StreamingContainerAgent sca = new StreamingContainerAgent(container, newStreamingContainerContext(container), this); containers.put(resource.containerId, sca); LOG.debug("Assigned container {} priority {}", resource.containerId, resource.priority); return sca; } private StreamingContainerContext newStreamingContainerContext(PTContainer container) { try { int bufferServerMemory = 0; Iterator<PTOperator> operatorIterator = container.getOperators().iterator(); while (operatorIterator.hasNext()) { bufferServerMemory += operatorIterator.next().getBufferServerMemory(); } LOG.debug("Buffer Server Memory {}", bufferServerMemory); // the logical plan is not to be serialized via RPC, clone attributes only StreamingContainerContext scc = new StreamingContainerContext(plan.getLogicalPlan().getAttributes().clone(), null); scc.attributes.put(ContainerContext.IDENTIFIER, container.getExternalId()); scc.attributes.put(ContainerContext.BUFFER_SERVER_MB, bufferServerMemory); scc.attributes.put(ContainerContext.BUFFER_SERVER_TOKEN, container.getBufferServerToken()); scc.startWindowMillis = this.vars.windowStartMillis; return scc; } catch (CloneNotSupportedException ex) { throw new RuntimeException("Cannot clone DAG attributes", ex); } } public StreamingContainerAgent getContainerAgent(String containerId) { StreamingContainerAgent cs = containers.get(containerId); if (cs == null) { LOG.warn("Trying to get unknown container {}", containerId); } return cs; } public Collection<StreamingContainerAgent> getContainerAgents() { return this.containers.values(); } private void processOperatorDeployStatus(final PTOperator oper, OperatorHeartbeat ohb, StreamingContainerAgent sca) { OperatorHeartbeat.DeployState ds = null; if (ohb != null) { ds = ohb.getState(); } LOG.debug("heartbeat {} {}/{} {}", oper, oper.getState(), ds, oper.getContainer().getExternalId()); switch (oper.getState()) { case ACTIVE: // Commented out the warning below because it's expected when the operator does something // quickly and goes out of commission, it will report SHUTDOWN correctly whereas this code // is incorrectly expecting ACTIVE to be reported. //LOG.warn("status out of sync {} expected {} remote {}", oper, oper.getState(), ds); // operator expected active, check remote status if (ds == null) { sca.deployOpers.add(oper); } else { switch (ds) { case SHUTDOWN: // schedule operator deactivation against the windowId // will be processed once window is committed and all dependent operators completed processing long windowId = oper.stats.currentWindowId.get(); if (ohb.windowStats != null && !ohb.windowStats.isEmpty()) { windowId = ohb.windowStats.get(ohb.windowStats.size() - 1).windowId; } LOG.debug("Operator {} deactivated at window {}", oper, windowId); synchronized (this.shutdownOperators) { Set<PTOperator> deactivatedOpers = this.shutdownOperators.get(windowId); if (deactivatedOpers == null) { this.shutdownOperators.put(windowId, deactivatedOpers = new HashSet<>()); } deactivatedOpers.add(oper); } sca.undeployOpers.add(oper.getId()); slowestUpstreamOp.remove(oper); // record operator stop event recordEventAsync(new StramEvent.StopOperatorEvent(oper.getName(), oper.getId(), oper.getContainer().getExternalId())); break; case FAILED: processOperatorFailure(oper); sca.undeployOpers.add(oper.getId()); slowestUpstreamOp.remove(oper); recordEventAsync(new StramEvent.StopOperatorEvent(oper.getName(), oper.getId(), oper.getContainer().getExternalId())); break; case ACTIVE: default: break; } } break; case PENDING_UNDEPLOY: if (ds == null) { // operator no longer deployed in container recordEventAsync(new StramEvent.StopOperatorEvent(oper.getName(), oper.getId(), oper.getContainer().getExternalId())); oper.setState(State.PENDING_DEPLOY); sca.deployOpers.add(oper); } else { // operator is currently deployed, request undeploy sca.undeployOpers.add(oper.getId()); slowestUpstreamOp.remove(oper); } break; case PENDING_DEPLOY: if (ds == null) { // operator to be deployed sca.deployOpers.add(oper); } else { // operator was deployed in container PTContainer container = oper.getContainer(); LOG.debug("{} marking deployed: {} remote status {}", container.getExternalId(), oper, ds); oper.setState(PTOperator.State.ACTIVE); oper.stats.lastHeartbeat = null; // reset on redeploy oper.stats.lastWindowIdChangeTms = clock.getTime(); recordEventAsync(new StramEvent.StartOperatorEvent(oper.getName(), oper.getId(), container.getExternalId())); } break; default: //LOG.warn("Unhandled operator state {} {} remote {}", oper, oper.getState(), ds); if (ds != null) { // operator was removed and needs to be undeployed from container sca.undeployOpers.add(oper.getId()); slowestUpstreamOp.remove(oper); recordEventAsync(new StramEvent.StopOperatorEvent(oper.getName(), oper.getId(), oper.getContainer().getExternalId())); } } } private void processOperatorFailure(PTOperator oper) { // count failure transitions *->FAILED, applies to initialization as well as intermittent failures if (oper.getState() == PTOperator.State.ACTIVE) { oper.setState(PTOperator.State.INACTIVE); oper.failureCount++; oper.getOperatorMeta().getStatus().failureCount++; LOG.warn("Operator failure: {} count: {}", oper, oper.failureCount); Integer maxAttempts = oper.getOperatorMeta().getValue(OperatorContext.RECOVERY_ATTEMPTS); if (maxAttempts == null || oper.failureCount <= maxAttempts) { // restart entire container in attempt to recover operator // in the future a more sophisticated recovery strategy could // involve initial redeploy attempt(s) of affected operator in // existing container or sandbox container for just the operator LOG.error("Initiating container restart after operator failure {}", oper); containerStopRequests.put(oper.getContainer().getExternalId(), oper.getContainer().getExternalId()); } else { String msg = String.format("Shutdown after reaching failure threshold for %s", oper); LOG.warn(msg); shutdownAllContainers(msg); forcedShutdown = true; } } else { // should not get here LOG.warn("Failed operator {} {} {} to be undeployed by container", oper, oper.getState()); } } /** * process the heartbeat from each container. * called by the RPC thread for each container. (i.e. called by multiple threads) * * @param heartbeat * @return heartbeat response */ @SuppressWarnings("StatementWithEmptyBody") public ContainerHeartbeatResponse processHeartbeat(ContainerHeartbeat heartbeat) { long currentTimeMillis = clock.getTime(); final StreamingContainerAgent sca = this.containers.get(heartbeat.getContainerId()); if (sca == null || sca.container.getState() == PTContainer.State.KILLED) { // could be orphaned container that was replaced and needs to terminate LOG.error("Unknown container {}", heartbeat.getContainerId()); ContainerHeartbeatResponse response = new ContainerHeartbeatResponse(); response.shutdown = true; return response; } //LOG.debug("{} {} {}", new Object[]{sca.container.containerId, sca.container.bufferServerAddress, sca.container.getState()}); if (sca.container.getState() == PTContainer.State.ALLOCATED) { // capture dynamically assigned address from container if (sca.container.bufferServerAddress == null && heartbeat.bufferServerHost != null) { sca.container.bufferServerAddress = InetSocketAddress.createUnresolved(heartbeat.bufferServerHost, heartbeat.bufferServerPort); LOG.info("Container {} buffer server: {}", sca.container.getExternalId(), sca.container.bufferServerAddress); } final long containerStartTime = System.currentTimeMillis(); sca.container.setState(PTContainer.State.ACTIVE); sca.container.setStartedTime(containerStartTime); sca.container.setFinishedTime(-1); sca.jvmName = heartbeat.jvmName; poolExecutor.submit(new Runnable() { @Override public void run() { try { containerFile.append(sca.getContainerInfo()); } catch (IOException ex) { LOG.warn("Cannot write to container file"); } for (PTOperator ptOp : sca.container.getOperators()) { try { JSONObject operatorInfo = new JSONObject(); operatorInfo.put("name", ptOp.getName()); operatorInfo.put("id", ptOp.getId()); operatorInfo.put("container", sca.container.getExternalId()); operatorInfo.put("startTime", containerStartTime); operatorFile.append(operatorInfo); } catch (IOException | JSONException ex) { LOG.warn("Cannot write to operator file: ", ex); } } } }); } sca.containerStackTrace = heartbeat.stackTrace; if (heartbeat.restartRequested) { LOG.error("Container {} restart request", sca.container.getExternalId()); containerStopRequests.put(sca.container.getExternalId(), sca.container.getExternalId()); } sca.memoryMBFree = heartbeat.memoryMBFree; sca.gcCollectionCount = heartbeat.gcCollectionCount; sca.gcCollectionTime = heartbeat.gcCollectionTime; sca.undeployOpers.clear(); sca.deployOpers.clear(); if (!this.deployChangeInProgress.get()) { sca.deployCnt = this.deployChangeCnt; } Set<Integer> reportedOperators = Sets.newHashSetWithExpectedSize(sca.container.getOperators().size()); for (OperatorHeartbeat shb : heartbeat.getContainerStats().operators) { long maxEndWindowTimestamp = 0; reportedOperators.add(shb.nodeId); PTOperator oper = this.plan.getAllOperators().get(shb.getNodeId()); if (oper == null) { LOG.info("Heartbeat for unknown operator {} (container {})", shb.getNodeId(), heartbeat.getContainerId()); sca.undeployOpers.add(shb.nodeId); continue; } if (shb.requestResponse != null) { for (StatsListener.OperatorResponse obj : shb.requestResponse) { if (obj instanceof OperatorResponse) { // This is to identify platform requests commandResponse.put((Long)obj.getResponseId(), obj.getResponse()); LOG.debug(" Got back the response {} for the request {}", obj, obj.getResponseId()); } else { // This is to identify user requests oper.stats.responses.add(obj); } } } //LOG.debug("heartbeat {} {}/{} {}", oper, oper.getState(), shb.getState(), oper.getContainer().getExternalId()); if (!(oper.getState() == PTOperator.State.ACTIVE && shb.getState() == OperatorHeartbeat.DeployState.ACTIVE)) { // deploy state may require synchronization processOperatorDeployStatus(oper, shb, sca); } oper.stats.lastHeartbeat = shb; List<ContainerStats.OperatorStats> statsList = shb.getOperatorStatsContainer(); if (!statsList.isEmpty()) { long tuplesProcessed = 0; long tuplesEmitted = 0; long totalCpuTimeUsed = 0; int statCount = 0; long maxDequeueTimestamp = -1; oper.stats.recordingId = null; final OperatorStatus status = oper.stats; status.statsRevs.checkout(); for (Map.Entry<String, PortStatus> entry : status.inputPortStatusList.entrySet()) { entry.getValue().recordingId = null; } for (Map.Entry<String, PortStatus> entry : status.outputPortStatusList.entrySet()) { entry.getValue().recordingId = null; } for (ContainerStats.OperatorStats stats : statsList) { if (stats == null) { LOG.warn("Operator {} statistics list contains null element", shb.getNodeId()); continue; } /* report checkpoint-ed WindowId status of the operator */ if (stats.checkpoint instanceof Checkpoint) { if (oper.getRecentCheckpoint() == null || oper.getRecentCheckpoint().windowId < stats.checkpoint.getWindowId()) { addCheckpoint(oper, (Checkpoint)stats.checkpoint); if (stats.checkpointStats != null) { status.checkpointStats = stats.checkpointStats; status.checkpointTimeMA.add(stats.checkpointStats.checkpointTime); } oper.failureCount = 0; } } oper.stats.recordingId = stats.recordingId; /* report all the other stuff */ // calculate the stats related to end window EndWindowStats endWindowStats = new EndWindowStats(); // end window stats for a particular window id for a particular node Collection<ContainerStats.OperatorStats.PortStats> ports = stats.inputPorts; if (ports != null) { Set<String> currentInputPortSet = Sets.newHashSetWithExpectedSize(ports.size()); for (ContainerStats.OperatorStats.PortStats s : ports) { currentInputPortSet.add(s.id); PortStatus ps = status.inputPortStatusList.get(s.id); if (ps == null) { ps = status.new PortStatus(); ps.portName = s.id; status.inputPortStatusList.put(s.id, ps); } ps.totalTuples += s.tupleCount; ps.recordingId = s.recordingId; tuplesProcessed += s.tupleCount; endWindowStats.dequeueTimestamps.put(s.id, s.endWindowTimestamp); Pair<Integer, String> operatorPortName = new Pair<>(oper.getId(), s.id); Long lastEndWindowTimestamp = operatorPortLastEndWindowTimestamps.get(operatorPortName); if (lastEndWindowTimestamp == null) { lastEndWindowTimestamp = lastStatsTimestamp; } long portElapsedMillis = Math.max(s.endWindowTimestamp - lastEndWindowTimestamp, 0); //LOG.debug("=== PROCESSED TUPLE COUNT for {}: {}, {}, {}, {}", operatorPortName, s.tupleCount, portElapsedMillis, operatorPortLastEndWindowTimestamps.get(operatorPortName), lastStatsTimestamp); ps.tuplesPMSMA.add(s.tupleCount, portElapsedMillis); ps.bufferServerBytesPMSMA.add(s.bufferServerBytes, portElapsedMillis); ps.queueSizeMA.add(s.queueSize); operatorPortLastEndWindowTimestamps.put(operatorPortName, s.endWindowTimestamp); if (maxEndWindowTimestamp < s.endWindowTimestamp) { maxEndWindowTimestamp = s.endWindowTimestamp; } if (s.endWindowTimestamp > maxDequeueTimestamp) { maxDequeueTimestamp = s.endWindowTimestamp; } } // need to remove dead ports, for unifiers Iterator<Map.Entry<String, PortStatus>> it = status.inputPortStatusList.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, PortStatus> entry = it.next(); if (!currentInputPortSet.contains(entry.getKey())) { it.remove(); } } } ports = stats.outputPorts; if (ports != null) { Set<String> currentOutputPortSet = Sets.newHashSetWithExpectedSize(ports.size()); for (ContainerStats.OperatorStats.PortStats s : ports) { currentOutputPortSet.add(s.id); PortStatus ps = status.outputPortStatusList.get(s.id); if (ps == null) { ps = status.new PortStatus(); ps.portName = s.id; status.outputPortStatusList.put(s.id, ps); } ps.totalTuples += s.tupleCount; ps.recordingId = s.recordingId; tuplesEmitted += s.tupleCount; Pair<Integer, String> operatorPortName = new Pair<>(oper.getId(), s.id); Long lastEndWindowTimestamp = operatorPortLastEndWindowTimestamps.get(operatorPortName); if (lastEndWindowTimestamp == null) { lastEndWindowTimestamp = lastStatsTimestamp; } long portElapsedMillis = Math.max(s.endWindowTimestamp - lastEndWindowTimestamp, 0); //LOG.debug("=== EMITTED TUPLE COUNT for {}: {}, {}, {}, {}", operatorPortName, s.tupleCount, portElapsedMillis, operatorPortLastEndWindowTimestamps.get(operatorPortName), lastStatsTimestamp); ps.tuplesPMSMA.add(s.tupleCount, portElapsedMillis); ps.bufferServerBytesPMSMA.add(s.bufferServerBytes, portElapsedMillis); operatorPortLastEndWindowTimestamps.put(operatorPortName, s.endWindowTimestamp); if (maxEndWindowTimestamp < s.endWindowTimestamp) { maxEndWindowTimestamp = s.endWindowTimestamp; } } if (ports.size() > 0) { endWindowStats.emitTimestamp = ports.iterator().next().endWindowTimestamp; } // need to remove dead ports, for unifiers Iterator<Map.Entry<String, PortStatus>> it = status.outputPortStatusList.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, PortStatus> entry = it.next(); if (!currentOutputPortSet.contains(entry.getKey())) { it.remove(); } } } // for output operator, just take the maximum dequeue time for emit timestamp. // (we don't know the latency for output operators because they don't emit tuples) if (endWindowStats.emitTimestamp < 0) { endWindowStats.emitTimestamp = maxDequeueTimestamp; } if (status.currentWindowId.get() != stats.windowId) { status.lastWindowIdChangeTms = currentTimeMillis; status.currentWindowId.set(stats.windowId); } totalCpuTimeUsed += stats.cpuTimeUsed; statCount++; if (oper.getOperatorMeta().getValue(OperatorContext.COUNTERS_AGGREGATOR) != null) { endWindowStats.counters = stats.counters; } if (oper.getOperatorMeta().getMetricAggregatorMeta() != null && oper.getOperatorMeta().getMetricAggregatorMeta().getAggregator() != null) { endWindowStats.metrics = stats.metrics; } if (stats.windowId > currentEndWindowStatsWindowId) { Map<Integer, EndWindowStats> endWindowStatsMap = endWindowStatsOperatorMap.get(stats.windowId); if (endWindowStatsMap == null) { endWindowStatsMap = new ConcurrentSkipListMap<>(); Map<Integer, EndWindowStats> endWindowStatsMapPrevious = endWindowStatsOperatorMap.putIfAbsent(stats.windowId, endWindowStatsMap); if (endWindowStatsMapPrevious != null) { endWindowStatsMap = endWindowStatsMapPrevious; } } endWindowStatsMap.put(shb.getNodeId(), endWindowStats); if (!oper.getInputs().isEmpty()) { long latency = Long.MAX_VALUE; long adjustedEndWindowEmitTimestamp = endWindowStats.emitTimestamp; MovingAverageLong rpcLatency = rpcLatencies.get(oper.getContainer().getExternalId()); if (rpcLatency != null) { adjustedEndWindowEmitTimestamp += rpcLatency.getAvg(); } PTOperator slowestUpstream = null; for (PTInput input : oper.getInputs()) { PTOperator upstreamOp = input.source.source; if (upstreamOp.getOperatorMeta().getOperator() instanceof Operator.DelayOperator) { continue; } EndWindowStats ews = endWindowStatsMap.get(upstreamOp.getId()); long portLatency; if (ews == null) { // This is when the operator is likely to be behind too many windows. We need to give an estimate for // latency at this point, by looking at the number of windows behind int widthMillis = plan.getLogicalPlan().getValue(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS); portLatency = (upstreamOp.stats.currentWindowId.get() - oper.stats.currentWindowId.get()) * widthMillis; } else { MovingAverageLong upstreamRPCLatency = rpcLatencies.get(upstreamOp.getContainer().getExternalId()); portLatency = adjustedEndWindowEmitTimestamp - ews.emitTimestamp; if (upstreamRPCLatency != null) { portLatency -= upstreamRPCLatency.getAvg(); } } if (portLatency < 0) { portLatency = 0; } if (latency > portLatency) { latency = portLatency; slowestUpstream = upstreamOp; } } status.latencyMA.add(latency); slowestUpstreamOp.put(oper, slowestUpstream); } Set<Integer> allCurrentOperators = plan.getAllOperators().keySet(); int numOperators = plan.getAllOperators().size(); if (allCurrentOperators.containsAll(endWindowStatsMap.keySet()) && endWindowStatsMap.size() == numOperators) { completeEndWindowStatsWindowId = stats.windowId; } } } status.totalTuplesProcessed.add(tuplesProcessed); status.totalTuplesEmitted.add(tuplesEmitted); OperatorMeta logicalOperator = oper.getOperatorMeta(); LogicalOperatorStatus logicalStatus = logicalOperator.getStatus(); if (!oper.isUnifier()) { logicalStatus.totalTuplesProcessed += tuplesProcessed; logicalStatus.totalTuplesEmitted += tuplesEmitted; } long lastMaxEndWindowTimestamp = operatorLastEndWindowTimestamps.containsKey(oper.getId()) ? operatorLastEndWindowTimestamps.get(oper.getId()) : lastStatsTimestamp; if (maxEndWindowTimestamp >= lastMaxEndWindowTimestamp) { double tuplesProcessedPMSMA = 0.0; double tuplesEmittedPMSMA = 0.0; if (statCount != 0) { //LOG.debug("CPU for {}: {} / {} - {}", oper.getId(), totalCpuTimeUsed, maxEndWindowTimestamp, lastMaxEndWindowTimestamp); status.cpuNanosPMSMA.add(totalCpuTimeUsed, maxEndWindowTimestamp - lastMaxEndWindowTimestamp); } for (PortStatus ps : status.inputPortStatusList.values()) { tuplesProcessedPMSMA += ps.tuplesPMSMA.getAvg(); } for (PortStatus ps : status.outputPortStatusList.values()) { tuplesEmittedPMSMA += ps.tuplesPMSMA.getAvg(); } status.tuplesProcessedPSMA.set(Math.round(tuplesProcessedPMSMA * 1000)); status.tuplesEmittedPSMA.set(Math.round(tuplesEmittedPMSMA * 1000)); } else { //LOG.warn("This timestamp for {} is lower than the previous!! {} < {}", oper.getId(), // maxEndWindowTimestamp, lastMaxEndWindowTimestamp); } operatorLastEndWindowTimestamps.put(oper.getId(), maxEndWindowTimestamp); status.listenerStats.add(statsList); this.reportStats.put(oper, oper); status.statsRevs.commit(); } if (lastStatsTimestamp < maxEndWindowTimestamp) { lastStatsTimestamp = maxEndWindowTimestamp; } } sca.lastHeartbeatMillis = currentTimeMillis; for (PTOperator oper : sca.container.getOperators()) { if (!reportedOperators.contains(oper.getId())) { processOperatorDeployStatus(oper, null, sca); } } ContainerHeartbeatResponse rsp = getHeartbeatResponse(sca); if (heartbeat.getContainerStats().operators.isEmpty() && isApplicationIdle()) { LOG.info("requesting idle shutdown for container {}", heartbeat.getContainerId()); rsp.shutdown = true; } else { if (sca.shutdownRequested) { LOG.info("requesting shutdown for container {}", heartbeat.getContainerId()); rsp.shutdown = true; } } List<StramToNodeRequest> requests = rsp.nodeRequests != null ? rsp.nodeRequests : new ArrayList<StramToNodeRequest>(); ConcurrentLinkedQueue<StramToNodeRequest> operatorRequests = sca.getOperatorRequests(); while (true) { StramToNodeRequest r = operatorRequests.poll(); if (r == null) { break; } requests.add(r); } rsp.nodeRequests = requests; rsp.committedWindowId = committedWindowId; rsp.stackTraceRequired = sca.stackTraceRequested; sca.stackTraceRequested = false; return rsp; } private ContainerHeartbeatResponse getHeartbeatResponse(StreamingContainerAgent sca) { ContainerHeartbeatResponse rsp = new ContainerHeartbeatResponse(); if (this.deployChangeInProgress.get() || sca.deployCnt != this.deployChangeCnt) { LOG.debug("{} deferred requests due to concurrent plan change.", sca.container.toIdStateString()); rsp.hasPendingRequests = true; return rsp; } if (!sca.undeployOpers.isEmpty()) { rsp.undeployRequest = Lists.newArrayList(sca.undeployOpers); rsp.hasPendingRequests = (!sca.deployOpers.isEmpty()); return rsp; } Set<PTOperator> deployOperators = sca.deployOpers; if (!deployOperators.isEmpty()) { // deploy once all containers are running and no undeploy operations are pending. for (PTContainer c : getPhysicalPlan().getContainers()) { if (c.getState() != PTContainer.State.ACTIVE) { LOG.debug("{} waiting for container activation {}", sca.container.toIdStateString(), c.toIdStateString()); rsp.hasPendingRequests = true; return rsp; } for (PTOperator oper : c.getOperators()) { if (oper.getState() == PTOperator.State.PENDING_UNDEPLOY) { LOG.debug("{} waiting for undeploy {} {}", sca.container.toIdStateString(), c.toIdStateString(), oper); rsp.hasPendingRequests = true; return rsp; } } } LOG.debug("{} deployable operators: {}", sca.container.toIdStateString(), deployOperators); List<OperatorDeployInfo> deployList = sca.getDeployInfoList(deployOperators); if (deployList != null && !deployList.isEmpty()) { rsp.deployRequest = deployList; rsp.nodeRequests = Lists.newArrayList(); for (PTOperator o : deployOperators) { rsp.nodeRequests.addAll(o.deployRequests); } } rsp.hasPendingRequests = false; return rsp; } return rsp; } private boolean isApplicationIdle() { if (eventQueueProcessing.get()) { return false; } for (StreamingContainerAgent sca : this.containers.values()) { if (sca.hasPendingWork()) { // container may have no active operators but deploy request pending return false; } for (PTOperator oper : sca.container.getOperators()) { if (!oper.stats.isIdle()) { return false; } } } return true; } @SuppressWarnings("StatementWithEmptyBody") void addCheckpoint(PTOperator node, Checkpoint checkpoint) { synchronized (node.checkpoints) { if (!node.checkpoints.isEmpty()) { Checkpoint lastCheckpoint = node.checkpoints.getLast(); // skip unless checkpoint moves if (lastCheckpoint.windowId != checkpoint.windowId) { if (lastCheckpoint.windowId > checkpoint.windowId) { // list needs to have max windowId last LOG.warn("Out of sequence checkpoint {} last {} (operator {})", checkpoint, lastCheckpoint, node); ListIterator<Checkpoint> li = node.checkpoints.listIterator(); while (li.hasNext() && li.next().windowId < checkpoint.windowId) { //continue; } if (li.previous().windowId != checkpoint.windowId) { li.add(checkpoint); } } else { node.checkpoints.add(checkpoint); } } } else { node.checkpoints.add(checkpoint); } } } public static class UpdateCheckpointsContext { public final MutableLong committedWindowId = new MutableLong(Long.MAX_VALUE); public final Set<PTOperator> visited = new LinkedHashSet<>(); public final Set<PTOperator> blocked = new LinkedHashSet<>(); public final long currentTms; public final boolean recovery; public final Map<OperatorMeta, Set<OperatorMeta>> checkpointGroups; public UpdateCheckpointsContext(Clock clock) { this(clock, false, Collections.<OperatorMeta, Set<OperatorMeta>>emptyMap()); } public UpdateCheckpointsContext(Clock clock, boolean recovery, Map<OperatorMeta, Set<OperatorMeta>> checkpointGroups) { this.currentTms = clock.getTime(); this.recovery = recovery; this.checkpointGroups = checkpointGroups; } } /** * Compute checkpoints required for a given operator instance to be recovered. * This is done by looking at checkpoints available for downstream dependencies first, * and then selecting the most recent available checkpoint that is smaller than downstream. * * @param operator Operator instance for which to find recovery checkpoint * @param ctx Context into which to collect traversal info */ public void updateRecoveryCheckpoints(PTOperator operator, UpdateCheckpointsContext ctx) { if (operator.getRecoveryCheckpoint().windowId < ctx.committedWindowId.longValue()) { ctx.committedWindowId.setValue(operator.getRecoveryCheckpoint().windowId); } if (operator.getState() == PTOperator.State.ACTIVE && (ctx.currentTms - operator.stats.lastWindowIdChangeTms) > operator.stats.windowProcessingTimeoutMillis) { // if the checkpoint is ahead, then it is not blocked but waiting for activation (state-less recovery, at-most-once) if (ctx.committedWindowId.longValue() >= operator.getRecoveryCheckpoint().windowId) { LOG.warn("Marking operator {} blocked committed window {}, recovery window {}, current time {}, last window id change time {}, window processing timeout millis {}", operator, Codec.getStringWindowId(ctx.committedWindowId.longValue()), Codec.getStringWindowId(operator.getRecoveryCheckpoint().windowId), ctx.currentTms, operator.stats.lastWindowIdChangeTms, operator.stats.windowProcessingTimeoutMillis); ctx.blocked.add(operator); } } // the most recent checkpoint eligible for recovery based on downstream state Checkpoint maxCheckpoint = Checkpoint.INITIAL_CHECKPOINT; Set<OperatorMeta> checkpointGroup = ctx.checkpointGroups.get(operator.getOperatorMeta()); if (checkpointGroup == null) { checkpointGroup = Collections.singleton(operator.getOperatorMeta()); } // find intersection of checkpoints that group can collectively move to TreeSet<Checkpoint> commonCheckpoints = new TreeSet<>(new Checkpoint.CheckpointComparator()); synchronized (operator.checkpoints) { commonCheckpoints.addAll(operator.checkpoints); } Set<PTOperator> groupOpers = new HashSet<>(checkpointGroup.size()); boolean pendingDeploy = operator.getState() == PTOperator.State.PENDING_DEPLOY; if (checkpointGroup.size() > 1) { for (OperatorMeta om : checkpointGroup) { Collection<PTOperator> operators = plan.getAllOperators(om); for (PTOperator groupOper : operators) { synchronized (groupOper.checkpoints) { commonCheckpoints.retainAll(groupOper.checkpoints); } // visit all downstream operators of the group ctx.visited.add(groupOper); groupOpers.add(groupOper); pendingDeploy |= operator.getState() == PTOperator.State.PENDING_DEPLOY; } } // highest common checkpoint if (!commonCheckpoints.isEmpty()) { maxCheckpoint = commonCheckpoints.last(); } } else { // without logical grouping, treat partitions as independent // this is especially important for parallel partitioning ctx.visited.add(operator); groupOpers.add(operator); maxCheckpoint = operator.getRecentCheckpoint(); if (ctx.recovery && maxCheckpoint.windowId == Stateless.WINDOW_ID && operator.isOperatorStateLess()) { long currentWindowId = WindowGenerator.getWindowId(ctx.currentTms, this.vars.windowStartMillis, this.getLogicalPlan().getValue(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS)); maxCheckpoint = new Checkpoint(currentWindowId, 0, 0); } } // DFS downstream operators for (PTOperator groupOper : groupOpers) { for (PTOperator.PTOutput out : groupOper.getOutputs()) { for (PTOperator.PTInput sink : out.sinks) { PTOperator sinkOperator = sink.target; if (groupOpers.contains(sinkOperator)) { continue; // downstream operator within group } if (!ctx.visited.contains(sinkOperator)) { // downstream traversal updateRecoveryCheckpoints(sinkOperator, ctx); } // recovery window id cannot move backwards // when dynamically adding new operators if (sinkOperator.getRecoveryCheckpoint().windowId >= operator.getRecoveryCheckpoint().windowId) { maxCheckpoint = Checkpoint.min(maxCheckpoint, sinkOperator.getRecoveryCheckpoint()); } if (ctx.blocked.contains(sinkOperator)) { if (sinkOperator.stats.getCurrentWindowId() == operator.stats.getCurrentWindowId()) { // downstream operator is blocked by this operator ctx.blocked.remove(sinkOperator); } } } } } // find the common checkpoint that is <= downstream recovery checkpoint if (!commonCheckpoints.contains(maxCheckpoint)) { if (!commonCheckpoints.isEmpty()) { maxCheckpoint = Objects.firstNonNull(commonCheckpoints.floor(maxCheckpoint), maxCheckpoint); } } for (PTOperator groupOper : groupOpers) { // checkpoint frozen during deployment if (!pendingDeploy || ctx.recovery) { // remove previous checkpoints Checkpoint c1 = Checkpoint.INITIAL_CHECKPOINT; LinkedList<Checkpoint> checkpoints = groupOper.checkpoints; synchronized (checkpoints) { if (!checkpoints.isEmpty() && (checkpoints.getFirst()).windowId <= maxCheckpoint.windowId) { c1 = checkpoints.getFirst(); Checkpoint c2; while (checkpoints.size() > 1 && ((c2 = checkpoints.get(1)).windowId) <= maxCheckpoint.windowId) { checkpoints.removeFirst(); //LOG.debug("Checkpoint to delete: operator={} windowId={}", operator.getName(), c1); this.purgeCheckpoints.add(new Pair<>(groupOper, c1.windowId)); c1 = c2; } } else { if (ctx.recovery && checkpoints.isEmpty() && groupOper.isOperatorStateLess()) { LOG.debug("Adding checkpoint for stateless operator {} {}", groupOper, Codec.getStringWindowId(maxCheckpoint.windowId)); c1 = groupOper.addCheckpoint(maxCheckpoint.windowId, this.vars.windowStartMillis); } } } //LOG.debug("Operator {} checkpoints: commit {} recent {}", new Object[] {operator.getName(), c1, operator.checkpoints}); groupOper.setRecoveryCheckpoint(c1); } else { LOG.debug("Skipping checkpoint update {} during {}", groupOper, groupOper.getState()); } } } public long windowIdToMillis(long windowId) { int widthMillis = plan.getLogicalPlan().getValue(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS); return WindowGenerator.getWindowMillis(windowId, this.vars.windowStartMillis, widthMillis); } public long getWindowStartMillis() { return this.vars.windowStartMillis; } private Map<OperatorMeta, Set<OperatorMeta>> getCheckpointGroups() { if (this.checkpointGroups == null) { this.checkpointGroups = new HashMap<>(); LogicalPlan dag = this.plan.getLogicalPlan(); dag.resetNIndex(); LogicalPlan.ValidationContext vc = new LogicalPlan.ValidationContext(); for (OperatorMeta om : dag.getRootOperators()) { this.plan.getLogicalPlan().findStronglyConnected(om, vc); } for (Set<OperatorMeta> checkpointGroup : vc.stronglyConnected) { for (OperatorMeta om : checkpointGroup) { this.checkpointGroups.put(om, checkpointGroup); } } } return checkpointGroups; } /** * Visit all operators to update current checkpoint based on updated downstream state. * Purge older checkpoints that are no longer needed. */ private long updateCheckpoints(boolean recovery) { UpdateCheckpointsContext ctx = new UpdateCheckpointsContext(clock, recovery, getCheckpointGroups()); for (OperatorMeta logicalOperator : plan.getLogicalPlan().getRootOperators()) { //LOG.debug("Updating checkpoints for operator {}", logicalOperator.getName()); List<PTOperator> operators = plan.getOperators(logicalOperator); if (operators != null) { for (PTOperator operator : operators) { updateRecoveryCheckpoints(operator, ctx); } } } purgeCheckpoints(); for (PTOperator oper : ctx.blocked) { String containerId = oper.getContainer().getExternalId(); if (containerId != null) { LOG.info("Blocked operator {} container {} time {}ms", oper, oper.getContainer().toIdStateString(), ctx.currentTms - oper.stats.lastWindowIdChangeTms); this.containerStopRequests.put(containerId, containerId); } } return ctx.committedWindowId.longValue(); } private BufferServerController getBufferServerClient(PTOperator operator) { BufferServerController bsc = new BufferServerController(operator.getLogicalId()); bsc.setToken(operator.getContainer().getBufferServerToken()); InetSocketAddress address = operator.getContainer().bufferServerAddress; StreamingContainer.eventloop.connect(address.isUnresolved() ? new InetSocketAddress(address.getHostName(), address.getPort()) : address, bsc); return bsc; } private void purgeCheckpoints() { for (Pair<PTOperator, Long> p : purgeCheckpoints) { final PTOperator operator = p.getFirst(); if (!operator.isOperatorStateLess()) { final long windowId = p.getSecond(); Runnable r = new Runnable() { @Override public void run() { try { operator.getOperatorMeta().getValue(OperatorContext.STORAGE_AGENT).delete(operator.getId(), windowId); } catch (IOException ex) { LOG.error("Failed to purge checkpoint for operator {} for windowId {}", operator, windowId, ex); } } }; poolExecutor.submit(r); } // delete stream state when using buffer server for (PTOperator.PTOutput out : operator.getOutputs()) { if (!out.isDownStreamInline()) { if (operator.getContainer().bufferServerAddress == null) { // address should be null only for a new container, in which case there should not be a purge request // TODO: logging added to find out how we got here LOG.warn("purge request w/o buffer server address source {} container {} checkpoints {}", out, operator.getContainer(), operator.checkpoints); continue; } for (InputPortMeta ipm : out.logicalStream.getSinks()) { StreamCodec<?> streamCodecInfo = StreamingContainerAgent.getStreamCodec(ipm); Integer codecId = plan.getStreamCodecIdentifier(streamCodecInfo); // following needs to match the concat logic in StreamingContainer String sourceIdentifier = Integer.toString(operator.getId()).concat(Component.CONCAT_SEPARATOR).concat(out.portName).concat(Component.CONCAT_SEPARATOR).concat(codecId.toString()); // delete everything from buffer server prior to new checkpoint BufferServerController bsc = getBufferServerClient(operator); try { bsc.purge(null, sourceIdentifier, operator.checkpoints.getFirst().windowId - 1); } catch (RuntimeException re) { LOG.warn("Failed to purge {} {}", bsc.addr, sourceIdentifier, re); } } } } } purgeCheckpoints.clear(); } /** * Mark all containers for shutdown, next container heartbeat response * will propagate the shutdown request. This is controlled soft shutdown. * If containers don't respond, the application can be forcefully terminated * via yarn using forceKillApplication. * * @param message */ public void shutdownAllContainers(String message) { this.shutdownDiagnosticsMessage = message; LOG.info("Initiating application shutdown: {}", message); for (StreamingContainerAgent cs : this.containers.values()) { cs.shutdownRequested = true; } } private Map<PTContainer, List<PTOperator>> groupByContainer(Collection<PTOperator> operators) { Map<PTContainer, List<PTOperator>> m = new HashMap<>(); for (PTOperator node : operators) { List<PTOperator> nodes = m.get(node.getContainer()); if (nodes == null) { nodes = new ArrayList<>(); m.put(node.getContainer(), nodes); } nodes.add(node); } return m; } private void requestContainer(PTContainer c) { ContainerStartRequest dr = new ContainerStartRequest(c); containerStartRequests.add(dr); pendingAllocation.add(dr.container); lastResourceRequest = System.currentTimeMillis(); for (PTOperator operator : c.getOperators()) { operator.setState(PTOperator.State.INACTIVE); } } @Override public void deploy(Set<PTContainer> releaseContainers, Collection<PTOperator> undeploy, Set<PTContainer> startContainers, Collection<PTOperator> deploy) { try { this.deployChangeInProgress.set(true); Map<PTContainer, List<PTOperator>> undeployGroups = groupByContainer(undeploy); // stop affected operators (exclude new/failed containers) // order does not matter, remove all operators in each container in one sweep for (Map.Entry<PTContainer, List<PTOperator>> e : undeployGroups.entrySet()) { // container may already be in failed or pending deploy state, notified by RM or timed out PTContainer c = e.getKey(); if (!startContainers.contains(c) && !releaseContainers.contains(c) && c.getState() != PTContainer.State.KILLED) { LOG.debug("scheduling undeploy {} {}", e.getKey().getExternalId(), e.getValue()); for (PTOperator oper : e.getValue()) { oper.setState(PTOperator.State.PENDING_UNDEPLOY); } } } // start new containers for (PTContainer c : startContainers) { requestContainer(c); } // (re)deploy affected operators // can happen in parallel after buffer server for recovered publishers is reset Map<PTContainer, List<PTOperator>> deployGroups = groupByContainer(deploy); for (Map.Entry<PTContainer, List<PTOperator>> e : deployGroups.entrySet()) { if (!startContainers.contains(e.getKey())) { // to reset publishers, clean buffer server past checkpoint so subscribers don't read stale data (including end of stream) for (PTOperator operator : e.getValue()) { for (PTOperator.PTOutput out : operator.getOutputs()) { if (!out.isDownStreamInline()) { for (InputPortMeta ipm : out.logicalStream.getSinks()) { StreamCodec<?> streamCodecInfo = StreamingContainerAgent.getStreamCodec(ipm); Integer codecId = plan.getStreamCodecIdentifier(streamCodecInfo); // following needs to match the concat logic in StreamingContainer String sourceIdentifier = Integer.toString(operator.getId()).concat(Component.CONCAT_SEPARATOR).concat(out.portName).concat(Component.CONCAT_SEPARATOR).concat(codecId.toString()); if (operator.getContainer().getState() == PTContainer.State.ACTIVE) { // TODO: unit test - find way to mock this when testing rest of logic if (operator.getContainer().bufferServerAddress.getPort() != 0) { BufferServerController bsc = getBufferServerClient(operator); // reset publisher (stale operator may still write data until disconnected) // ensures new subscriber starting to read from checkpoint will wait until publisher redeploy cycle is complete try { bsc.reset(null, sourceIdentifier, 0); } catch (Exception ex) { LOG.error("Failed to reset buffer server {} {}", sourceIdentifier, ex); } } } } } } } } // add to operators that we expect to deploy LOG.debug("scheduling deploy {} {}", e.getKey().getExternalId(), e.getValue()); for (PTOperator oper : e.getValue()) { // operator will be deployed after it has been undeployed, if still referenced by the container if (oper.getState() != PTOperator.State.PENDING_UNDEPLOY) { oper.setState(PTOperator.State.PENDING_DEPLOY); } } } // stop containers that are no longer used for (PTContainer c : releaseContainers) { if (c.getExternalId() == null) { continue; } StreamingContainerAgent sca = containers.get(c.getExternalId()); if (sca != null) { LOG.debug("Container marked for shutdown: {}", c); // container already removed from plan // TODO: monitor soft shutdown sca.shutdownRequested = true; } } } finally { this.deployChangeCnt++; this.deployChangeInProgress.set(false); } } @Override public void recordEventAsync(StramEvent ev) { if (eventBus != null) { eventBus.publishAsync(ev); } } @Override public void dispatch(Runnable r) { this.eventQueue.add(r); } public OperatorInfo getOperatorInfo(int operatorId) { PTOperator o = this.plan.getAllOperators().get(operatorId); return o == null ? null : fillPhysicalOperatorInfo(o); } public List<OperatorInfo> getOperatorInfoList() { List<OperatorInfo> infoList = new ArrayList<>(); for (PTContainer container : this.plan.getContainers()) { for (PTOperator operator : container.getOperators()) { infoList.add(fillPhysicalOperatorInfo(operator)); } } return infoList; } public LogicalOperatorInfo getLogicalOperatorInfo(String operatorName) { OperatorMeta operatorMeta = getLogicalPlan().getOperatorMeta(operatorName); if (operatorMeta == null) { return null; } return fillLogicalOperatorInfo(operatorMeta); } public ModuleMeta getModuleMeta(String moduleName) { return getModuleMeta(moduleName, getLogicalPlan()); } private ModuleMeta getModuleMeta(String moduleName, LogicalPlan dag) { for (ModuleMeta m : dag.getAllModules()) { if (m.getFullName().equals(moduleName)) { return m; } ModuleMeta res = getModuleMeta(moduleName, m.getDag()); if (res != null) { return res; } } return null; } public List<LogicalOperatorInfo> getLogicalOperatorInfoList() { List<LogicalOperatorInfo> infoList = new ArrayList<>(); Collection<OperatorMeta> allOperators = getLogicalPlan().getAllOperators(); for (OperatorMeta operatorMeta : allOperators) { infoList.add(fillLogicalOperatorInfo(operatorMeta)); } return infoList; } public OperatorAggregationInfo getOperatorAggregationInfo(String operatorName) { OperatorMeta operatorMeta = getLogicalPlan().getOperatorMeta(operatorName); if (operatorMeta == null) { return null; } return fillOperatorAggregationInfo(operatorMeta); } public static long toWsWindowId(long windowId) { // until console handles -1 return windowId < 0 ? 0 : windowId; } private OperatorInfo fillPhysicalOperatorInfo(PTOperator operator) { OperatorInfo oi = new OperatorInfo(); oi.container = operator.getContainer().getExternalId(); oi.host = operator.getContainer().host; oi.id = Integer.toString(operator.getId()); oi.name = operator.getName(); oi.className = operator.getOperatorMeta().getOperator().getClass().getName(); oi.status = operator.getState().toString(); if (operator.isUnifier()) { oi.unifierClass = operator.getUnifierClass().getName(); } oi.logicalName = operator.getOperatorMeta().getName(); OperatorStatus os = operator.stats; oi.recordingId = os.recordingId; oi.totalTuplesProcessed = os.totalTuplesProcessed.get(); oi.totalTuplesEmitted = os.totalTuplesEmitted.get(); oi.tuplesProcessedPSMA = os.tuplesProcessedPSMA.get(); oi.tuplesEmittedPSMA = os.tuplesEmittedPSMA.get(); oi.cpuPercentageMA = os.cpuNanosPMSMA.getAvg() / 10000; oi.latencyMA = os.latencyMA.getAvg(); oi.failureCount = operator.failureCount; oi.recoveryWindowId = toWsWindowId(operator.getRecoveryCheckpoint().windowId); oi.currentWindowId = toWsWindowId(os.currentWindowId.get()); if (os.lastHeartbeat != null) { oi.lastHeartbeat = os.lastHeartbeat.getGeneratedTms(); } if (os.checkpointStats != null) { oi.checkpointTime = os.checkpointStats.checkpointTime; oi.checkpointStartTime = os.checkpointStats.checkpointStartTime; } oi.checkpointTimeMA = os.checkpointTimeMA.getAvg(); for (PortStatus ps : os.inputPortStatusList.values()) { PortInfo pinfo = new PortInfo(); pinfo.name = ps.portName; pinfo.type = "input"; pinfo.totalTuples = ps.totalTuples; pinfo.tuplesPSMA = Math.round(ps.tuplesPMSMA.getAvg() * 1000); pinfo.bufferServerBytesPSMA = Math.round(ps.bufferServerBytesPMSMA.getAvg() * 1000); pinfo.queueSizeMA = ps.queueSizeMA.getAvg(); pinfo.recordingId = ps.recordingId; oi.addPort(pinfo); } for (PortStatus ps : os.outputPortStatusList.values()) { PortInfo pinfo = new PortInfo(); pinfo.name = ps.portName; pinfo.type = "output"; pinfo.totalTuples = ps.totalTuples; pinfo.tuplesPSMA = Math.round(ps.tuplesPMSMA.getAvg() * 1000); pinfo.bufferServerBytesPSMA = Math.round(ps.bufferServerBytesPMSMA.getAvg() * 1000); pinfo.recordingId = ps.recordingId; oi.addPort(pinfo); } oi.counters = os.getLastWindowedStats().size() > 0 ? os.getLastWindowedStats().get(os.getLastWindowedStats().size() - 1).counters : null; oi.metrics = os.getLastWindowedStats().size() > 0 ? os.getLastWindowedStats().get(os.getLastWindowedStats().size() - 1).metrics : null; return oi; } private LogicalOperatorInfo fillLogicalOperatorInfo(OperatorMeta operator) { LogicalOperatorInfo loi = new LogicalOperatorInfo(); loi.name = operator.getName(); loi.className = operator.getOperator().getClass().getName(); loi.totalTuplesEmitted = operator.getStatus().totalTuplesEmitted; loi.totalTuplesProcessed = operator.getStatus().totalTuplesProcessed; loi.failureCount = operator.getStatus().failureCount; loi.status = new HashMap<>(); loi.partitions = new TreeSet<>(); loi.unifiers = new TreeSet<>(); loi.containerIds = new TreeSet<>(); loi.hosts = new TreeSet<>(); Collection<PTOperator> physicalOperators = getPhysicalPlan().getAllOperators(operator); NumberAggregate.LongAggregate checkpointTimeAggregate = new NumberAggregate.LongAggregate(); for (PTOperator physicalOperator : physicalOperators) { OperatorStatus os = physicalOperator.stats; if (physicalOperator.isUnifier()) { loi.unifiers.add(physicalOperator.getId()); } else { loi.partitions.add(physicalOperator.getId()); // exclude unifier, not sure if we should include it in the future loi.tuplesEmittedPSMA += os.tuplesEmittedPSMA.get(); loi.tuplesProcessedPSMA += os.tuplesProcessedPSMA.get(); // calculate maximum latency for all partitions long latency = calculateLatency(physicalOperator); if (latency > loi.latencyMA) { loi.latencyMA = latency; } checkpointTimeAggregate.addNumber(os.checkpointTimeMA.getAvg()); } loi.cpuPercentageMA += os.cpuNanosPMSMA.getAvg() / 10000; if (os.lastHeartbeat != null && (loi.lastHeartbeat == 0 || loi.lastHeartbeat > os.lastHeartbeat.getGeneratedTms())) { loi.lastHeartbeat = os.lastHeartbeat.getGeneratedTms(); } long currentWindowId = toWsWindowId(os.currentWindowId.get()); if (loi.currentWindowId == 0 || loi.currentWindowId > currentWindowId) { loi.currentWindowId = currentWindowId; } MutableInt count = loi.status.get(physicalOperator.getState().toString()); if (count == null) { count = new MutableInt(); loi.status.put(physicalOperator.getState().toString(), count); } count.increment(); if (physicalOperator.getRecoveryCheckpoint() != null) { long recoveryWindowId = toWsWindowId(physicalOperator.getRecoveryCheckpoint().windowId); if (loi.recoveryWindowId == 0 || loi.recoveryWindowId > recoveryWindowId) { loi.recoveryWindowId = recoveryWindowId; } } PTContainer container = physicalOperator.getContainer(); if (container != null) { String externalId = container.getExternalId(); if (externalId != null) { loi.containerIds.add(externalId); loi.hosts.add(container.host); } } } if (physicalOperators.size() > 0 && checkpointTimeAggregate.getAvg() != null) { loi.checkpointTimeMA = checkpointTimeAggregate.getAvg().longValue(); loi.counters = latestLogicalCounters.get(operator.getName()); loi.autoMetrics = latestLogicalMetrics.get(operator.getName()); } return loi; } private OperatorAggregationInfo fillOperatorAggregationInfo(OperatorMeta operator) { OperatorAggregationInfo oai = new OperatorAggregationInfo(); Collection<PTOperator> physicalOperators = getPhysicalPlan().getAllOperators(operator); if (physicalOperators.isEmpty()) { return null; } oai.name = operator.getName(); for (PTOperator physicalOperator : physicalOperators) { if (!physicalOperator.isUnifier()) { OperatorStatus os = physicalOperator.stats; oai.latencyMA.addNumber(os.latencyMA.getAvg()); oai.cpuPercentageMA.addNumber(os.cpuNanosPMSMA.getAvg() / 10000); oai.tuplesEmittedPSMA.addNumber(os.tuplesEmittedPSMA.get()); oai.tuplesProcessedPSMA.addNumber(os.tuplesProcessedPSMA.get()); oai.currentWindowId.addNumber(os.currentWindowId.get()); oai.recoveryWindowId.addNumber(toWsWindowId(physicalOperator.getRecoveryCheckpoint().windowId)); if (os.lastHeartbeat != null) { oai.lastHeartbeat.addNumber(os.lastHeartbeat.getGeneratedTms()); } oai.checkpointTime.addNumber(os.checkpointTimeMA.getAvg()); } } return oai; } private long calculateLatency(PTOperator operator) { long latency = operator.stats.latencyMA.getAvg(); long maxUnifierLatency = 0; for (PTOutput output : operator.getOutputs()) { for (PTInput input : output.sinks) { if (input.target.isUnifier()) { long thisUnifierLatency = calculateLatency(input.target); if (maxUnifierLatency < thisUnifierLatency) { maxUnifierLatency = thisUnifierLatency; } } } } return latency + maxUnifierLatency; } public List<StreamInfo> getStreamInfoList() { List<StreamInfo> infoList = new ArrayList<>(); for (PTContainer container : this.plan.getContainers()) { for (PTOperator operator : container.getOperators()) { List<PTOutput> outputs = operator.getOutputs(); for (PTOutput output : outputs) { StreamInfo si = new StreamInfo(); si.logicalName = output.logicalStream.getName(); si.source.operatorId = String.valueOf(operator.getId()); si.source.portName = output.portName; si.locality = output.logicalStream.getLocality(); for (PTInput input : output.sinks) { StreamInfo.Port p = new StreamInfo.Port(); p.operatorId = String.valueOf(input.target.getId()); if (input.target.isUnifier()) { p.portName = StreamingContainer.getUnifierInputPortName(input.portName, operator.getId(), output.portName); } else { p.portName = input.portName; } si.sinks.add(p); } infoList.add(si); } } } return infoList; } private static class RecordingRequestFilter implements Predicate<StramToNodeRequest> { static final Set<StramToNodeRequest.RequestType> MATCH_TYPES = Sets.newHashSet(StramToNodeRequest.RequestType.START_RECORDING, StramToNodeRequest.RequestType.STOP_RECORDING, StramToNodeRequest.RequestType.SYNC_RECORDING); @Override public boolean apply(@Nullable StramToNodeRequest input) { return input != null && MATCH_TYPES.contains(input.getRequestType()); } } private class SetOperatorPropertyRequestFilter implements Predicate<StramToNodeRequest> { final String propertyKey; SetOperatorPropertyRequestFilter(String key) { this.propertyKey = key; } @Override public boolean apply(@Nullable StramToNodeRequest input) { if (input == null) { return false; } if (input instanceof StramToNodeSetPropertyRequest) { return ((StramToNodeSetPropertyRequest)input).getPropertyKey().equals(propertyKey); } return false; } } private void updateOnDeployRequests(PTOperator p, Predicate<StramToNodeRequest> superseded, StramToNodeRequest newRequest) { // filter existing requests List<StramToNodeRequest> cloneRequests = new ArrayList<>(p.deployRequests.size()); for (StramToNodeRequest existingRequest : p.deployRequests) { if (!superseded.apply(existingRequest)) { cloneRequests.add(existingRequest); } } // add new request, if any if (newRequest != null) { cloneRequests.add(newRequest); } p.deployRequests = Collections.unmodifiableList(cloneRequests); } private StreamingContainerAgent getContainerAgentFromOperatorId(int operatorId) { PTOperator oper = plan.getAllOperators().get(operatorId); if (oper != null) { StreamingContainerAgent sca = containers.get(oper.getContainer().getExternalId()); if (sca != null) { return sca; } } // throw exception that propagates to web client throw new NotFoundException("Operator ID " + operatorId + " not found"); } public void startRecording(String id, int operId, String portName, long numWindows) { StreamingContainerAgent sca = getContainerAgentFromOperatorId(operId); StramToNodeStartRecordingRequest request = new StramToNodeStartRecordingRequest(); request.setOperatorId(operId); if (!StringUtils.isBlank(portName)) { request.setPortName(portName); } request.setNumWindows(numWindows); request.setId(id); sca.addOperatorRequest(request); PTOperator operator = plan.getAllOperators().get(operId); if (operator != null) { // restart on deploy updateOnDeployRequests(operator, new RecordingRequestFilter(), request); } } public void stopRecording(int operId, String portName) { StreamingContainerAgent sca = getContainerAgentFromOperatorId(operId); StramToNodeRequest request = new StramToNodeRequest(); request.setOperatorId(operId); if (!StringUtils.isBlank(portName)) { request.setPortName(portName); } request.setRequestType(StramToNodeRequest.RequestType.STOP_RECORDING); sca.addOperatorRequest(request); PTOperator operator = plan.getAllOperators().get(operId); if (operator != null) { // no stop on deploy, but remove existing start updateOnDeployRequests(operator, new RecordingRequestFilter(), null); } } public void syncStats() { statsRecorder.requestSync(); } public void syncEvents() { eventRecorder.requestSync(); } public void stopContainer(String containerId) { this.containerStopRequests.put(containerId, containerId); } public Recoverable getSetOperatorProperty(String operatorName, String propertyName, String propertyValue) { return new SetOperatorProperty(operatorName, propertyName, propertyValue); } public Recoverable getSetPhysicalOperatorProperty(int operatorId, String propertyName, String propertyValue) { return new SetPhysicalOperatorProperty(operatorId, propertyName, propertyValue); } public void setOperatorProperty(String operatorName, String propertyName, String propertyValue) { OperatorMeta logicalOperator = plan.getLogicalPlan().getOperatorMeta(operatorName); if (logicalOperator == null) { throw new IllegalArgumentException("Unknown operator " + operatorName); } writeJournal(new SetOperatorProperty(operatorName, propertyName, propertyValue)); setOperatorProperty(logicalOperator, propertyName, propertyValue); } private void setOperatorProperty(OperatorMeta logicalOperator, String propertyName, String propertyValue) { Map<String, String> properties = Collections.singletonMap(propertyName, propertyValue); LogicalPlanConfiguration.setOperatorProperties(logicalOperator.getOperator(), properties); List<PTOperator> operators = plan.getOperators(logicalOperator); for (PTOperator o : operators) { StramToNodeSetPropertyRequest request = new StramToNodeSetPropertyRequest(); request.setOperatorId(o.getId()); request.setPropertyKey(propertyName); request.setPropertyValue(propertyValue); addOperatorRequest(o, request); // re-apply to checkpointed state on deploy updateOnDeployRequests(o, new SetOperatorPropertyRequestFilter(propertyName), request); } // should probably not record it here because it's better to get confirmation from the operators first. // but right now, the operators do not give confirmation for the requests. so record it here for now. recordEventAsync(new StramEvent.SetOperatorPropertyEvent(logicalOperator.getName(), propertyName, propertyValue)); } /** * Set property on a physical operator. The property change is applied asynchronously on the deployed operator. * * @param operatorId * @param propertyName * @param propertyValue */ public void setPhysicalOperatorProperty(int operatorId, String propertyName, String propertyValue) { PTOperator o = this.plan.getAllOperators().get(operatorId); if (o == null) { return; } writeJournal(new SetPhysicalOperatorProperty(operatorId, propertyName, propertyValue)); setPhysicalOperatorProperty(o, propertyName, propertyValue); } private void setPhysicalOperatorProperty(PTOperator o, String propertyName, String propertyValue) { String operatorName = o.getName(); StramToNodeSetPropertyRequest request = new StramToNodeSetPropertyRequest(); request.setOperatorId(o.getId()); request.setPropertyKey(propertyName); request.setPropertyValue(propertyValue); addOperatorRequest(o, request); updateOnDeployRequests(o, new SetOperatorPropertyRequestFilter(propertyName), request); // should probably not record it here because it's better to get confirmation from the operators first. // but right now, the operators do not give confirmation for the requests. so record it here for now. recordEventAsync(new StramEvent.SetPhysicalOperatorPropertyEvent(operatorName, o.getId(), propertyName, propertyValue)); } @Override public void addOperatorRequest(PTOperator oper, StramToNodeRequest request) { StreamingContainerAgent sca = getContainerAgent(oper.getContainer().getExternalId()); // yarn may not assigned resource to the container yet if (sca != null) { sca.addOperatorRequest(request); } } /** * Send requests to change logger levels to all containers * * @param changedLoggers loggers that were changed. */ public void setLoggersLevel(Map<String, String> changedLoggers) { LOG.debug("change logger request"); StramToNodeChangeLoggersRequest request = new StramToNodeChangeLoggersRequest(); request.setTargetChanges(changedLoggers); for (StreamingContainerAgent stramChildAgent : containers.values()) { stramChildAgent.addOperatorRequest(request); } } public FutureTask<Object> getPhysicalOperatorProperty(int operatorId, String propertyName, long waitTime) { PTOperator o = this.plan.getAllOperators().get(operatorId); StramToNodeGetPropertyRequest request = new StramToNodeGetPropertyRequest(); request.setOperatorId(operatorId); request.setPropertyName(propertyName); addOperatorRequest(o, request); RequestHandler task = new RequestHandler(); task.requestId = nodeToStramRequestIds.incrementAndGet(); task.waitTime = waitTime; request.requestId = task.requestId; FutureTask<Object> future = new FutureTask<>(task); dispatch(future); return future; } public Attribute.AttributeMap getApplicationAttributes() { LogicalPlan lp = getLogicalPlan(); try { return lp.getAttributes().clone(); } catch (CloneNotSupportedException ex) { throw new RuntimeException("Cannot clone DAG attributes", ex); } } public Attribute.AttributeMap getOperatorAttributes(String operatorId) { OperatorMeta logicalOperator = plan.getLogicalPlan().getOperatorMeta(operatorId); if (logicalOperator == null) { throw new IllegalArgumentException("Invalid operatorId " + operatorId); } try { return logicalOperator.getAttributes().clone(); } catch (CloneNotSupportedException ex) { throw new RuntimeException("Cannot clone operator attributes", ex); } } public Attribute.AttributeMap getPortAttributes(String operatorId, String portName) { OperatorMeta logicalOperator = plan.getLogicalPlan().getOperatorMeta(operatorId); if (logicalOperator == null) { throw new IllegalArgumentException("Invalid operatorId " + operatorId); } Operators.PortMappingDescriptor portMap = new Operators.PortMappingDescriptor(); Operators.describe(logicalOperator.getOperator(), portMap); PortContextPair<InputPort<?>> inputPort = portMap.inputPorts.get(portName); if (inputPort != null) { InputPortMeta portMeta = logicalOperator.getMeta(inputPort.component); try { return portMeta.getAttributes().clone(); } catch (CloneNotSupportedException ex) { throw new RuntimeException("Cannot clone port attributes", ex); } } else { PortContextPair<OutputPort<?>> outputPort = portMap.outputPorts.get(portName); if (outputPort != null) { OutputPortMeta portMeta = logicalOperator.getMeta(outputPort.component); try { return portMeta.getAttributes().clone(); } catch (CloneNotSupportedException ex) { throw new RuntimeException("Cannot clone port attributes", ex); } } throw new IllegalArgumentException("Invalid port name " + portName); } } public LogicalPlan getLogicalPlan() { return plan.getLogicalPlan(); } /** * Asynchronously process the logical, physical plan and execution layer changes. * Caller can use the returned future to block until processing is complete. * * @param requests * @return future * @throws Exception */ public FutureTask<Object> logicalPlanModification(List<LogicalPlanRequest> requests) throws Exception { // delegate processing to dispatch thread FutureTask<Object> future = new FutureTask<>(new LogicalPlanChangeRunnable(requests)); dispatch(future); //LOG.info("Scheduled plan changes: {}", requests); return future; } private class LogicalPlanChangeRunnable implements java.util.concurrent.Callable<Object> { final List<LogicalPlanRequest> requests; private LogicalPlanChangeRunnable(List<LogicalPlanRequest> requests) { this.requests = requests; } @Override public Object call() throws Exception { // clone logical plan, for dry run and validation LOG.info("Begin plan changes: {}", requests); LogicalPlan lp = plan.getLogicalPlan(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); LogicalPlan.write(lp, bos); bos.flush(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); lp = LogicalPlan.read(bis); PlanModifier pm = new PlanModifier(lp); for (LogicalPlanRequest request : requests) { LOG.debug("Dry run plan change: {}", request); request.execute(pm); } lp.validate(); // perform changes on live plan pm = new PlanModifier(plan); for (LogicalPlanRequest request : requests) { request.execute(pm); // record an event for the request. however, we should probably record these when we get a confirmation. recordEventAsync(new StramEvent.ChangeLogicalPlanEvent(request)); } pm.applyChanges(StreamingContainerManager.this); LOG.info("Plan changes applied: {}", requests); return null; } } public CriticalPathInfo getCriticalPathInfo() { return criticalPathInfo; } private void checkpoint() throws IOException { if (recoveryHandler != null) { LOG.debug("Checkpointing state"); DataOutputStream out = recoveryHandler.rotateLog(); journal.setOutputStream(out); // checkpoint the state CheckpointState cs = new CheckpointState(); cs.finals = this.vars; cs.physicalPlan = this.plan; recoveryHandler.save(cs); } } @Override public void writeJournal(Recoverable operation) { try { if (journal != null) { journal.write(operation); } } catch (Exception e) { throw new IllegalStateException("Failed to write to journal " + operation, e); } } /** * Get the instance for the given application. If the application directory contains a checkpoint, the state will be restored. * * @param rh * @param dag * @param enableEventRecording * @return instance of {@link StreamingContainerManager} * @throws IOException */ public static StreamingContainerManager getInstance(RecoveryHandler rh, LogicalPlan dag, boolean enableEventRecording) throws IOException { try { CheckpointState checkpointedState = (CheckpointState)rh.restore(); StreamingContainerManager scm; if (checkpointedState == null) { scm = new StreamingContainerManager(dag, enableEventRecording, new SystemClock()); } else { // find better way to support final transient members PhysicalPlan plan = checkpointedState.physicalPlan; plan.getLogicalPlan().setAttribute(LogicalPlan.APPLICATION_ATTEMPT_ID, dag.getAttributes().get(LogicalPlan.APPLICATION_ATTEMPT_ID)); scm = new StreamingContainerManager(checkpointedState, enableEventRecording); for (Field f : plan.getClass().getDeclaredFields()) { if (f.getType() == PlanContext.class) { f.setAccessible(true); try { f.set(plan, scm); } catch (Exception e) { throw new RuntimeException("Failed to set " + f, e); } f.setAccessible(false); } } DataInputStream logStream = rh.getLog(); scm.journal.replay(logStream); logStream.close(); // restore checkpoint info plan.syncCheckpoints(scm.vars.windowStartMillis, scm.clock.getTime()); scm.committedWindowId = scm.updateCheckpoints(true); // at this point the physical plan has been fully restored // populate container agents for existing containers for (PTContainer c : plan.getContainers()) { if (c.getExternalId() != null) { LOG.debug("Restore container agent {} for {}", c.getExternalId(), c); StreamingContainerAgent sca = new StreamingContainerAgent(c, scm.newStreamingContainerContext(c), scm); scm.containers.put(c.getExternalId(), sca); } else { LOG.debug("Requesting new resource for {}", c.toIdStateString()); scm.requestContainer(c); } } } scm.recoveryHandler = rh; scm.checkpoint(); return scm; } catch (IOException e) { throw new IllegalStateException("Failed to read checkpointed state", e); } } private static class FinalVars implements java.io.Serializable { private static final long serialVersionUID = 3827310557521807024L; private final long windowStartMillis; private final int heartbeatTimeoutMillis; private final String appPath; private final int maxWindowsBehindForStats; private final boolean enableStatsRecording; private final int rpcLatencyCompensationSamples; private FinalVars(LogicalPlan dag, long tms) { Attribute.AttributeMap attributes = dag.getAttributes(); /* try to align to it to please eyes. */ windowStartMillis = tms - (tms % 1000); if (attributes.get(LogicalPlan.APPLICATION_PATH) == null) { throw new IllegalArgumentException("Not set: " + LogicalPlan.APPLICATION_PATH); } this.appPath = attributes.get(LogicalPlan.APPLICATION_PATH); if (attributes.get(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS) == null) { attributes.put(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS, 500); } if (attributes.get(LogicalPlan.CHECKPOINT_WINDOW_COUNT) == null) { attributes.put(LogicalPlan.CHECKPOINT_WINDOW_COUNT, 30000 / attributes.get(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS)); } this.heartbeatTimeoutMillis = dag.getValue(LogicalPlan.HEARTBEAT_TIMEOUT_MILLIS); this.maxWindowsBehindForStats = dag.getValue(LogicalPlan.STATS_MAX_ALLOWABLE_WINDOWS_LAG); this.enableStatsRecording = dag.getValue(LogicalPlan.ENABLE_STATS_RECORDING); this.rpcLatencyCompensationSamples = dag.getValue(LogicalPlan.RPC_LATENCY_COMPENSATION_SAMPLES); } private FinalVars(FinalVars other, LogicalPlan dag) { this.windowStartMillis = other.windowStartMillis; this.heartbeatTimeoutMillis = other.heartbeatTimeoutMillis; this.maxWindowsBehindForStats = other.maxWindowsBehindForStats; this.enableStatsRecording = other.enableStatsRecording; this.appPath = dag.getValue(LogicalPlan.APPLICATION_PATH); this.rpcLatencyCompensationSamples = other.rpcLatencyCompensationSamples; } } /** * The state that can be saved and used to recover the manager. */ static class CheckpointState implements Serializable { private static final long serialVersionUID = 3827310557521807024L; private FinalVars finals; private PhysicalPlan physicalPlan; /** * Modify previously saved state to allow for re-launch of application. */ public void setApplicationId(LogicalPlan newApp, Configuration conf) { LogicalPlan lp = physicalPlan.getLogicalPlan(); String appId = newApp.getValue(LogicalPlan.APPLICATION_ID); String oldAppId = lp.getValue(LogicalPlan.APPLICATION_ID); if (oldAppId == null) { throw new AssertionError("Missing original application id"); } lp.setAttribute(LogicalPlan.APPLICATION_ID, appId); lp.setAttribute(LogicalPlan.APPLICATION_PATH, newApp.assertAppPath()); lp.setAttribute(Context.DAGContext.LIBRARY_JARS, newApp.getValue(Context.DAGContext.LIBRARY_JARS)); lp.setAttribute(LogicalPlan.ARCHIVES, newApp.getValue(LogicalPlan.ARCHIVES)); this.finals = new FinalVars(finals, lp); StorageAgent sa = lp.getValue(OperatorContext.STORAGE_AGENT); if (sa instanceof AsyncFSStorageAgent) { // replace the default storage agent, if present AsyncFSStorageAgent fssa = (AsyncFSStorageAgent)sa; if (fssa.path.contains(oldAppId)) { fssa = new AsyncFSStorageAgent(fssa.path.replace(oldAppId, appId), conf); lp.setAttribute(OperatorContext.STORAGE_AGENT, fssa); } } else if (sa instanceof FSStorageAgent) { // replace the default storage agent, if present FSStorageAgent fssa = (FSStorageAgent)sa; if (fssa.path.contains(oldAppId)) { fssa = new FSStorageAgent(fssa.path.replace(oldAppId, appId), conf); lp.setAttribute(OperatorContext.STORAGE_AGENT, fssa); } } } } public interface RecoveryHandler { /** * Save snapshot. * * @param state * @throws IOException */ void save(Object state) throws IOException; /** * Restore snapshot. Must get/apply log after restore. * * @return snapshot * @throws IOException */ Object restore() throws IOException; /** * Backup log. Call before save. * * @return output stream * @throws IOException */ DataOutputStream rotateLog() throws IOException; /** * Get input stream for log. Call after restore. * * @return input stream * @throws IOException */ DataInputStream getLog() throws IOException; } private class RequestHandler implements Callable<Object> { /* * The unique requestId of the request */ public long requestId; /* * The maximum time this thread will wait for the response */ public long waitTime = 5000; @Override @SuppressWarnings("SleepWhileInLoop") public Object call() throws Exception { Object obj; long expiryTime = System.currentTimeMillis() + waitTime; while ((obj = commandResponse.getIfPresent(requestId)) == null && expiryTime > System.currentTimeMillis()) { Thread.sleep(100); LOG.debug("Polling for a response to request with Id {}", requestId); } if (obj != null) { commandResponse.invalidate(requestId); return obj; } return null; } } @VisibleForTesting protected Collection<Pair<Long, Map<String, Object>>> getLogicalMetrics(String operatorName) { if (logicalMetrics.get(operatorName) != null) { return Collections.unmodifiableCollection(logicalMetrics.get(operatorName)); } return null; } @VisibleForTesting protected Object getLogicalCounter(String operatorName) { return latestLogicalCounters.get(operatorName); } }
apache-2.0
jotaramirez90/Android-DesignPatterns
abstractfactory/src/main/java/com/jota/patterns/abstractfactory/model/CarCountry.java
184
package com.jota.patterns.abstractfactory.model; public class CarCountry extends Car { public CarCountry() { } @Override public String getType() { return "Country"; } }
apache-2.0
emre-aydin/hazelcast
hazelcast-sql-core/src/main/java/com/hazelcast/sql/impl/calcite/validate/HazelcastSqlConformance.java
2615
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.sql.impl.calcite.validate; import org.apache.calcite.sql.validate.SqlConformanceEnum; import org.apache.calcite.sql.validate.SqlDelegatingConformance; /** * The class that defines conformance level for Hazelcast SQL dialect. */ public final class HazelcastSqlConformance extends SqlDelegatingConformance { /** Singleton. */ public static final HazelcastSqlConformance INSTANCE = new HazelcastSqlConformance(); private HazelcastSqlConformance() { super(SqlConformanceEnum.DEFAULT); } @Override public boolean allowExplicitRowValueConstructor() { // Do not allow explicit row constructor: "ROW([vals])". return false; } @Override public boolean isLimitStartCountAllowed() { // Allow "LIMIT [start], [count]" syntax. return true; } @Override public boolean isGroupByAlias() { // Allow aliases in GROUP BY: "SELECT a AS b FROM table GROUP BY b". return true; } @Override public boolean isGroupByOrdinal() { // Allow ordinals in GROUP BY: "SELECT a AS b FROM table GROUP BY 1". return true; } @Override public boolean isHavingAlias() { // Allow aliases in HAVING, similar to example in "isGroupByAlias". return true; } @Override public boolean isFromRequired() { // FROM keyword is required as per SQL'2003 standard. return true; } @Override public boolean isMinusAllowed() { // Support "MINUS" in addition to "EXCEPT". return true; } @Override public boolean isPercentRemainderAllowed() { // Allow "A % B". return true; } @Override public boolean allowNiladicParentheses() { // Allow CURRENT_DATE() in addition to CURRENT_DATE. return true; } @Override public boolean isBangEqualAllowed() { // Allow "A != B" in addition to "A <> B". return true; } }
apache-2.0
smartsheet-platform/smartsheet-java-sdk
src/test/java/com/smartsheet/api/ResourceNotFoundExceptionTest.java
1361
package com.smartsheet.api; /* * #[license] * Smartsheet SDK for Java * %% * Copyright (C) 2014 Smartsheet * %% * 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] */ import com.smartsheet.api.models.Error; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ResourceNotFoundExceptionTest { @Before public void setUp() throws Exception { } @Test public void testResourceNotFoundException() { try{ Error error = new Error(); error.setErrorCode(1); error.setMessage("testing testing"); throw new ResourceNotFoundException(error); }catch(ResourceNotFoundException e){ assertEquals("testing testing",e.getMessage()); assertEquals(1, e.getErrorCode()); } } }
apache-2.0
saulbein/web3j
core/src/main/java/org/web3j/abi/datatypes/generated/Ufixed80x168.java
594
package org.web3j.abi.datatypes.generated; import java.math.BigInteger; import org.web3j.abi.datatypes.Ufixed; /** * <p>Auto generated code.<br> * <strong>Do not modifiy!</strong><br> * Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.</p> */ public class Ufixed80x168 extends Ufixed { public static final Ufixed80x168 DEFAULT = new Ufixed80x168(BigInteger.ZERO); public Ufixed80x168(BigInteger value) { super(80, 168, value); } public Ufixed80x168(int mBitSize, int nBitSize, BigInteger m, BigInteger n) { super(80, 168, m, n); } }
apache-2.0
IWSDevelopers/iws
iws-persistence/src/main/java/net/iaeste/iws/persistence/ViewsDao.java
3132
/* * Licensed to IAESTE A.s.b.l. (IAESTE) under one or more contributor * license agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. The Authors * (See the AUTHORS file distributed with this work) 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 net.iaeste.iws.persistence; import net.iaeste.iws.api.dtos.exchange.Employer; import net.iaeste.iws.api.enums.exchange.OfferState; import net.iaeste.iws.api.util.Page; import net.iaeste.iws.persistence.entities.GroupEntity; import net.iaeste.iws.persistence.views.DomesticOfferStatisticsView; import net.iaeste.iws.persistence.views.EmployerView; import net.iaeste.iws.persistence.views.ForeignOfferStatisticsView; import net.iaeste.iws.persistence.views.OfferSharedToGroupView; import net.iaeste.iws.persistence.views.OfferView; import net.iaeste.iws.persistence.views.SharedOfferView; import net.iaeste.iws.persistence.views.StudentView; import java.util.List; import java.util.Set; /** * This DAO contains the various views that exists, and is used mainly for * searches for Objects using a read-only database connection, i.e. no * transaction. * * @author Kim Jensen / last $Author:$ * @version $Revision:$ / $Date:$ * @since IWS 1.0 */ public interface ViewsDao { List<ForeignOfferStatisticsView> findForeignOfferStatistics(GroupEntity group, Integer year); List<DomesticOfferStatisticsView> findDomesticOfferStatistics(GroupEntity group, Integer year); EmployerView findEmployer(Long groupId, String externalId); List<EmployerView> findEmployers(Long groupId, Page page); List<EmployerView> findEmployers(Long groupId, Page page, String partialName); List<OfferView> findDomesticOffers(Authentication authentication, Integer exchangeYear, Set<OfferState> states, Boolean retrieveCurrentAndNextExchangeYear, Page page); List<OfferView> findDomesticOffersByOfferIds(Authentication authentication, Integer exchangeYear, List<String> offerIds); List<SharedOfferView> findSharedOffers(Authentication authentication, Integer exchangeYear, Set<OfferState> states, Boolean retrieveCurrentAndNextExchangeYear, Page page); List<SharedOfferView> findSharedOffersByOfferIds(Authentication authentication, Integer exchangeYear, List<String> offerIds); List<OfferSharedToGroupView> findSharedToGroup(Long parentId, Integer exchangeYear, List<String> externalOfferIds); List<StudentView> findStudentsForMemberGroup(Long groupId, Page page); List<String> findOfferRefNoForEmployers(List<Employer> employers); }
apache-2.0
qobel/esoguproject
spring-framework/spring-test/src/main/java/org/springframework/test/context/TestContext.java
3835
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context; import java.io.Serializable; import java.lang.reflect.Method; import org.springframework.context.ApplicationContext; import org.springframework.core.AttributeAccessor; import org.springframework.test.annotation.DirtiesContext.HierarchyMode; /** * {@code TestContext} encapsulates the context in which a test is executed, * agnostic of the actual testing framework in use. * * @author Sam Brannen * @since 2.5 */ public interface TestContext extends AttributeAccessor, Serializable { /** * Get the {@linkplain ApplicationContext application context} for this * test context, possibly cached. * <p>Implementations of this method are responsible for loading the * application context if the corresponding context has not already been * loaded, potentially caching the context as well. * @return the application context * @throws IllegalStateException if an error occurs while retrieving the * application context */ ApplicationContext getApplicationContext(); /** * Get the {@linkplain Class test class} for this test context. * @return the test class (never {@code null}) */ Class<?> getTestClass(); /** * Get the current {@linkplain Object test instance} for this test context. * <p>Note: this is a mutable property. * @return the current test instance (may be {@code null}) * @see #updateState(Object, Method, Throwable) */ Object getTestInstance(); /** * Get the current {@linkplain Method test method} for this test context. * <p>Note: this is a mutable property. * @return the current test method (may be {@code null}) * @see #updateState(Object, Method, Throwable) */ Method getTestMethod(); /** * Get the {@linkplain Throwable exception} that was thrown during execution * of the {@linkplain #getTestMethod() test method}. * <p>Note: this is a mutable property. * @return the exception that was thrown, or {@code null} if no * exception was thrown * @see #updateState(Object, Method, Throwable) */ Throwable getTestException(); /** * Call this method to signal that the {@linkplain ApplicationContext application * context} associated with this test context is <em>dirty</em> and should be * removed from the context cache. * <p>Do this if a test has modified the context &mdash; for example, by * modifying the state of a singleton bean, modifying the state of an embedded * database, etc. * @param hierarchyMode the context cache clearing mode to be applied if the * context is part of a hierarchy (may be {@code null}) */ void markApplicationContextDirty(HierarchyMode hierarchyMode); /** * Update this test context to reflect the state of the currently executing * test. * <p>Caution: concurrent invocations of this method might not be thread-safe, * depending on the underlying implementation. * @param testInstance the current test instance (may be {@code null}) * @param testMethod the current test method (may be {@code null}) * @param testException the exception that was thrown in the test method, or * {@code null} if no exception was thrown */ void updateState(Object testInstance, Method testMethod, Throwable testException); }
apache-2.0
hof/wstcp-text-proxy
src/main/java/org/red5/net/websocket/Constants.java
2188
/* * RED5 Open Source Flash Server - https://github.com/red5 * * Copyright 2006-2015 by respective authors (see below). 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 org.red5.net.websocket; /** * Convenience class for holding constants. * * @author Paul Gregoire */ public class Constants { public static final String MANAGER = "ws.manager"; public static final String SCOPE = "ws.scope"; public final static String CONNECTION = "ws.connection"; public final static String SESSION = "session"; public static final Object WS_HANDSHAKE = "ws.handshake"; public final static String WS_HEADER_KEY = "Sec-WebSocket-Key"; public final static String WS_HEADER_VERSION = "Sec-WebSocket-Version"; public final static String WS_HEADER_EXTENSIONS = "Sec-WebSocket-Extensions"; public final static String WS_HEADER_PROTOCOL = "Sec-WebSocket-Protocol"; public final static String HTTP_HEADER_HOST = "Host"; public final static String HTTP_HEADER_ORIGIN = "Origin"; public final static String HTTP_HEADER_USERAGENT = "User-Agent"; public final static String WS_HEADER_FORWARDED = "X-Forwarded-For"; public final static String WS_HEADER_REAL_IP = "X-Real-IP"; public final static String WS_HEADER_GENERIC_PREFIX = "X-"; public static final String URI_QS_PARAMETERS = "querystring-parameters"; // magic string for websockets public static final String WEBSOCKET_MAGIC_STRING = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; public static final byte[] CRLF = { 0x0d, 0x0a }; public static final byte[] END_OF_REQ = { 0x0d, 0x0a, 0x0d, 0x0a }; }
apache-2.0
wanforyou/GraduateWork
app/src/androidTest/java/com/tyut/himusic/ApplicationTest.java
347
package com.tyut.himusic; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
apache-2.0
jensgreiner/Miwok
app/src/main/java/com/example/android/miwok/Word.java
3058
package com.example.android.miwok; /** * {@link Word} represents a vocabulary word that the user wants to learn. * It contains a default translation and a Miwok translation and an image for that word. * Created by jens on 20.05.17. */ class Word { /** * Constant value that represents no image was provided for this word */ private static final int NO_IMAGE_PROVIDED = -1; // private attributes // Default translation for the word private final String mDefaultTranslation; // Miwok translation for the word private final String mMiwokTranslation; // Image as drawable resource ID for the icon private int mImageResourceId = NO_IMAGE_PROVIDED; // Sound as raw resource ID for the sound file @SuppressWarnings("CanBeFinal") private int mSoundResourceId; // Constructors /** * Creates a new Word object * * @param defaultTranslation is the word in a language that the user is already familiar with * @param miwokTranslation is the word in the Miwok language */ public Word(String defaultTranslation, String miwokTranslation, int soundResourceId) { mDefaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; mSoundResourceId = soundResourceId; } /** * Overloaded constructor to create a Word object with an image * * @param defaultTranslation is the word in a language that the user is already familiar with * @param miwokTranslation is the word in the Miwok language * @param imageResourceId is the image corresponding to the word * @param soundResourceId is the sound file corresponding to the word */ public Word(String defaultTranslation, String miwokTranslation, int imageResourceId, int soundResourceId) { mDefaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; mImageResourceId = imageResourceId; mSoundResourceId = soundResourceId; } // Getters public String getDefaultTranslation() { return mDefaultTranslation; } public String getMiwokTranslation() { return mMiwokTranslation; } public int getImageResourceId() { return mImageResourceId; } public int getSoundResourceId() { return mSoundResourceId; } /** * Returns whether or not there is an image for this word. * * @return true if there is an image resource id set and false, if not */ // Public methods public boolean hasImage() { return mImageResourceId != NO_IMAGE_PROVIDED; } /** * @return a string representation of the objects content */ @Override public String toString() { return "Word{" + "mDefaultTranslation='" + mDefaultTranslation + '\'' + ", mMiwokTranslation='" + mMiwokTranslation + '\'' + ", mImageResourceId=" + mImageResourceId + ", mSoundResourceId=" + mSoundResourceId + '}'; } }
apache-2.0
adbrucker/SecureBPMN
designer/src/org.activiti.designer.model/src/main/java/org/eclipse/securebpmn2/User.java
1698
/** * <copyright> * * Copyright (c) 2010 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation * * </copyright> */ package org.eclipse.securebpmn2; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>User</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.eclipse.securebpmn2.User#getUserName <em>User Name</em>}</li> * </ul> * </p> * * @see org.eclipse.securebpmn2.Securebpmn2Package#getUser() * @model * @generated */ public interface User extends Subject { /** * Returns the value of the '<em><b>User Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>User Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>User Name</em>' attribute. * @see #setUserName(String) * @see org.eclipse.securebpmn2.Securebpmn2Package#getUser_UserName() * @model * @generated */ String getUserName(); /** * Sets the value of the '{@link org.eclipse.securebpmn2.User#getUserName <em>User Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>User Name</em>' attribute. * @see #getUserName() * @generated */ void setUserName(String value); } // User
apache-2.0
bobmcwhirter/drools
drools-core/src/main/java/org/drools/ruleflow/core/validation/RuleFlowProcessValidator.java
21705
package org.drools.ruleflow.core.validation; /* * Copyright 2005 JBoss 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. */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.drools.process.core.Process; import org.drools.process.core.Work; import org.drools.process.core.context.variable.Variable; import org.drools.process.core.validation.ProcessValidationError; import org.drools.process.core.validation.ProcessValidator; import org.drools.process.core.validation.impl.ProcessValidationErrorImpl; import org.drools.ruleflow.core.RuleFlowProcess; import org.drools.workflow.core.Connection; import org.drools.workflow.core.Node; import org.drools.workflow.core.impl.DroolsConsequenceAction; import org.drools.workflow.core.node.ActionNode; import org.drools.workflow.core.node.CompositeNode; import org.drools.workflow.core.node.EndNode; import org.drools.workflow.core.node.EventNode; import org.drools.workflow.core.node.ForEachNode; import org.drools.workflow.core.node.Join; import org.drools.workflow.core.node.MilestoneNode; import org.drools.workflow.core.node.RuleSetNode; import org.drools.workflow.core.node.Split; import org.drools.workflow.core.node.StartNode; import org.drools.workflow.core.node.SubProcessNode; import org.drools.workflow.core.node.WorkItemNode; import org.mvel.ErrorDetail; import org.mvel.ParserContext; import org.mvel.compiler.ExpressionCompiler; /** * Default implementation of a RuleFlow validator. * * @author <a href="mailto:kris_verlaenen@hotmail.com">Kris Verlaenen</a> */ public class RuleFlowProcessValidator implements ProcessValidator { // TODO: make this pluggable // TODO: extract generic process stuff and generic workflow stuff private static RuleFlowProcessValidator instance; private boolean startNodeFound; private boolean endNodeFound; private RuleFlowProcessValidator() { } public static RuleFlowProcessValidator getInstance() { if ( instance == null ) { instance = new RuleFlowProcessValidator(); } return instance; } public ProcessValidationError[] validateProcess(final RuleFlowProcess process) { final List<ProcessValidationError> errors = new ArrayList<ProcessValidationError>(); if (process.getName() == null) { errors.add(new ProcessValidationErrorImpl(process, "Process has no name.")); } if (process.getId() == null || "".equals(process.getId())) { errors.add(new ProcessValidationErrorImpl(process, "Process has no id.")); } if ( process.getPackageName() == null || "".equals( process.getPackageName() ) ) { errors.add(new ProcessValidationErrorImpl(process, "Process has no package name.")); } // check start node of process if ( process.getStart() == null ) { errors.add(new ProcessValidationErrorImpl(process, "Process has no start node.")); } startNodeFound = false; endNodeFound = false; final Node[] nodes = process.getNodes(); validateNodes(nodes, errors, process); if (!startNodeFound) { errors.add(new ProcessValidationErrorImpl(process, "Process has no start node.")); } if (!endNodeFound) { errors.add(new ProcessValidationErrorImpl(process, "Process has no end node.")); } for (final Iterator<Variable> it = process.getVariableScope().getVariables().iterator(); it.hasNext(); ) { final Variable variable = it.next(); if (variable.getType() == null) { errors.add(new ProcessValidationErrorImpl(process, "Variable '" + variable.getName() + "' has no type.")); } } checkAllNodesConnectedToStart(process, errors); return errors.toArray(new ProcessValidationError[errors.size()]); } private void validateNodes(Node[] nodes, List<ProcessValidationError> errors, RuleFlowProcess process) { for ( int i = 0; i < nodes.length; i++ ) { final Node node = nodes[i]; if (node instanceof StartNode) { final StartNode startNode = (StartNode) node; startNodeFound = true; if (startNode.getTo() == null) { errors.add(new ProcessValidationErrorImpl(process, "Start node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection.")); } } else if (node instanceof EndNode) { final EndNode endNode = (EndNode) node; endNodeFound = true; if (endNode.getFrom() == null) { errors.add(new ProcessValidationErrorImpl(process, "End node '" + node.getName() + "' [" + node.getId() + "] has no incoming connection.")); } } else if (node instanceof RuleSetNode) { final RuleSetNode ruleSetNode = (RuleSetNode) node; if (ruleSetNode.getFrom() == null) { errors.add(new ProcessValidationErrorImpl(process, "RuleSet node '" + node.getName() + "' [" + node.getId() + "] has no incoming connection.")); } if (ruleSetNode.getTo() == null) { errors.add(new ProcessValidationErrorImpl(process, "RuleSet node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection.")); } final String ruleFlowGroup = ruleSetNode.getRuleFlowGroup(); if (ruleFlowGroup == null || "".equals(ruleFlowGroup)) { errors.add( new ProcessValidationErrorImpl(process, "RuleSet node '" + node.getName() + "' [" + node.getId() + "] has no ruleflow-group.")); } } else if (node instanceof Split) { final Split split = (Split) node; if (split.getType() == Split.TYPE_UNDEFINED) { errors.add(new ProcessValidationErrorImpl(process, "Split node '" + node.getName() + "' [" + node.getId() + "] has no type.")); } if (split.getFrom() == null) { errors.add(new ProcessValidationErrorImpl(process, "Split node '" + node.getName() + "' [" + node.getId() + "] has no incoming connection.")); } if (split.getDefaultOutgoingConnections().size() < 2) { errors.add(new ProcessValidationErrorImpl(process, "Split node '" + node.getName() + "' [" + node.getId() + "] does not have more than one outgoing connection: " + split.getOutgoingConnections().size() + ".")); } if (split.getType() == Split.TYPE_XOR || split.getType() == Split.TYPE_OR ) { for ( final Iterator<Connection> it = split.getDefaultOutgoingConnections().iterator(); it.hasNext(); ) { final Connection connection = it.next(); if (split.getConstraint(connection) == null) { errors.add(new ProcessValidationErrorImpl(process, "Split node '" + node.getName() + "' [" + node.getId() + "] does not have a constraint for " + connection.toString() + ".")); } } } } else if ( node instanceof Join ) { final Join join = (Join) node; if (join.getType() == Join.TYPE_UNDEFINED) { errors.add(new ProcessValidationErrorImpl(process, "Join node '" + node.getName() + "' [" + node.getId() + "] has no type.")); } if (join.getDefaultIncomingConnections().size() < 2) { errors.add(new ProcessValidationErrorImpl(process, "Join node '" + node.getName() + "' [" + node.getId() + "] does not have more than one incoming connection: " + join.getIncomingConnections().size() + ".")); } if (join.getTo() == null) { errors.add(new ProcessValidationErrorImpl(process, "Join node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection.")); } } else if (node instanceof MilestoneNode) { final MilestoneNode milestone = (MilestoneNode) node; if (milestone.getFrom() == null) { errors.add(new ProcessValidationErrorImpl(process, "Milestone node '" + node.getName() + "' [" + node.getId() + "] has no incoming connection.")); } if (milestone.getTo() == null) { errors.add( new ProcessValidationErrorImpl(process, "Milestone node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection.")); } if (milestone.getConstraint() == null) { errors.add( new ProcessValidationErrorImpl(process, "Milestone node '" + node.getName() + "' [" + node.getId() + "] has no constraint.")); } } else if (node instanceof SubProcessNode) { final SubProcessNode subProcess = (SubProcessNode) node; if (subProcess.getFrom() == null) { errors.add(new ProcessValidationErrorImpl(process, "SubProcess node '" + node.getName() + "' [" + node.getId() + "] has no incoming connection.")); } if (subProcess.getTo() == null) { errors.add(new ProcessValidationErrorImpl(process, "SubProcess node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection.")); } if (subProcess.getProcessId() == null) { errors.add(new ProcessValidationErrorImpl(process, "SubProcess node '" + node.getName() + "' [" + node.getId() + "] has no process id.")); } } else if (node instanceof ActionNode) { final ActionNode actionNode = (ActionNode) node; if (actionNode.getFrom() == null) { errors.add(new ProcessValidationErrorImpl(process, "Action node '" + node.getName() + "' [" + node.getId() + "] has no incoming connection.")); } if (actionNode.getTo() == null) { errors.add(new ProcessValidationErrorImpl(process, "Action node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection.")); } if (actionNode.getAction() == null) { errors.add(new ProcessValidationErrorImpl(process, "Action node '" + node.getName() + "' [" + node.getId() + "] has no action.")); } else { if (actionNode.getAction() instanceof DroolsConsequenceAction) { DroolsConsequenceAction droolsAction = (DroolsConsequenceAction) actionNode.getAction(); String actionString = droolsAction.getConsequence(); if (actionString == null) { errors.add(new ProcessValidationErrorImpl(process, "Action node '" + node.getName() + "' [" + node.getId() + "] has empty action.")); } else { try { ExpressionCompiler compiler = new ExpressionCompiler(actionString); compiler.setVerifying(true); ParserContext parserContext = new ParserContext(); //parserContext.setStrictTypeEnforcement(true); compiler.compile(parserContext); List<ErrorDetail> mvelErrors = parserContext.getErrorList(); if (mvelErrors != null) { for (Iterator<ErrorDetail> iterator = mvelErrors.iterator(); iterator.hasNext(); ) { ErrorDetail error = iterator.next(); errors.add(new ProcessValidationErrorImpl(process, "Action node '" + node.getName() + "' [" + node.getId() + "] has invalid action: " + error.getMessage() + ".")); } } } catch (Throwable t) { errors.add(new ProcessValidationErrorImpl(process, "Action node '" + node.getName() + "' [" + node.getId() + "] has invalid action: " + t.getMessage() + ".")); } } } } } else if (node instanceof WorkItemNode) { final WorkItemNode workItemNode = (WorkItemNode) node; if (workItemNode.getFrom() == null) { errors.add(new ProcessValidationErrorImpl(process, "WorkItem node '" + node.getName() + "' [" + node.getId() + "] has no incoming connection.")); } if (workItemNode.getTo() == null) { errors.add(new ProcessValidationErrorImpl(process, "WorkItem node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection.")); } if (workItemNode.getWork() == null) { errors.add(new ProcessValidationErrorImpl(process, "WorkItem node '" + node.getName() + "' [" + node.getId() + "] has no work specified.")); } else { Work work = workItemNode.getWork(); if (work.getName() == null) { errors.add(new ProcessValidationErrorImpl(process, "WorkItem node '" + node.getName() + "' [" + node.getId() + "] has no work name.")); } } } else if (node instanceof ForEachNode) { final ForEachNode forEachNode = (ForEachNode) node; String variableName = forEachNode.getVariableName(); if (variableName == null || "".equals(variableName)) { errors.add(new ProcessValidationErrorImpl(process, "ForEach node '" + node.getName() + "' [" + node.getId() + "] has no variable name")); } String collectionExpression = forEachNode.getCollectionExpression(); if (collectionExpression == null || "".equals(collectionExpression)) { errors.add(new ProcessValidationErrorImpl(process, "ForEach node '" + node.getName() + "' [" + node.getId() + "] has no collection expression")); } if (forEachNode.getIncomingConnections(Node.CONNECTION_DEFAULT_TYPE).size() == 0) { errors.add(new ProcessValidationErrorImpl(process, "ForEach node '" + node.getName() + "' [" + node.getId() + "] has no incoming connection")); } if (forEachNode.getOutgoingConnections(Node.CONNECTION_DEFAULT_TYPE).size() == 0) { errors.add(new ProcessValidationErrorImpl(process, "ForEach node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection")); } if (forEachNode.getLinkedIncomingNode(Node.CONNECTION_DEFAULT_TYPE) == null) { errors.add(new ProcessValidationErrorImpl(process, "ForEach node '" + node.getName() + "' [" + node.getId() + "] has no linked start node")); } if (forEachNode.getLinkedOutgoingNode(Node.CONNECTION_DEFAULT_TYPE) == null) { errors.add(new ProcessValidationErrorImpl(process, "ForEach node '" + node.getName() + "' [" + node.getId() + "] has no linked end node")); } validateNodes(forEachNode.getNodes(), errors, process); } else if (node instanceof CompositeNode) { final CompositeNode compositeNode = (CompositeNode) node; for (String inType: compositeNode.getLinkedIncomingNodes().keySet()) { if (compositeNode.getIncomingConnections(inType).size() == 0) { errors.add(new ProcessValidationErrorImpl(process, "Composite node '" + node.getName() + "' [" + node.getId() + "] has no incoming connection for type " + inType)); } } for (String outType: compositeNode.getLinkedOutgoingNodes().keySet()) { if (compositeNode.getOutgoingConnections(outType).size() == 0) { errors.add(new ProcessValidationErrorImpl(process, "Composite node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection for type " + outType)); } } validateNodes(compositeNode.getNodes(), errors, process); } else if (node instanceof EventNode) { final EventNode eventNode = (EventNode) node; if (eventNode.getEventFilters().size() == 0) { errors.add(new ProcessValidationErrorImpl(process, "Event node '" + node.getName() + "' [" + node.getId() + "] should specify an event type")); } if (eventNode.getOutgoingConnections(Node.CONNECTION_DEFAULT_TYPE).size() == 0) { errors.add(new ProcessValidationErrorImpl(process, "Event node '" + node.getName() + "' [" + node.getId() + "] has no outgoing connection")); } } } } private void checkAllNodesConnectedToStart(final RuleFlowProcess process, final List<ProcessValidationError> errors) { final Map<Node, Boolean> processNodes = new HashMap<Node, Boolean>(); final Node[] nodes = process.getNodes(); List<Node> eventNodes = new ArrayList<Node>(); for (int i = 0; i < nodes.length; i++) { final Node node = nodes[i]; processNodes.put(node, Boolean.FALSE); if (node instanceof EventNode) { eventNodes.add(node); } } final Node start = process.getStart(); if (start != null) { processNode(start, processNodes); } for (Node eventNode: eventNodes) { processNode(eventNode, processNodes); } for ( final Iterator<Node> it = processNodes.keySet().iterator(); it.hasNext(); ) { final Node node = it.next(); if (Boolean.FALSE.equals(processNodes.get(node))) { errors.add(new ProcessValidationErrorImpl(process, "Node '" + node.getName() + "' [" + node.getId() + "] has no connection to the start node.")); } } } private void processNode(final Node node, final Map<Node, Boolean> nodes) { if (!nodes.containsKey(node) ) { throw new IllegalStateException("A process node is connected with a node that does not belong to the process."); } final Boolean prevValue = (Boolean) nodes.put(node, Boolean.TRUE); if (prevValue == Boolean.FALSE) { for (final Iterator<List<Connection>> it = node.getOutgoingConnections().values().iterator(); it.hasNext(); ) { final List<Connection> list = it.next(); for (final Iterator<Connection> it2 = list.iterator(); it2.hasNext(); ) { processNode(it2.next().getTo(), nodes); } } } } public ProcessValidationError[] validateProcess(Process process) { if (!(process instanceof RuleFlowProcess)) { throw new IllegalArgumentException( "This validator can only validate ruleflow processes!"); } return validateProcess((RuleFlowProcess) process); } }
apache-2.0
ocpsoft/regex-tester
src/main/java/org/ocpsoft/tutorial/regex/server/RegexParserImpl.java
6109
package org.ocpsoft.tutorial.regex.server; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.enterprise.context.RequestScoped; import org.jboss.errai.bus.server.annotations.Service; import org.ocpsoft.tutorial.regex.client.shared.Group; import org.ocpsoft.tutorial.regex.client.shared.ParseTools; import org.ocpsoft.tutorial.regex.client.shared.ParseTools.CaptureFilter; import org.ocpsoft.tutorial.regex.client.shared.ParseTools.CaptureType; import org.ocpsoft.tutorial.regex.client.shared.ParseTools.CapturingGroup; import org.ocpsoft.tutorial.regex.client.shared.RegexException; import org.ocpsoft.tutorial.regex.client.shared.RegexParser; import org.ocpsoft.tutorial.regex.client.shared.RegexRequest; import org.ocpsoft.tutorial.regex.client.shared.RegexResult; @Service @RequestScoped public class RegexParserImpl implements RegexParser { private static final long REGEX_TIMOUT_MS = 5000; @Override public RegexResult parse(final RegexRequest request) { final RegexResult result = new RegexResult(); Runnable runnable = new Runnable() { @Override public void run() { result.setText(request.getText()); CharSequence text = new InterruptibleCharSequence(request.getText()); Matcher matcher = null; String replacement = request.getReplacement(); String regex = request.getRegex(); if (text != null && text.length() > 0) { try { if (regex != null) { matcher = Pattern.compile(regex).matcher(text); } } catch (Exception e) { result.setError(e.getMessage()); } List<CapturingGroup> fragments = ParseTools.extractCaptures(CaptureType.PAREN, regex, new CaptureFilter() { @Override public boolean accept(CapturingGroup group) { String captured = new String(group.getCaptured()); return !captured.startsWith("?"); } }); if (matcher != null) { matcher.reset(); if (matcher.matches()) { result.setMatches(matcher.matches()); result.getGroups().clear(); for (int i = 0; i < matcher.groupCount(); i++) { int start = matcher.start(i + 1); int end = matcher.end(i + 1); if (start != -1 && end != -1) result.getGroups().add(new Group(fragments.get(i), start, end)); } StringBuffer replaced = new StringBuffer(); if (replacement != null && !replacement.isEmpty()) { matcher.appendReplacement(replaced, request.getReplacement()); result.setReplaced(replaced.toString()); } } else { matcher.reset(); while (matcher.find()) { Group defaultGroup = new Group( new CapturingGroup(("(" + regex + ")").toCharArray(), 0, regex.length() + 1), matcher.start(), matcher.end()); result.getGroups().add(defaultGroup); for (int i = 0; i < matcher.groupCount(); i++) { int start = matcher.start(i + 1); int end = matcher.end(i + 1); if ((start != -1 && end != -1) && (defaultGroup.getStart() != start || defaultGroup.getEnd() != end)) { result.getGroups().add(new Group(fragments.get(i), start, end)); } } } if (replacement != null && !replacement.isEmpty()) result.setReplaced(matcher.replaceAll(replacement)); } } } } }; long startTime = System.currentTimeMillis(); Thread thread = new Thread(runnable); thread.start(); try { while (thread.isAlive() && (System.currentTimeMillis() - startTime < REGEX_TIMOUT_MS)) { Thread.sleep(50); } if (thread.isAlive()) { thread.interrupt(); Thread.sleep(1000); result.setMatches(false); result.setReplaced(""); result.setText(""); result.setError("Regex processing timed out."); } } catch (InterruptedException e) { throw new RuntimeException(e); } return result; } // TODO add this as an option? public String javaMode(String regex) { StringBuilder result = new StringBuilder(); int count = 0; for (int i = 0; i < regex.length(); i++) { char c = regex.charAt(i); if (c == '\\') { count++; } if (count % 2 == 1) { if (c != '\\') { if (i + 1 <= regex.length()) { throw new RegexException("Unterminated escape sequence at character " + i + ": " + result); } } else if (i + 1 == regex.length()) { throw new RegexException("Unterminated escape sequence at character " + i + ": " + result); } } result.append(c); } return result.toString().replaceAll("\\\\\\\\", "\\\\"); } }
apache-2.0
52North/topology-serialization-framework
scratch/src/main/java/de/n52/tsf/scratch/geotools/GeoToolsTest.java
3677
package de.n52.tsf.scratch.geotools; import org.geotools.coverage.grid.GridCoverage2D; import org.geotools.coverage.grid.GridCoverageFactory; import org.geotools.coverage.grid.GridEnvelope2D; import org.geotools.coverage.grid.GridGeometry2D; import org.geotools.coverage.grid.io.AbstractGridFormat; import org.geotools.coverage.grid.io.GridCoverage2DReader; import org.geotools.coverage.grid.io.GridFormatFinder; import org.geotools.coverage.grid.io.imageio.IIOMetadataDumper; import org.geotools.gce.geotiff.GeoTiffReader; import org.geotools.gce.geotiff.GeoTiffWriter; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.opengis.coverage.grid.GridCoordinates; import org.opengis.coverage.grid.GridEnvelope; import org.opengis.referencing.operation.TransformException; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class GeoToolsTest { public static void main (String[] args) throws IOException, TransformException { ClassLoader classLoader = GeoToolsTest.class.getClassLoader(); //source geo.tiff - https://github.com/geotools/geotools/tree/master/modules/plugin/geotiff/src/test/resources/org/geotools/gce/geotiff/test-data File file = new File(classLoader.getResource("geotif/geo.tiff").getFile()); extractPoints(file); createGeotif(10,10,1); } public static void extractPoints(File file) throws TransformException, IOException { AbstractGridFormat format = GridFormatFinder.findFormat(file); GridCoverage2DReader reader = format.getReader(file); GridEnvelope dimensions = reader.getOriginalGridRange(); GridCoordinates maxDimensions = dimensions.getHigh(); int w = maxDimensions.getCoordinateValue(0) + 1; int h = maxDimensions.getCoordinateValue(1) + 1; System.out.println(maxDimensions.getCoordinateValue(0) + ":" + maxDimensions.getCoordinateValue(1)); GridCoverage2D coverage = reader.read(null); GridGeometry2D geometry = coverage.getGridGeometry(); System.out.println(coverage.getRenderedImage().getColorModel().getColorSpace().getType()); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { org.geotools.geometry.Envelope2D pixelEnvelop = geometry.gridToWorld(new GridEnvelope2D(i, j, 1, 1)); double latitude = pixelEnvelop.getCenterX(); double longitude = pixelEnvelop.getCenterY(); System.out.println(latitude + ":" + longitude); } } } public static void createGeotif(int x, int y, int c) throws IOException { ClassLoader classLoader = GeoToolsTest.class.getClassLoader(); //source geo.tiff - https://github.com/geotools/geotools/tree/master/modules/plugin/geotiff/src/test/resources/org/geotools/gce/geotiff/test-data File file = new File(classLoader.getResource("geotif/test.tif").getFile()); // write down a fake geotiff with non-standard CRS GridCoverageFactory factory = new GridCoverageFactory(); BufferedImage bi = new BufferedImage(x, y, c); ReferencedEnvelope envelope = new ReferencedEnvelope(0, x, 0, y, DefaultGeographicCRS.WGS84); GridCoverage2D test = factory.create("test", bi, envelope); GeoTiffWriter writer = new GeoTiffWriter(file); writer.write(test, null); writer.dispose(); // read final GeoTiffReader reader = new GeoTiffReader(file); System.out.println(reader.getCrs()); } }
apache-2.0
linkedin/pinot
pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/WebApplicationExceptionMapper.java
2456
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.controller.api.resources; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.apache.pinot.spi.utils.JsonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Provider public class WebApplicationExceptionMapper implements ExceptionMapper<Throwable> { private static final Logger LOGGER = LoggerFactory.getLogger(WebApplicationExceptionMapper.class); @Override public Response toResponse(Throwable t) { int status = 500; if (!(t instanceof WebApplicationException)) { LOGGER.error("Server error: ", t); } else { status = ((WebApplicationException) t).getResponse().getStatus(); } ErrorInfo einfo = new ErrorInfo(status, t.getMessage()); try { return Response.status(status).entity(JsonUtils.objectToString(einfo)).type(MediaType.APPLICATION_JSON).build(); } catch (JsonProcessingException e) { String err = String.format("{\"status\":%d, \"error\":%s}", einfo.code, einfo.error); return Response.status(status).entity(err).type(MediaType.APPLICATION_JSON).build(); } } public static class ErrorInfo { @JsonCreator public ErrorInfo(@JsonProperty("code") int code, @JsonProperty("error") String message) { this.code = code; this.error = message; } public int code; public String error; } }
apache-2.0
jexp/idea2
xml/dom-openapi/src/com/intellij/util/xml/ui/CommittableUtil.java
1092
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.util.xml.ui; import org.jetbrains.annotations.Nullable; /** * @author peter */ public class CommittableUtil { public void commit(Committable committable) { committable.commit(); } public void queueReset(Committable committable) { committable.reset(); } public static void updateHighlighting(@Nullable Committable committable) { if (committable instanceof Highlightable) { ((Highlightable)committable).updateHighlighting(); } } }
apache-2.0
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/stream/WrappedInputStream.java
1673
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.commons.io.stream; import java.io.FilterInputStream; import java.io.InputStream; import javax.annotation.Nonnull; import com.helger.commons.ValueEnforcer; import com.helger.commons.string.ToStringGenerator; /** * A wrapper around another {@link FilterInputStream} to make the wrapped * {@link InputStream} accessible. * * @author Philip Helger */ public class WrappedInputStream extends FilterInputStream { /** * @param aWrappedIS * The input stream to be wrapped. May not be <code>null</code>. */ public WrappedInputStream (@Nonnull final InputStream aWrappedIS) { super (ValueEnforcer.notNull (aWrappedIS, "WrappedInputStream")); } /** * @return The input stream provided in the constructor. Never * <code>null</code>. */ @Nonnull public final InputStream getWrappedInputStream () { return in; } @Override public String toString () { return new ToStringGenerator (this).append ("wrappedIS", in).getToString (); } }
apache-2.0
Penitence1992/webCodeG
src/com/penitence/service/PropertiesGetter.java
752
package com.penitence.service; import java.io.IOException; import java.util.Properties; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; public class PropertiesGetter { private static Resource resource = new ClassPathResource("resource.properties"); private static Properties props = null; public PropertiesGetter (){ try{ props = PropertiesLoaderUtils.loadProperties(resource); }catch(Exception e){ e.printStackTrace(); } } @SuppressWarnings("unchecked") protected <T> T getPropertiesValue (String key){ return (T) props.get(key); } }
apache-2.0
alipayhuber/hack-hbase
hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.java
23371
/** * * 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.regionserver; import java.io.IOException; import java.util.NavigableSet; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.Filter.ReturnCode; import org.apache.hadoop.hbase.io.TimeRange; import org.apache.hadoop.hbase.regionserver.DeleteTracker.DeleteResult; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import com.google.common.base.Preconditions; /** * A query matcher that is specifically designed for the scan case. */ @InterfaceAudience.Private public class ScanQueryMatcher { // Optimization so we can skip lots of compares when we decide to skip // to the next row. private boolean stickyNextRow; private final byte[] stopRow; private final TimeRange tr; private final Filter filter; /** Keeps track of deletes */ private final DeleteTracker deletes; /* * The following three booleans define how we deal with deletes. * There are three different aspects: * 1. Whether to keep delete markers. This is used in compactions. * Minor compactions always keep delete markers. * 2. Whether to keep deleted rows. This is also used in compactions, * if the store is set to keep deleted rows. This implies keeping * the delete markers as well. * In this case deleted rows are subject to the normal max version * and TTL/min version rules just like "normal" rows. * 3. Whether a scan can do time travel queries even before deleted * marker to reach deleted rows. */ /** whether to retain delete markers */ private boolean retainDeletesInOutput; /** whether to return deleted rows */ private final boolean keepDeletedCells; /** whether time range queries can see rows "behind" a delete */ private final boolean seePastDeleteMarkers; /** Keeps track of columns and versions */ private final ColumnTracker columns; /** Key to seek to in memstore and StoreFiles */ private final KeyValue startKey; /** Row comparator for the region this query is for */ private final KeyValue.KVComparator rowComparator; /* row is not private for tests */ /** Row the query is on */ byte [] row; int rowOffset; short rowLength; /** * Oldest put in any of the involved store files * Used to decide whether it is ok to delete * family delete marker of this store keeps * deleted KVs. */ private final long earliestPutTs; /** readPoint over which the KVs are unconditionally included */ protected long maxReadPointToTrackVersions; private byte[] dropDeletesFromRow = null, dropDeletesToRow = null; /** * This variable shows whether there is an null column in the query. There * always exists a null column in the wildcard column query. * There maybe exists a null column in the explicit column query based on the * first column. * */ private boolean hasNullColumn = true; // By default, when hbase.hstore.time.to.purge.deletes is 0ms, a delete // marker is always removed during a major compaction. If set to non-zero // value then major compaction will try to keep a delete marker around for // the given number of milliseconds. We want to keep the delete markers // around a bit longer because old puts might appear out-of-order. For // example, during log replication between two clusters. // // If the delete marker has lived longer than its column-family's TTL then // the delete marker will be removed even if time.to.purge.deletes has not // passed. This is because all the Puts that this delete marker can influence // would have also expired. (Removing of delete markers on col family TTL will // not happen if min-versions is set to non-zero) // // But, if time.to.purge.deletes has not expired then a delete // marker will not be removed just because there are no Puts that it is // currently influencing. This is because Puts, that this delete can // influence. may appear out of order. private final long timeToPurgeDeletes; private final boolean isUserScan; private final boolean isReversed; /** * Construct a QueryMatcher for a scan * @param scan * @param scanInfo The store's immutable scan info * @param columns * @param scanType Type of the scan * @param earliestPutTs Earliest put seen in any of the store files. * @param oldestUnexpiredTS the oldest timestamp we are interested in, * based on TTL */ public ScanQueryMatcher(Scan scan, ScanInfo scanInfo, NavigableSet<byte[]> columns, ScanType scanType, long readPointToUse, long earliestPutTs, long oldestUnexpiredTS) { this.tr = scan.getTimeRange(); this.rowComparator = scanInfo.getComparator(); this.deletes = new ScanDeleteTracker(); this.stopRow = scan.getStopRow(); this.startKey = KeyValue.createFirstDeleteFamilyOnRow(scan.getStartRow(), scanInfo.getFamily()); this.filter = scan.getFilter(); this.earliestPutTs = earliestPutTs; this.maxReadPointToTrackVersions = readPointToUse; this.timeToPurgeDeletes = scanInfo.getTimeToPurgeDeletes(); /* how to deal with deletes */ this.isUserScan = scanType == ScanType.USER_SCAN; // keep deleted cells: if compaction or raw scan this.keepDeletedCells = (scanInfo.getKeepDeletedCells() && !isUserScan) || scan.isRaw(); // retain deletes: if minor compaction or raw scan this.retainDeletesInOutput = scanType == ScanType.COMPACT_RETAIN_DELETES || scan.isRaw(); // seePastDeleteMarker: user initiated scans this.seePastDeleteMarkers = scanInfo.getKeepDeletedCells() && isUserScan; int maxVersions = scan.isRaw() ? scan.getMaxVersions() : Math.min(scan.getMaxVersions(), scanInfo.getMaxVersions()); // Single branch to deal with two types of reads (columns vs all in family) if (columns == null || columns.size() == 0) { // there is always a null column in the wildcard column query. hasNullColumn = true; // use a specialized scan for wildcard column tracker. this.columns = new ScanWildcardColumnTracker( scanInfo.getMinVersions(), maxVersions, oldestUnexpiredTS); } else { // whether there is null column in the explicit column query hasNullColumn = (columns.first().length == 0); // We can share the ExplicitColumnTracker, diff is we reset // between rows, not between storefiles. byte[] attr = scan.getAttribute(Scan.HINT_LOOKAHEAD); this.columns = new ExplicitColumnTracker(columns, scanInfo.getMinVersions(), maxVersions, oldestUnexpiredTS, attr == null ? 0 : Bytes.toInt(attr)); } this.isReversed = scan.isReversed(); } /** * Construct a QueryMatcher for a scan that drop deletes from a limited range of rows. * @param scan * @param scanInfo The store's immutable scan info * @param columns * @param earliestPutTs Earliest put seen in any of the store files. * @param oldestUnexpiredTS the oldest timestamp we are interested in, * based on TTL * @param dropDeletesFromRow The inclusive left bound of the range; can be EMPTY_START_ROW. * @param dropDeletesToRow The exclusive right bound of the range; can be EMPTY_END_ROW. */ public ScanQueryMatcher(Scan scan, ScanInfo scanInfo, NavigableSet<byte[]> columns, long readPointToUse, long earliestPutTs, long oldestUnexpiredTS, byte[] dropDeletesFromRow, byte[] dropDeletesToRow) { this(scan, scanInfo, columns, ScanType.COMPACT_RETAIN_DELETES, readPointToUse, earliestPutTs, oldestUnexpiredTS); Preconditions.checkArgument((dropDeletesFromRow != null) && (dropDeletesToRow != null)); this.dropDeletesFromRow = dropDeletesFromRow; this.dropDeletesToRow = dropDeletesToRow; } /* * Constructor for tests */ ScanQueryMatcher(Scan scan, ScanInfo scanInfo, NavigableSet<byte[]> columns, long oldestUnexpiredTS) { this(scan, scanInfo, columns, ScanType.USER_SCAN, Long.MAX_VALUE, /* max Readpoint to track versions */ HConstants.LATEST_TIMESTAMP, oldestUnexpiredTS); } /** * * @return whether there is an null column in the query */ public boolean hasNullColumnInQuery() { return hasNullColumn; } /** * Determines if the caller should do one of several things: * - seek/skip to the next row (MatchCode.SEEK_NEXT_ROW) * - seek/skip to the next column (MatchCode.SEEK_NEXT_COL) * - include the current KeyValue (MatchCode.INCLUDE) * - ignore the current KeyValue (MatchCode.SKIP) * - got to the next row (MatchCode.DONE) * * @param kv KeyValue to check * @return The match code instance. * @throws IOException in case there is an internal consistency problem * caused by a data corruption. */ public MatchCode match(KeyValue kv) throws IOException { if (filter != null && filter.filterAllRemaining()) { return MatchCode.DONE_SCAN; } byte [] bytes = kv.getBuffer(); int offset = kv.getOffset(); int keyLength = Bytes.toInt(bytes, offset, Bytes.SIZEOF_INT); offset += KeyValue.ROW_OFFSET; int initialOffset = offset; short rowLength = Bytes.toShort(bytes, offset, Bytes.SIZEOF_SHORT); offset += Bytes.SIZEOF_SHORT; int ret = this.rowComparator.compareRows(row, this.rowOffset, this.rowLength, bytes, offset, rowLength); if (!this.isReversed) { if (ret <= -1) { return MatchCode.DONE; } else if (ret >= 1) { // could optimize this, if necessary? // Could also be called SEEK_TO_CURRENT_ROW, but this // should be rare/never happens. return MatchCode.SEEK_NEXT_ROW; } } else { if (ret <= -1) { return MatchCode.SEEK_NEXT_ROW; } else if (ret >= 1) { return MatchCode.DONE; } } // optimize case. if (this.stickyNextRow) return MatchCode.SEEK_NEXT_ROW; if (this.columns.done()) { stickyNextRow = true; return MatchCode.SEEK_NEXT_ROW; } //Passing rowLength offset += rowLength; //Skipping family byte familyLength = bytes [offset]; offset += familyLength + 1; int qualLength = keyLength - (offset - initialOffset) - KeyValue.TIMESTAMP_TYPE_SIZE; long timestamp = Bytes.toLong(bytes, initialOffset + keyLength - KeyValue.TIMESTAMP_TYPE_SIZE); // check for early out based on timestamp alone if (columns.isDone(timestamp)) { return columns.getNextRowOrNextColumn(bytes, offset, qualLength); } /* * The delete logic is pretty complicated now. * This is corroborated by the following: * 1. The store might be instructed to keep deleted rows around. * 2. A scan can optionally see past a delete marker now. * 3. If deleted rows are kept, we have to find out when we can * remove the delete markers. * 4. Family delete markers are always first (regardless of their TS) * 5. Delete markers should not be counted as version * 6. Delete markers affect puts of the *same* TS * 7. Delete marker need to be version counted together with puts * they affect */ byte type = bytes[initialOffset + keyLength - 1]; if (kv.isDelete()) { if (!keepDeletedCells) { // first ignore delete markers if the scanner can do so, and the // range does not include the marker // // during flushes and compactions also ignore delete markers newer // than the readpoint of any open scanner, this prevents deleted // rows that could still be seen by a scanner from being collected boolean includeDeleteMarker = seePastDeleteMarkers ? tr.withinTimeRange(timestamp) : tr.withinOrAfterTimeRange(timestamp); if (includeDeleteMarker && kv.getMvccVersion() <= maxReadPointToTrackVersions) { this.deletes.add(bytes, offset, qualLength, timestamp, type); } // Can't early out now, because DelFam come before any other keys } if (retainDeletesInOutput || (!isUserScan && (EnvironmentEdgeManager.currentTimeMillis() - timestamp) <= timeToPurgeDeletes) || kv.getMvccVersion() > maxReadPointToTrackVersions) { // always include or it is not time yet to check whether it is OK // to purge deltes or not if (!isUserScan) { // if this is not a user scan (compaction), we can filter this deletemarker right here // otherwise (i.e. a "raw" scan) we fall through to normal version and timerange checking return MatchCode.INCLUDE; } } else if (keepDeletedCells) { if (timestamp < earliestPutTs) { // keeping delete rows, but there are no puts older than // this delete in the store files. return columns.getNextRowOrNextColumn(bytes, offset, qualLength); } // else: fall through and do version counting on the // delete markers } else { return MatchCode.SKIP; } // note the following next else if... // delete marker are not subject to other delete markers } else if (!this.deletes.isEmpty()) { DeleteResult deleteResult = deletes.isDeleted(bytes, offset, qualLength, timestamp); switch (deleteResult) { case FAMILY_DELETED: case COLUMN_DELETED: return columns.getNextRowOrNextColumn(bytes, offset, qualLength); case VERSION_DELETED: case FAMILY_VERSION_DELETED: return MatchCode.SKIP; case NOT_DELETED: break; default: throw new RuntimeException("UNEXPECTED"); } } int timestampComparison = tr.compare(timestamp); if (timestampComparison >= 1) { return MatchCode.SKIP; } else if (timestampComparison <= -1) { return columns.getNextRowOrNextColumn(bytes, offset, qualLength); } // STEP 1: Check if the column is part of the requested columns MatchCode colChecker = columns.checkColumn(bytes, offset, qualLength, type); if (colChecker == MatchCode.INCLUDE) { ReturnCode filterResponse = ReturnCode.SKIP; // STEP 2: Yes, the column is part of the requested columns. Check if filter is present if (filter != null) { // STEP 3: Filter the key value and return if it filters out filterResponse = filter.filterKeyValue(kv); switch (filterResponse) { case SKIP: return MatchCode.SKIP; case NEXT_COL: return columns.getNextRowOrNextColumn(bytes, offset, qualLength); case NEXT_ROW: stickyNextRow = true; return MatchCode.SEEK_NEXT_ROW; case SEEK_NEXT_USING_HINT: return MatchCode.SEEK_NEXT_USING_HINT; default: //It means it is either include or include and seek next break; } } /* * STEP 4: Reaching this step means the column is part of the requested columns and either * the filter is null or the filter has returned INCLUDE or INCLUDE_AND_NEXT_COL response. * Now check the number of versions needed. This method call returns SKIP, INCLUDE, * INCLUDE_AND_SEEK_NEXT_ROW, INCLUDE_AND_SEEK_NEXT_COL. * * FilterResponse ColumnChecker Desired behavior * INCLUDE SKIP row has already been included, SKIP. * INCLUDE INCLUDE INCLUDE * INCLUDE INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_COL * INCLUDE INCLUDE_AND_SEEK_NEXT_ROW INCLUDE_AND_SEEK_NEXT_ROW * INCLUDE_AND_SEEK_NEXT_COL SKIP row has already been included, SKIP. * INCLUDE_AND_SEEK_NEXT_COL INCLUDE INCLUDE_AND_SEEK_NEXT_COL * INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_COL * INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_ROW INCLUDE_AND_SEEK_NEXT_ROW * * In all the above scenarios, we return the column checker return value except for * FilterResponse (INCLUDE_AND_SEEK_NEXT_COL) and ColumnChecker(INCLUDE) */ colChecker = columns.checkVersions(bytes, offset, qualLength, timestamp, type, kv.getMvccVersion() > maxReadPointToTrackVersions); //Optimize with stickyNextRow stickyNextRow = colChecker == MatchCode.INCLUDE_AND_SEEK_NEXT_ROW ? true : stickyNextRow; return (filterResponse == ReturnCode.INCLUDE_AND_NEXT_COL && colChecker == MatchCode.INCLUDE) ? MatchCode.INCLUDE_AND_SEEK_NEXT_COL : colChecker; } stickyNextRow = (colChecker == MatchCode.SEEK_NEXT_ROW) ? true : stickyNextRow; return colChecker; } /** Handle partial-drop-deletes. As we match keys in order, when we have a range from which * we can drop deletes, we can set retainDeletesInOutput to false for the duration of this * range only, and maintain consistency. */ private void checkPartialDropDeleteRange(byte [] row, int offset, short length) { // If partial-drop-deletes are used, initially, dropDeletesFromRow and dropDeletesToRow // are both set, and the matcher is set to retain deletes. We assume ordered keys. When // dropDeletesFromRow is leq current kv, we start dropping deletes and reset // dropDeletesFromRow; thus the 2nd "if" starts to apply. if ((dropDeletesFromRow != null) && ((dropDeletesFromRow == HConstants.EMPTY_START_ROW) || (Bytes.compareTo(row, offset, length, dropDeletesFromRow, 0, dropDeletesFromRow.length) >= 0))) { retainDeletesInOutput = false; dropDeletesFromRow = null; } // If dropDeletesFromRow is null and dropDeletesToRow is set, we are inside the partial- // drop-deletes range. When dropDeletesToRow is leq current kv, we stop dropping deletes, // and reset dropDeletesToRow so that we don't do any more compares. if ((dropDeletesFromRow == null) && (dropDeletesToRow != null) && (dropDeletesToRow != HConstants.EMPTY_END_ROW) && (Bytes.compareTo(row, offset, length, dropDeletesToRow, 0, dropDeletesToRow.length) >= 0)) { retainDeletesInOutput = true; dropDeletesToRow = null; } } public boolean moreRowsMayExistAfter(KeyValue kv) { if (this.isReversed) { if (rowComparator.compareRows(kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(), stopRow, 0, stopRow.length) <= 0) { return false; } else { return true; } } if (!Bytes.equals(stopRow , HConstants.EMPTY_END_ROW) && rowComparator.compareRows(kv.getBuffer(),kv.getRowOffset(), kv.getRowLength(), stopRow, 0, stopRow.length) >= 0) { // KV >= STOPROW // then NO there is nothing left. return false; } else { return true; } } /** * Set current row * @param row */ public void setRow(byte [] row, int offset, short length) { checkPartialDropDeleteRange(row, offset, length); this.row = row; this.rowOffset = offset; this.rowLength = length; reset(); } public void reset() { this.deletes.reset(); this.columns.reset(); stickyNextRow = false; } /** * * @return the start key */ public KeyValue getStartKey() { return this.startKey; } /** * * @return the Filter */ Filter getFilter() { return this.filter; } public Cell getNextKeyHint(Cell kv) throws IOException { if (filter == null) { return null; } else { return filter.getNextCellHint(kv); } } public KeyValue getKeyForNextColumn(KeyValue kv) { ColumnCount nextColumn = columns.getColumnHint(); if (nextColumn == null) { return KeyValue.createLastOnRow( kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(), kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(), kv.getBuffer(), kv.getQualifierOffset(), kv.getQualifierLength()); } else { return KeyValue.createFirstOnRow( kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(), kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(), nextColumn.getBuffer(), nextColumn.getOffset(), nextColumn.getLength()); } } public KeyValue getKeyForNextRow(KeyValue kv) { return KeyValue.createLastOnRow( kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(), null, 0, 0, null, 0, 0); } //Used only for testing purposes static MatchCode checkColumn(ColumnTracker columnTracker, byte[] bytes, int offset, int length, long ttl, byte type, boolean ignoreCount) throws IOException { MatchCode matchCode = columnTracker.checkColumn(bytes, offset, length, type); if (matchCode == MatchCode.INCLUDE) { return columnTracker.checkVersions(bytes, offset, length, ttl, type, ignoreCount); } return matchCode; } /** * {@link #match} return codes. These instruct the scanner moving through * memstores and StoreFiles what to do with the current KeyValue. * <p> * Additionally, this contains "early-out" language to tell the scanner to * move on to the next File (memstore or Storefile), or to return immediately. */ public static enum MatchCode { /** * Include KeyValue in the returned result */ INCLUDE, /** * Do not include KeyValue in the returned result */ SKIP, /** * Do not include, jump to next StoreFile or memstore (in time order) */ NEXT, /** * Do not include, return current result */ DONE, /** * These codes are used by the ScanQueryMatcher */ /** * Done with the row, seek there. */ SEEK_NEXT_ROW, /** * Done with column, seek to next. */ SEEK_NEXT_COL, /** * Done with scan, thanks to the row filter. */ DONE_SCAN, /* * Seek to next key which is given as hint. */ SEEK_NEXT_USING_HINT, /** * Include KeyValue and done with column, seek to next. */ INCLUDE_AND_SEEK_NEXT_COL, /** * Include KeyValue and done with row, seek to next. */ INCLUDE_AND_SEEK_NEXT_ROW, } }
apache-2.0
ferjorosa/Voltric
src/main/java/voltric/clustering/util/GenerateCompleteData.java
8277
package voltric.clustering.util; import voltric.data.DiscreteData; import voltric.data.DiscreteDataInstance; import voltric.model.DiscreteBayesNet; import voltric.util.SymmetricPair; import voltric.variables.DiscreteVariable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by equipo on 12/05/2018. * * Genera un dataSet completo al asignar a cada instancia su valor de cluster mas probable, con respecto a 1 o mas particiones. */ public class GenerateCompleteData { public static DiscreteData generateUnidimensional(DiscreteData dataSet, DiscreteBayesNet lcm) { if(lcm.getLatentVariables().size() > 1) throw new IllegalArgumentException("Solo se permite una variable latente en el modelo"); Map<DiscreteDataInstance, Integer> completeDataMap = new HashMap<>(); List<SymmetricPair<DiscreteDataInstance, double[]>> clusterAssingments = AssignToClusters.assignDataCaseToCluster(dataSet, lcm); // Inicializamos el Map for(DiscreteDataInstance instance: dataSet.getInstances()) completeDataMap.put(instance, -1); // Transformamos las probabilidades de asignacin de cada instancia a un cluster por el indice del cluster con // mayor probabilidad y lo almacenamos for (SymmetricPair<DiscreteDataInstance, double[]> clustAssignment : clusterAssingments) { // Calculamos el índice de valor máximo double maxVal = 0; int maxIndex = 0; for (int i = 0; i < clustAssignment.getSecond().length; i++) if (clustAssignment.getSecond()[i] > maxVal) { maxIndex = i; maxVal = clustAssignment.getSecond()[i]; } // Asignamos el indice del cluster al que pertenece la instancia con mayor probabilidad a la instancia en cuestion completeDataMap.put(clustAssignment.getFirst(), maxIndex); } // Una vez hemos asignado a cada instancia su cluster mas probable, generamos un objeto "DiscreteData" donde // se incluyan las variables de particion como variables observadas. // Por cada variable latente creamos una MV cuyo nombre coincide y que servirá para el nuevo DataSet // TODO 09-07-2018: referencio directamente las variables latentes List<DiscreteVariable> observedPartitionVars = new ArrayList<>(); for(DiscreteVariable partitionVar: lcm.getLatentVariables()){ /* DiscreteVariable newManifestVar = new DiscreteVariable(partitionVar.getCardinality(), VariableType.MANIFEST_VARIABLE, partitionVar.getName()); observedPartitionVars.add(newManifestVar); */ observedPartitionVars.add(partitionVar); } // Creamos una nueva lista con todas las variables, primero las MVs y luego las LVs (ahora son MV tmb) List<DiscreteVariable> completedDataSetVars = new ArrayList<>(); completedDataSetVars.addAll(dataSet.getVariables()); completedDataSetVars.addAll(observedPartitionVars); // Creamos el dataSet completo que debemos rellenar con los valores de las LVs DiscreteData completedDataSet = new DiscreteData(completedDataSetVars); // Añadimos las instancias correspondientes // Por cada instancia de los datos antiguos añadimos los valores de las MVs seguidos de las LVs for(DiscreteDataInstance oldInstance: dataSet.getInstances()){ int[] oldData = oldInstance.getNumericValues(); int latentVarData = completeDataMap.get(oldInstance); int[] newData = new int[oldData.length + 1]; // Primero las MVs for(int i = 0; i < oldData.length; i++) newData[i] = oldData[i]; // Despues las LVs (en este caso solo hay 1) cuya posicion es la ultima del array newData[oldData.length] = latentVarData; // Add to the new completed data a new data instance containing both the MVs and the LVs completedDataSet.add(new DiscreteDataInstance(newData), dataSet.getWeight(oldInstance)); } return completedDataSet; } public static DiscreteData generateMultidimensional(DiscreteData dataSet, DiscreteBayesNet mpm) { Map<DiscreteDataInstance, List<Integer>> completeDataMap = new HashMap<>(); List<SymmetricPair<DiscreteDataInstance, List<double[]>>> instancesWithPartitionProbs = AssignToClusters.assignDataCaseToClusters(dataSet, mpm); // Transformamos las probabilidades de asignacin de cada instancia a un cluster por el indice del cluster con // mayor probabilidad y lo almacenamos for (SymmetricPair<DiscreteDataInstance, List<double[]>> instanceWithPartitionProbs : instancesWithPartitionProbs) { /** Por cada variable latente del modelo, calculamos el indice del estado con mayor probabilidad*/ DiscreteDataInstance instance = instanceWithPartitionProbs.getFirst(); List<Integer> partitionAssignments = new ArrayList<>(mpm.getLatentVariables().size()); /** Iteramos por el indice de variables latentes */ for(int partitionVarIndex = 0; partitionVarIndex < mpm.getLatentVariables().size(); partitionVarIndex++){ double[] partitionProbs = instanceWithPartitionProbs.getSecond().get(partitionVarIndex); // Calculamos el índice de valor máximo double maxVal = 0; int maxIndex = 0; for (int i = 0; i < partitionProbs.length; i++) if (partitionProbs[i] > maxVal) { maxIndex = i; maxVal = partitionProbs[i]; } partitionAssignments.add(maxIndex); } // Enlazamos cada instancia con su lista de asignaciones para las particiones completeDataMap.put(instance, partitionAssignments); } // Una vez hemos asignado a cada instancia su cluster mas probable, generamos un objeto "DiscreteData" donde // se incluyan las variables de particion como variables observadas. // Por cada variable latente creamos una MV cuyo nombre coincide y que servirá para el nuevo DataSet // TODO 09-07-2018: referencio directamente las variables latentes List<DiscreteVariable> observedPartitionVars = new ArrayList<>(); for(DiscreteVariable partitionVar: mpm.getLatentVariables()){ /* DiscreteVariable newManifestVar = new DiscreteVariable(partitionVar.getCardinality(), VariableType.MANIFEST_VARIABLE, partitionVar.getName()); observedPartitionVars.add(newManifestVar); */ observedPartitionVars.add(partitionVar); } // Creamos una nueva lista con todas las variables, primero las MVs y luego las LVs (ahora son MV tmb) List<DiscreteVariable> completedDataSetVars = new ArrayList<>(); completedDataSetVars.addAll(dataSet.getVariables()); completedDataSetVars.addAll(observedPartitionVars); // Creamos el dataSet completo que debemos rellenar con los valores de las LVs DiscreteData completedDataSet = new DiscreteData(completedDataSetVars); // Añadimos las instancias correspondientes // Por cada instancia de los datos antiguos añadimos los valores de las MVs seguidos de las LVs for(DiscreteDataInstance oldInstance: dataSet.getInstances()){ int[] oldData = oldInstance.getNumericValues(); List<Integer> latentVarData = completeDataMap.get(oldInstance); int[] newData = new int[oldData.length + latentVarData.size()]; for(int i = 0; i < oldData.length; i++) newData[i] = oldData[i]; // Despues las LVs for(int i = 0; i < latentVarData.size(); i++) newData[i+oldData.length] = latentVarData.get(i); // Add to the new completed data a new data instance containing both the MVs and the LVs completedDataSet.add(new DiscreteDataInstance(newData), dataSet.getWeight(oldInstance)); } return completedDataSet; } }
apache-2.0
kpelykh/sharepast.com
sharepast-project/sp-container/src/main/java/com/sharepast/freemarker/UrlMethod.java
1729
package com.sharepast.freemarker; import freemarker.template.TemplateHashModelEx; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModelException; import freemarker.template.TemplateModelIterator; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by IntelliJ IDEA. * User: Kostya * Date: 8/27/11 * Time: 12:11 AM * To change this template use File | Settings | File Templates. */ public class UrlMethod implements TemplateMethodModelEx { public Object exec(List arguments) throws TemplateModelException { if (arguments.size() != 2) { throw new TemplateModelException("Wrong arguments"); } // first argument is url type String routeName = arguments.get( 0 ).toString(); // second argument is hash of params e.g. {"offerId": 12} TemplateHashModelEx hash = (TemplateHashModelEx) arguments.get(1); Map<String, Object> params = convertToMap(hash); UriComponents url = UriComponentsBuilder.fromPath(routeName).build().expand(params).encode(); return url.toUriString(); } private static Map<String, Object> convertToMap(TemplateHashModelEx hash) throws TemplateModelException { Map<String, Object> map = new HashMap<String, Object>(); TemplateModelIterator iterator = hash.keys().iterator(); while (iterator.hasNext()) { String key = iterator.next().toString(); String value = hash.get(key).toString(); map.put(key, value); } return map; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/VolumeConfiguration.java
22955
/* * Copyright 2017-2022 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.opsworks.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Describes an Amazon EBS volume configuration. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/VolumeConfiguration" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class VolumeConfiguration implements Serializable, Cloneable, StructuredPojo { /** * <p> * The volume mount point. For example "/dev/sdh". * </p> */ private String mountPoint; /** * <p> * The volume <a href="http://en.wikipedia.org/wiki/Standard_RAID_levels">RAID level</a>. * </p> */ private Integer raidLevel; /** * <p> * The number of disks in the volume. * </p> */ private Integer numberOfDisks; /** * <p> * The volume size. * </p> */ private Integer size; /** * <p> * The volume type. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html"> Amazon EBS Volume Types</a>. * </p> * <ul> * <li> * <p> * <code>standard</code> - Magnetic. Magnetic volumes must have a minimum size of 1 GiB and a maximum size of 1024 * GiB. * </p> * </li> * <li> * <p> * <code>io1</code> - Provisioned IOPS (SSD). PIOPS volumes must have a minimum size of 4 GiB and a maximum size of * 16384 GiB. * </p> * </li> * <li> * <p> * <code>gp2</code> - General Purpose (SSD). General purpose volumes must have a minimum size of 1 GiB and a maximum * size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>st1</code> - Throughput Optimized hard disk drive (HDD). Throughput optimized HDD volumes must have a * minimum size of 500 GiB and a maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>sc1</code> - Cold HDD. Cold HDD volumes must have a minimum size of 500 GiB and a maximum size of 16384 * GiB. * </p> * </li> * </ul> */ private String volumeType; /** * <p> * For PIOPS volumes, the IOPS per disk. * </p> */ private Integer iops; /** * <p> * Specifies whether an Amazon EBS volume is encrypted. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>. * </p> */ private Boolean encrypted; /** * <p> * The volume mount point. For example "/dev/sdh". * </p> * * @param mountPoint * The volume mount point. For example "/dev/sdh". */ public void setMountPoint(String mountPoint) { this.mountPoint = mountPoint; } /** * <p> * The volume mount point. For example "/dev/sdh". * </p> * * @return The volume mount point. For example "/dev/sdh". */ public String getMountPoint() { return this.mountPoint; } /** * <p> * The volume mount point. For example "/dev/sdh". * </p> * * @param mountPoint * The volume mount point. For example "/dev/sdh". * @return Returns a reference to this object so that method calls can be chained together. */ public VolumeConfiguration withMountPoint(String mountPoint) { setMountPoint(mountPoint); return this; } /** * <p> * The volume <a href="http://en.wikipedia.org/wiki/Standard_RAID_levels">RAID level</a>. * </p> * * @param raidLevel * The volume <a href="http://en.wikipedia.org/wiki/Standard_RAID_levels">RAID level</a>. */ public void setRaidLevel(Integer raidLevel) { this.raidLevel = raidLevel; } /** * <p> * The volume <a href="http://en.wikipedia.org/wiki/Standard_RAID_levels">RAID level</a>. * </p> * * @return The volume <a href="http://en.wikipedia.org/wiki/Standard_RAID_levels">RAID level</a>. */ public Integer getRaidLevel() { return this.raidLevel; } /** * <p> * The volume <a href="http://en.wikipedia.org/wiki/Standard_RAID_levels">RAID level</a>. * </p> * * @param raidLevel * The volume <a href="http://en.wikipedia.org/wiki/Standard_RAID_levels">RAID level</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public VolumeConfiguration withRaidLevel(Integer raidLevel) { setRaidLevel(raidLevel); return this; } /** * <p> * The number of disks in the volume. * </p> * * @param numberOfDisks * The number of disks in the volume. */ public void setNumberOfDisks(Integer numberOfDisks) { this.numberOfDisks = numberOfDisks; } /** * <p> * The number of disks in the volume. * </p> * * @return The number of disks in the volume. */ public Integer getNumberOfDisks() { return this.numberOfDisks; } /** * <p> * The number of disks in the volume. * </p> * * @param numberOfDisks * The number of disks in the volume. * @return Returns a reference to this object so that method calls can be chained together. */ public VolumeConfiguration withNumberOfDisks(Integer numberOfDisks) { setNumberOfDisks(numberOfDisks); return this; } /** * <p> * The volume size. * </p> * * @param size * The volume size. */ public void setSize(Integer size) { this.size = size; } /** * <p> * The volume size. * </p> * * @return The volume size. */ public Integer getSize() { return this.size; } /** * <p> * The volume size. * </p> * * @param size * The volume size. * @return Returns a reference to this object so that method calls can be chained together. */ public VolumeConfiguration withSize(Integer size) { setSize(size); return this; } /** * <p> * The volume type. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html"> Amazon EBS Volume Types</a>. * </p> * <ul> * <li> * <p> * <code>standard</code> - Magnetic. Magnetic volumes must have a minimum size of 1 GiB and a maximum size of 1024 * GiB. * </p> * </li> * <li> * <p> * <code>io1</code> - Provisioned IOPS (SSD). PIOPS volumes must have a minimum size of 4 GiB and a maximum size of * 16384 GiB. * </p> * </li> * <li> * <p> * <code>gp2</code> - General Purpose (SSD). General purpose volumes must have a minimum size of 1 GiB and a maximum * size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>st1</code> - Throughput Optimized hard disk drive (HDD). Throughput optimized HDD volumes must have a * minimum size of 500 GiB and a maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>sc1</code> - Cold HDD. Cold HDD volumes must have a minimum size of 500 GiB and a maximum size of 16384 * GiB. * </p> * </li> * </ul> * * @param volumeType * The volume type. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html"> Amazon EBS Volume * Types</a>.</p> * <ul> * <li> * <p> * <code>standard</code> - Magnetic. Magnetic volumes must have a minimum size of 1 GiB and a maximum size of * 1024 GiB. * </p> * </li> * <li> * <p> * <code>io1</code> - Provisioned IOPS (SSD). PIOPS volumes must have a minimum size of 4 GiB and a maximum * size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>gp2</code> - General Purpose (SSD). General purpose volumes must have a minimum size of 1 GiB and a * maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>st1</code> - Throughput Optimized hard disk drive (HDD). Throughput optimized HDD volumes must have * a minimum size of 500 GiB and a maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>sc1</code> - Cold HDD. Cold HDD volumes must have a minimum size of 500 GiB and a maximum size of * 16384 GiB. * </p> * </li> */ public void setVolumeType(String volumeType) { this.volumeType = volumeType; } /** * <p> * The volume type. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html"> Amazon EBS Volume Types</a>. * </p> * <ul> * <li> * <p> * <code>standard</code> - Magnetic. Magnetic volumes must have a minimum size of 1 GiB and a maximum size of 1024 * GiB. * </p> * </li> * <li> * <p> * <code>io1</code> - Provisioned IOPS (SSD). PIOPS volumes must have a minimum size of 4 GiB and a maximum size of * 16384 GiB. * </p> * </li> * <li> * <p> * <code>gp2</code> - General Purpose (SSD). General purpose volumes must have a minimum size of 1 GiB and a maximum * size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>st1</code> - Throughput Optimized hard disk drive (HDD). Throughput optimized HDD volumes must have a * minimum size of 500 GiB and a maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>sc1</code> - Cold HDD. Cold HDD volumes must have a minimum size of 500 GiB and a maximum size of 16384 * GiB. * </p> * </li> * </ul> * * @return The volume type. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html"> Amazon EBS Volume * Types</a>.</p> * <ul> * <li> * <p> * <code>standard</code> - Magnetic. Magnetic volumes must have a minimum size of 1 GiB and a maximum size * of 1024 GiB. * </p> * </li> * <li> * <p> * <code>io1</code> - Provisioned IOPS (SSD). PIOPS volumes must have a minimum size of 4 GiB and a maximum * size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>gp2</code> - General Purpose (SSD). General purpose volumes must have a minimum size of 1 GiB and a * maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>st1</code> - Throughput Optimized hard disk drive (HDD). Throughput optimized HDD volumes must have * a minimum size of 500 GiB and a maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>sc1</code> - Cold HDD. Cold HDD volumes must have a minimum size of 500 GiB and a maximum size of * 16384 GiB. * </p> * </li> */ public String getVolumeType() { return this.volumeType; } /** * <p> * The volume type. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html"> Amazon EBS Volume Types</a>. * </p> * <ul> * <li> * <p> * <code>standard</code> - Magnetic. Magnetic volumes must have a minimum size of 1 GiB and a maximum size of 1024 * GiB. * </p> * </li> * <li> * <p> * <code>io1</code> - Provisioned IOPS (SSD). PIOPS volumes must have a minimum size of 4 GiB and a maximum size of * 16384 GiB. * </p> * </li> * <li> * <p> * <code>gp2</code> - General Purpose (SSD). General purpose volumes must have a minimum size of 1 GiB and a maximum * size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>st1</code> - Throughput Optimized hard disk drive (HDD). Throughput optimized HDD volumes must have a * minimum size of 500 GiB and a maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>sc1</code> - Cold HDD. Cold HDD volumes must have a minimum size of 500 GiB and a maximum size of 16384 * GiB. * </p> * </li> * </ul> * * @param volumeType * The volume type. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html"> Amazon EBS Volume * Types</a>.</p> * <ul> * <li> * <p> * <code>standard</code> - Magnetic. Magnetic volumes must have a minimum size of 1 GiB and a maximum size of * 1024 GiB. * </p> * </li> * <li> * <p> * <code>io1</code> - Provisioned IOPS (SSD). PIOPS volumes must have a minimum size of 4 GiB and a maximum * size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>gp2</code> - General Purpose (SSD). General purpose volumes must have a minimum size of 1 GiB and a * maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>st1</code> - Throughput Optimized hard disk drive (HDD). Throughput optimized HDD volumes must have * a minimum size of 500 GiB and a maximum size of 16384 GiB. * </p> * </li> * <li> * <p> * <code>sc1</code> - Cold HDD. Cold HDD volumes must have a minimum size of 500 GiB and a maximum size of * 16384 GiB. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public VolumeConfiguration withVolumeType(String volumeType) { setVolumeType(volumeType); return this; } /** * <p> * For PIOPS volumes, the IOPS per disk. * </p> * * @param iops * For PIOPS volumes, the IOPS per disk. */ public void setIops(Integer iops) { this.iops = iops; } /** * <p> * For PIOPS volumes, the IOPS per disk. * </p> * * @return For PIOPS volumes, the IOPS per disk. */ public Integer getIops() { return this.iops; } /** * <p> * For PIOPS volumes, the IOPS per disk. * </p> * * @param iops * For PIOPS volumes, the IOPS per disk. * @return Returns a reference to this object so that method calls can be chained together. */ public VolumeConfiguration withIops(Integer iops) { setIops(iops); return this; } /** * <p> * Specifies whether an Amazon EBS volume is encrypted. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>. * </p> * * @param encrypted * Specifies whether an Amazon EBS volume is encrypted. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>. */ public void setEncrypted(Boolean encrypted) { this.encrypted = encrypted; } /** * <p> * Specifies whether an Amazon EBS volume is encrypted. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>. * </p> * * @return Specifies whether an Amazon EBS volume is encrypted. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>. */ public Boolean getEncrypted() { return this.encrypted; } /** * <p> * Specifies whether an Amazon EBS volume is encrypted. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>. * </p> * * @param encrypted * Specifies whether an Amazon EBS volume is encrypted. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public VolumeConfiguration withEncrypted(Boolean encrypted) { setEncrypted(encrypted); return this; } /** * <p> * Specifies whether an Amazon EBS volume is encrypted. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>. * </p> * * @return Specifies whether an Amazon EBS volume is encrypted. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>. */ public Boolean isEncrypted() { return this.encrypted; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMountPoint() != null) sb.append("MountPoint: ").append(getMountPoint()).append(","); if (getRaidLevel() != null) sb.append("RaidLevel: ").append(getRaidLevel()).append(","); if (getNumberOfDisks() != null) sb.append("NumberOfDisks: ").append(getNumberOfDisks()).append(","); if (getSize() != null) sb.append("Size: ").append(getSize()).append(","); if (getVolumeType() != null) sb.append("VolumeType: ").append(getVolumeType()).append(","); if (getIops() != null) sb.append("Iops: ").append(getIops()).append(","); if (getEncrypted() != null) sb.append("Encrypted: ").append(getEncrypted()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof VolumeConfiguration == false) return false; VolumeConfiguration other = (VolumeConfiguration) obj; if (other.getMountPoint() == null ^ this.getMountPoint() == null) return false; if (other.getMountPoint() != null && other.getMountPoint().equals(this.getMountPoint()) == false) return false; if (other.getRaidLevel() == null ^ this.getRaidLevel() == null) return false; if (other.getRaidLevel() != null && other.getRaidLevel().equals(this.getRaidLevel()) == false) return false; if (other.getNumberOfDisks() == null ^ this.getNumberOfDisks() == null) return false; if (other.getNumberOfDisks() != null && other.getNumberOfDisks().equals(this.getNumberOfDisks()) == false) return false; if (other.getSize() == null ^ this.getSize() == null) return false; if (other.getSize() != null && other.getSize().equals(this.getSize()) == false) return false; if (other.getVolumeType() == null ^ this.getVolumeType() == null) return false; if (other.getVolumeType() != null && other.getVolumeType().equals(this.getVolumeType()) == false) return false; if (other.getIops() == null ^ this.getIops() == null) return false; if (other.getIops() != null && other.getIops().equals(this.getIops()) == false) return false; if (other.getEncrypted() == null ^ this.getEncrypted() == null) return false; if (other.getEncrypted() != null && other.getEncrypted().equals(this.getEncrypted()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMountPoint() == null) ? 0 : getMountPoint().hashCode()); hashCode = prime * hashCode + ((getRaidLevel() == null) ? 0 : getRaidLevel().hashCode()); hashCode = prime * hashCode + ((getNumberOfDisks() == null) ? 0 : getNumberOfDisks().hashCode()); hashCode = prime * hashCode + ((getSize() == null) ? 0 : getSize().hashCode()); hashCode = prime * hashCode + ((getVolumeType() == null) ? 0 : getVolumeType().hashCode()); hashCode = prime * hashCode + ((getIops() == null) ? 0 : getIops().hashCode()); hashCode = prime * hashCode + ((getEncrypted() == null) ? 0 : getEncrypted().hashCode()); return hashCode; } @Override public VolumeConfiguration clone() { try { return (VolumeConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.opsworks.model.transform.VolumeConfigurationMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
PhilippGrulich/Simple-Distributed-Store
src/main/java/de/tuberlin/aec/bg/sds/replication/types/ReplicationLink.java
346
package de.tuberlin.aec.bg.sds.replication.types; import de.tub.ise.hermes.Request; public abstract class ReplicationLink { public String src; public ReplicationLink(String src) { this.src = src; } public String getSrc() { return src; } public abstract Boolean startReplication(Request req, String startNode) throws Exception; }
apache-2.0
OlegNyr/sample-boot-mvc
src/main/java/ru/nyrk/bootmvc/integration/PrintBean.java
215
package ru.nyrk.bootmvc.integration; /** * Created by onyrk on 08.07.2016. */ public class PrintBean { public void print(){ System.out.println("00000000000000000000000000000000000000000000"); } }
apache-2.0
project-asap/IReS-Platform
panic/panic-core/src/main/java/gr/ntua/ece/cslab/panic/core/models/GaussianCurves.java
1075
/* * Copyright 2014 Giannis Giannakopoulos. * * 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 gr.ntua.ece.cslab.panic.core.models; import java.util.HashMap; import weka.classifiers.functions.GaussianProcesses; /** * * @author Giannis Giannakopoulos */ public class GaussianCurves extends AbstractWekaModel { public GaussianCurves() { super(); this.classifier = new GaussianProcesses(); } @Override public void configureClassifier(HashMap<String, String> conf) { // nothing for now } }
apache-2.0
kinshasa/react-native-qatest
android/android-pay-module/src/main/java/com/pay/WxPayActivity.java
4144
package com.pay; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.pay.event.WXPayCompletedEvent; import com.pay.module.PayModule; import com.pay.module.PayModule.PayResult; import com.tencent.mm.sdk.modelbase.BaseResp; import com.tencent.mm.sdk.modelpay.PayReq; import com.tencent.mm.sdk.openapi.IWXAPI; import com.tencent.mm.sdk.openapi.WXAPIFactory; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.json.JSONObject; /** * Created by liusp@gagc.com.cn on 2016.9.21. * 微信支付页面 */ public class WxPayActivity extends Activity { public static final String EXTRA = "prePayMsg"; private String prePayMsg = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prePayMsg = getIntent().getStringExtra(EXTRA); if (TextUtils.isEmpty(prePayMsg)) { finish(); } WXPay(prePayMsg); } @Override protected void onStart() { super.onStart(); if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } } @Override protected void onPause() { super.onPause(); } @Override protected void onRestart() { super.onRestart(); } @Override protected void onResume() { super.onResume(); } /** * 微信支付 * * @param payInfo */ private void WXPay(final String payInfo) { IWXAPI api; api = WXAPIFactory.createWXAPI(getApplicationContext(), "wx2429b4a5a943e5b0"); try { JSONObject json = new JSONObject(payInfo); PayReq req = new PayReq(); //req.appId = "wxf8b4f85f3a794e77"; // 测试用appId req.appId = json.getString("appid"); req.partnerId = json.getString("partnerid"); req.prepayId = json.getString("prepayid"); req.nonceStr = json.getString("noncestr"); req.timeStamp = json.getString("timestamp"); req.packageValue = json.getString("package"); req.sign = json.getString("sign"); req.extData = "app data"; // optional Toast.makeText(getApplicationContext(), "正常调起支付", Toast.LENGTH_SHORT).show(); // 在支付之前,如果应用没有注册到微信,应该先调用IWXMsg.registerApp将应用注册到微信 api.sendReq(req); } catch (Exception e) { Log.e("WxPay", "异常:" + e.getMessage()); Toast.makeText(getApplicationContext(), "异常:" + e.getMessage(), Toast.LENGTH_SHORT).show(); if (PayModule.exception != null){ PayModule.exception.invoke(new PayResult(-1,"支付异常:“"+e.getMessage()+"”").toString()); PayModule.callback = PayModule.exception = null; } finish(); } } /** * 监听WXPayEntryActivity支付结果后关闭 * @param event */ @Subscribe public void onWXPayCompletedEvent(WXPayCompletedEvent event) { Log.i("WxPayActivity", "onWXPayCompletedEvent, message = " + event.getMessage()); if (event.getCode() == BaseResp.ErrCode.ERR_OK) { if (PayModule.callback != null){ PayModule.callback.invoke(new PayResult(0,event.getMessage()).toString()); PayModule.callback = PayModule.exception = null; } } else { if (PayModule.callback != null){ PayModule.callback.invoke(new PayResult(event.getCode(),event.getMessage()).toString()); PayModule.callback = PayModule.exception = null; } } finish(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); } super.onDestroy(); } }
apache-2.0
Wokdsem/Kinject
kinject/src/main/java/com/wokdsem/kinject/Kinject.java
698
package com.wokdsem.kinject; import com.wokdsem.kinject.core.Injector; import com.wokdsem.kinject.core.KinjectRunner; import com.wokdsem.kinject.core.ModuleMapper; import static com.wokdsem.kinject.core.KinjectValues.DEFAULT_NAMED; public class Kinject { public static Kinject instantiate(ModuleMapper mapper) { Injector injector = KinjectRunner.initializeInjector(mapper); return new Kinject(injector); } private final Injector injector; private Kinject(Injector injector) { this.injector = injector; } public <T> T get(Class<T> tClass) { return get(tClass, DEFAULT_NAMED); } public <T> T get(Class<T> tClass, String named) { return injector.inject(tClass, named); } }
apache-2.0
gureronder/midpoint
samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/Main.java
31663
/* * Copyright (c) 2010-2014 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evolveum.midpoint.testing.model.client.sample; import com.evolveum.midpoint.model.client.ModelClientUtil; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.GetOperationOptionsType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaOperationListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectSelectorType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.RetrieveOptionType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.SelectorQualifiedGetOptionType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.SelectorQualifiedGetOptionsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ModelExecuteOptionsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaOperationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage; import com.evolveum.midpoint.xml.ns._public.model.model_3.ModelPortType; import com.evolveum.midpoint.xml.ns._public.model.model_3.ModelService; import com.evolveum.prism.xml.ns._public.query_3.OrderDirectionType; import com.evolveum.prism.xml.ns._public.query_3.PagingType; import com.evolveum.prism.xml.ns._public.query_3.QueryType; import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType; import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType; import com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType; import com.evolveum.prism.xml.ns._public.types_3.ModificationTypeType; import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import org.apache.commons.io.IOUtils; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor; import org.apache.wss4j.dom.handler.WSHandlerConstants; import org.apache.wss4j.dom.WSConstants; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.ws.BindingProvider; import javax.xml.ws.Holder; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ProxySelector; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; //import com.evolveum.midpoint.util.JAXBUtil; //import com.evolveum.midpoint.util.QNameUtil; /** * @author semancik * * Prerequisites: * 1. OpenDJ resource, Pirate and Captain roles should exist. * 2. Users lechuck and guybrush should NOT exist. * */ public class Main { // Configuration public static final String ADM_USERNAME = "administrator"; public static final String ADM_PASSWORD = "5ecr3t"; private static final String DEFAULT_ENDPOINT_URL = "http://localhost:8080/midpoint/model/model-3"; // Object OIDs private static final String ROLE_PIRATE_OID = "2de6a600-636f-11e4-9cc7-3c970e467874"; private static final String ROLE_CAPTAIN_OID = "12345678-d34d-b33f-f00d-987987cccccc"; /** * @param args */ public static void main(String[] args) { try { ModelPortType modelPort = createModelPort(args); SystemConfigurationType configurationType = getConfiguration(modelPort); System.out.println("Got system configuration"); // System.out.println(configurationType); UserType userAdministrator = searchUserByName(modelPort, "administrator"); System.out.println("Got administrator user: "+userAdministrator.getOid()); // System.out.println(userAdministrator); RoleType sailorRole = searchRoleByName(modelPort, "Sailor"); System.out.println("Got Sailor role"); // System.out.println(sailorRole); Collection<ResourceType> resources = listResources(modelPort); System.out.println("Resources ("+resources.size()+")"); // dump(resources); Collection<UserType> users = listUsers(modelPort); System.out.println("Users ("+users.size()+")"); // dump(users); Collection<TaskType> tasks = listTasks(modelPort); System.out.println("Tasks ("+tasks.size()+")"); // dump(tasks); // System.out.println("Next scheduled times: "); // for (TaskType taskType : tasks) { // System.out.println(" - " + getOrig(taskType.getName()) + ": " + taskType.getNextRunStartTimestamp()); // } String userGuybrushoid = createUserGuybrush(modelPort, sailorRole); System.out.println("Created user guybrush, OID: "+userGuybrushoid); UserType userGuybrush = getUser(modelPort, userGuybrushoid); System.out.println("Fetched user guybrush:"); // System.out.println(userGuybrush); System.out.println("Users fullName: " + ModelClientUtil.getOrig(userGuybrush.getFullName())); String userLeChuckOid = createUserFromSystemResource(modelPort, "user-lechuck.xml"); System.out.println("Created user lechuck, OID: "+userLeChuckOid); changeUserPassword(modelPort, userGuybrushoid, "MIGHTYpirate"); System.out.println("Changed user password"); changeUserGivenName(modelPort, userLeChuckOid, "CHUCK"); System.out.println("Changed user given name"); assignRoles(modelPort, userGuybrushoid, ROLE_PIRATE_OID, ROLE_CAPTAIN_OID); System.out.println("Assigned roles"); unAssignRoles(modelPort, userGuybrushoid, ROLE_CAPTAIN_OID); System.out.println("Unassigned roles"); Collection<RoleType> roles = listRequestableRoles(modelPort); System.out.println("Found "+roles.size()+" requestable roles"); // System.out.println(roles); String seaSuperuserRole = createRoleFromSystemResource(modelPort, "role-sea-superuser.xml"); System.out.println("Created role Sea Superuser, OID: " + seaSuperuserRole); assignRoles(modelPort, userLeChuckOid, seaSuperuserRole); System.out.println("Assigned role Sea Superuser to LeChuck"); modifyRoleModifyInducement(modelPort, seaSuperuserRole); System.out.println("Modified role Sea Superuser - modified resource inducement"); modifyRoleReplaceInducement(modelPort, seaSuperuserRole, 2, ROLE_CAPTAIN_OID); System.out.println("Modified role Sea Superuser - changed role inducement"); reconcileUser(modelPort, userLeChuckOid); System.out.println("LeChuck reconciled."); // Uncomment the following lines if you want to see what midPoint really did // ... because deleting the user will delete also all the traces (except logs and audit of course). deleteUser(modelPort, userGuybrushoid); deleteUser(modelPort, userLeChuckOid); deleteRole(modelPort, seaSuperuserRole); System.out.println("Deleted user(s)"); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private static void dump(Collection<? extends ObjectType> objects) { System.out.println("Objects returned: " + objects.size()); for (ObjectType objectType : objects) { System.out.println(" - " + ModelClientUtil.getOrig(objectType.getName()) + ": " + objectType); } } private static SystemConfigurationType getConfiguration(ModelPortType modelPort) throws FaultMessage { Holder<ObjectType> objectHolder = new Holder<ObjectType>(); Holder<OperationResultType> resultHolder = new Holder<OperationResultType>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); modelPort.getObject(ModelClientUtil.getTypeQName(SystemConfigurationType.class), SystemObjectsType.SYSTEM_CONFIGURATION.value(), options, objectHolder, resultHolder); return (SystemConfigurationType) objectHolder.value; } private static UserType getUser(ModelPortType modelPort, String oid) throws FaultMessage { Holder<ObjectType> objectHolder = new Holder<ObjectType>(); Holder<OperationResultType> resultHolder = new Holder<OperationResultType>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); modelPort.getObject(ModelClientUtil.getTypeQName(UserType.class), oid, options, objectHolder, resultHolder); return (UserType) objectHolder.value; } private static Collection<ResourceType> listResources(ModelPortType modelPort) throws SAXException, IOException, FaultMessage { SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder<ObjectListType> objectListHolder = new Holder<ObjectListType>(); Holder<OperationResultType> resultHolder = new Holder<OperationResultType>(); modelPort.searchObjects(ModelClientUtil.getTypeQName(ResourceType.class), null, options, objectListHolder, resultHolder); ObjectListType objectList = objectListHolder.value; return (Collection) objectList.getObject(); } private static Collection<UserType> listUsers(ModelPortType modelPort) throws SAXException, IOException, FaultMessage { SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder<ObjectListType> objectListHolder = new Holder<ObjectListType>(); Holder<OperationResultType> resultHolder = new Holder<OperationResultType>(); // let's say we want to get first 3 users, sorted alphabetically by user name QueryType queryType = new QueryType(); // holds search query + paging options PagingType pagingType = new PagingType(); pagingType.setMaxSize(3); pagingType.setOrderBy(ModelClientUtil.createItemPathType("name")); pagingType.setOrderDirection(OrderDirectionType.ASCENDING); queryType.setPaging(pagingType); modelPort.searchObjects(ModelClientUtil.getTypeQName(UserType.class), queryType, options, objectListHolder, resultHolder); ObjectListType objectList = objectListHolder.value; return (Collection) objectList.getObject(); } private static Collection<TaskType> listTasks(ModelPortType modelPort) throws SAXException, IOException, FaultMessage { SelectorQualifiedGetOptionsType operationOptions = new SelectorQualifiedGetOptionsType(); // Let's say we want to retrieve tasks' next scheduled time (because this may be a costly operation if // JDBC based quartz scheduler is used, the fetching of this attribute has to be explicitly requested) SelectorQualifiedGetOptionType getNextScheduledTimeOption = new SelectorQualifiedGetOptionType(); // prepare a selector (described by path) + options (saying to retrieve that attribute) ObjectSelectorType selector = new ObjectSelectorType(); selector.setPath(ModelClientUtil.createItemPathType("nextRunStartTimestamp")); getNextScheduledTimeOption.setSelector(selector); GetOperationOptionsType selectorOptions = new GetOperationOptionsType(); selectorOptions.setRetrieve(RetrieveOptionType.INCLUDE); getNextScheduledTimeOption.setOptions(selectorOptions); // add newly created option to the list of operation options operationOptions.getOption().add(getNextScheduledTimeOption); Holder<ObjectListType> objectListHolder = new Holder<ObjectListType>(); Holder<OperationResultType> resultHolder = new Holder<OperationResultType>(); modelPort.searchObjects(ModelClientUtil.getTypeQName(TaskType.class), null, operationOptions, objectListHolder, resultHolder); ObjectListType objectList = objectListHolder.value; return (Collection) objectList.getObject(); } private static String createUserGuybrush(ModelPortType modelPort, RoleType role) throws FaultMessage { Document doc = ModelClientUtil.getDocumnent(); UserType user = new UserType(); user.setName(ModelClientUtil.createPolyStringType("guybrush", doc)); user.setFullName(ModelClientUtil.createPolyStringType("Guybrush Threepwood", doc)); user.setGivenName(ModelClientUtil.createPolyStringType("Guybrush", doc)); user.setFamilyName(ModelClientUtil.createPolyStringType("Threepwood", doc)); user.setEmailAddress("guybrush@meleeisland.net"); user.getOrganization().add(ModelClientUtil.createPolyStringType("Pirate Brethren International", doc)); user.getOrganizationalUnit().add(ModelClientUtil.createPolyStringType("Pirate Wannabes", doc)); user.setCredentials(ModelClientUtil.createPasswordCredentials("IwannaBEaPIRATE")); if (role != null) { // create user with a role assignment AssignmentType roleAssignment = ModelClientUtil.createRoleAssignment(role.getOid()); user.getAssignment().add(roleAssignment); } return createUser(modelPort, user); } private static String createUserFromSystemResource(ModelPortType modelPort, String resourcePath) throws FileNotFoundException, JAXBException, FaultMessage { UserType user = ModelClientUtil.unmarshallResource(resourcePath); return createUser(modelPort, user); } private static String createRoleFromSystemResource(ModelPortType modelPort, String resourcePath) throws FileNotFoundException, JAXBException, FaultMessage { RoleType role = ModelClientUtil.unmarshallResource(resourcePath); return createRole(modelPort, role); } private static String createUser(ModelPortType modelPort, UserType userType) throws FaultMessage { ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(UserType.class)); deltaType.setChangeType(ChangeTypeType.ADD); deltaType.setObjectToAdd(userType); ObjectDeltaListType deltaListType = new ObjectDeltaListType(); deltaListType.getDelta().add(deltaType); ObjectDeltaOperationListType operationListType = modelPort.executeChanges(deltaListType, null); return ModelClientUtil.getOidFromDeltaOperationList(operationListType, deltaType); } private static String createRole(ModelPortType modelPort, RoleType roleType) throws FaultMessage { ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(RoleType.class)); deltaType.setChangeType(ChangeTypeType.ADD); deltaType.setObjectToAdd(roleType); ObjectDeltaListType deltaListType = new ObjectDeltaListType(); deltaListType.getDelta().add(deltaType); ObjectDeltaOperationListType operationListType = modelPort.executeChanges(deltaListType, null); return ModelClientUtil.getOidFromDeltaOperationList(operationListType, deltaType); } private static void changeUserPassword(ModelPortType modelPort, String oid, String newPassword) throws FaultMessage { ItemDeltaType passwordDelta = new ItemDeltaType(); passwordDelta.setModificationType(ModificationTypeType.REPLACE); passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value")); passwordDelta.getValue().add(ModelClientUtil.createProtectedString(newPassword)); ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(UserType.class)); deltaType.setChangeType(ChangeTypeType.MODIFY); deltaType.setOid(oid); deltaType.getItemDelta().add(passwordDelta); ObjectDeltaListType deltaListType = new ObjectDeltaListType(); deltaListType.getDelta().add(deltaType); modelPort.executeChanges(deltaListType, null); } private static void changeUserGivenName(ModelPortType modelPort, String oid, String newValue) throws FaultMessage { Document doc = ModelClientUtil.getDocumnent(); ObjectDeltaType userDelta = new ObjectDeltaType(); userDelta.setOid(oid); userDelta.setObjectType(ModelClientUtil.getTypeQName(UserType.class)); userDelta.setChangeType(ChangeTypeType.MODIFY); ItemDeltaType itemDelta = new ItemDeltaType(); itemDelta.setModificationType(ModificationTypeType.REPLACE); itemDelta.setPath(ModelClientUtil.createItemPathType("givenName")); itemDelta.getValue().add(ModelClientUtil.createPolyStringType(newValue, doc)); userDelta.getItemDelta().add(itemDelta); ObjectDeltaListType deltaList = new ObjectDeltaListType(); deltaList.getDelta().add(userDelta); modelPort.executeChanges(deltaList, null); } private static void reconcileUser(ModelPortType modelPort, String oid) throws FaultMessage { Document doc = ModelClientUtil.getDocumnent(); ObjectDeltaType userDelta = new ObjectDeltaType(); userDelta.setOid(oid); userDelta.setObjectType(ModelClientUtil.getTypeQName(UserType.class)); userDelta.setChangeType(ChangeTypeType.MODIFY); ObjectDeltaListType deltaList = new ObjectDeltaListType(); deltaList.getDelta().add(userDelta); ModelExecuteOptionsType optionsType = new ModelExecuteOptionsType(); optionsType.setReconcile(true); modelPort.executeChanges(deltaList, optionsType); } private static void assignRoles(ModelPortType modelPort, String userOid, String... roleOids) throws FaultMessage { modifyRoleAssignment(modelPort, userOid, true, roleOids); } private static void unAssignRoles(ModelPortType modelPort, String userOid, String... roleOids) throws FaultMessage { modifyRoleAssignment(modelPort, userOid, false, roleOids); } private static void modifyRoleAssignment(ModelPortType modelPort, String userOid, boolean isAdd, String... roleOids) throws FaultMessage { ItemDeltaType assignmentDelta = new ItemDeltaType(); if (isAdd) { assignmentDelta.setModificationType(ModificationTypeType.ADD); } else { assignmentDelta.setModificationType(ModificationTypeType.DELETE); } assignmentDelta.setPath(ModelClientUtil.createItemPathType("assignment")); for (String roleOid: roleOids) { assignmentDelta.getValue().add(ModelClientUtil.createRoleAssignment(roleOid)); } ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(UserType.class)); deltaType.setChangeType(ChangeTypeType.MODIFY); deltaType.setOid(userOid); deltaType.getItemDelta().add(assignmentDelta); ObjectDeltaOperationListType objectDeltaOperationList = modelPort.executeChanges(ModelClientUtil.createDeltaList(deltaType), null); for (ObjectDeltaOperationType objectDeltaOperation : objectDeltaOperationList.getDeltaOperation()) { if (!OperationResultStatusType.SUCCESS.equals(objectDeltaOperation.getExecutionResult().getStatus())) { System.out.println("*** Operation result = " + objectDeltaOperation.getExecutionResult().getStatus() + ": " + objectDeltaOperation.getExecutionResult().getMessage()); } } } private static void modifyRoleModifyInducement(ModelPortType modelPort, String roleOid) throws IOException, SAXException, FaultMessage { ItemDeltaType inducementDelta = new ItemDeltaType(); inducementDelta.setModificationType(ModificationTypeType.ADD); inducementDelta.setPath(ModelClientUtil.createItemPathType("inducement[3]/construction/attribute")); inducementDelta.getValue().add(ModelClientUtil.parseElement("<value>\n" + " <ref xmlns:ri=\"http://midpoint.evolveum.com/xml/ns/public/resource/instance-3\">ri:pager</ref>\n" + " <outbound>\n" + " <expression>\n" + " <value>00-000-001</value>\n" + " <value>00-000-003</value>\n" + " </expression>\n" + " </outbound>\n" + " </value>")); ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(RoleType.class)); deltaType.setChangeType(ChangeTypeType.MODIFY); deltaType.setOid(roleOid); deltaType.getItemDelta().add(inducementDelta); ObjectDeltaListType deltaListType = new ObjectDeltaListType(); deltaListType.getDelta().add(deltaType); ObjectDeltaOperationListType objectDeltaOperationList = modelPort.executeChanges(deltaListType, null); for (ObjectDeltaOperationType objectDeltaOperation : objectDeltaOperationList.getDeltaOperation()) { if (!OperationResultStatusType.SUCCESS.equals(objectDeltaOperation.getExecutionResult().getStatus())) { System.out.println("*** Operation result = " + objectDeltaOperation.getExecutionResult().getStatus() + ": " + objectDeltaOperation.getExecutionResult().getMessage()); } } } // removes inducement with a given ID and replaces it with a new one private static void modifyRoleReplaceInducement(ModelPortType modelPort, String roleOid, int oldId, String newInducementOid) throws FaultMessage, IOException, SAXException { ItemDeltaType inducementDeleteDelta = new ItemDeltaType(); inducementDeleteDelta.setModificationType(ModificationTypeType.DELETE); inducementDeleteDelta.setPath(ModelClientUtil.createItemPathType("inducement")); inducementDeleteDelta.getValue().add(ModelClientUtil.parseElement("<value><id>"+oldId+"</id></value>")); ItemDeltaType inducementAddDelta = new ItemDeltaType(); inducementAddDelta.setModificationType(ModificationTypeType.ADD); inducementAddDelta.setPath(ModelClientUtil.createItemPathType("inducement")); inducementAddDelta.getValue().add(ModelClientUtil.createRoleAssignment(newInducementOid)); ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(RoleType.class)); deltaType.setChangeType(ChangeTypeType.MODIFY); deltaType.setOid(roleOid); deltaType.getItemDelta().add(inducementDeleteDelta); deltaType.getItemDelta().add(inducementAddDelta); ObjectDeltaListType deltaListType = new ObjectDeltaListType(); deltaListType.getDelta().add(deltaType); ObjectDeltaOperationListType objectDeltaOperationList = modelPort.executeChanges(deltaListType, null); for (ObjectDeltaOperationType objectDeltaOperation : objectDeltaOperationList.getDeltaOperation()) { if (!OperationResultStatusType.SUCCESS.equals(objectDeltaOperation.getExecutionResult().getStatus())) { System.out.println("*** Operation result = " + objectDeltaOperation.getExecutionResult().getStatus() + ": " + objectDeltaOperation.getExecutionResult().getMessage()); } } } private static UserType searchUserByName(ModelPortType modelPort, String username) throws SAXException, IOException, FaultMessage, JAXBException { // WARNING: in a real case make sure that the username is properly escaped before putting it in XML SearchFilterType filter = ModelClientUtil.parseSearchFilterType( "<equal xmlns='http://prism.evolveum.com/xml/ns/public/query-3' xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3' >" + "<path>c:name</path>" + "<value>" + username + "</value>" + "</equal>" ); QueryType query = new QueryType(); query.setFilter(filter); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder<ObjectListType> objectListHolder = new Holder<ObjectListType>(); Holder<OperationResultType> resultHolder = new Holder<OperationResultType>(); modelPort.searchObjects(ModelClientUtil.getTypeQName(UserType.class), query, options, objectListHolder, resultHolder); ObjectListType objectList = objectListHolder.value; List<ObjectType> objects = objectList.getObject(); if (objects.isEmpty()) { return null; } if (objects.size() == 1) { return (UserType) objects.get(0); } throw new IllegalStateException("Expected to find a single user with username '"+username+"' but found "+objects.size()+" users instead"); } private static RoleType searchRoleByName(ModelPortType modelPort, String roleName) throws SAXException, IOException, FaultMessage, JAXBException { // WARNING: in a real case make sure that the role name is properly escaped before putting it in XML SearchFilterType filter = ModelClientUtil.parseSearchFilterType( "<equal xmlns='http://prism.evolveum.com/xml/ns/public/query-3' xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3' >" + "<path>c:name</path>" + "<value>" + roleName + "</value>" + "</equal>" ); QueryType query = new QueryType(); query.setFilter(filter); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder<ObjectListType> objectListHolder = new Holder<ObjectListType>(); Holder<OperationResultType> resultHolder = new Holder<OperationResultType>(); modelPort.searchObjects(ModelClientUtil.getTypeQName(RoleType.class), query, options, objectListHolder, resultHolder); ObjectListType objectList = objectListHolder.value; List<ObjectType> objects = objectList.getObject(); if (objects.isEmpty()) { return null; } if (objects.size() == 1) { return (RoleType) objects.get(0); } throw new IllegalStateException("Expected to find a single role with name '"+roleName+"' but found "+objects.size()+" users instead"); } private static Collection<RoleType> listRequestableRoles(ModelPortType modelPort) throws SAXException, IOException, FaultMessage, JAXBException { SearchFilterType filter = ModelClientUtil.parseSearchFilterType( "<equal xmlns='http://prism.evolveum.com/xml/ns/public/query-3' xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3' >" + "<path>c:requestable</path>" + "<value>true</value>" + "</equal>" ); QueryType query = new QueryType(); query.setFilter(filter); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder<ObjectListType> objectListHolder = new Holder<ObjectListType>(); Holder<OperationResultType> resultHolder = new Holder<OperationResultType>(); modelPort.searchObjects(ModelClientUtil.getTypeQName(RoleType.class), query, options, objectListHolder, resultHolder); ObjectListType objectList = objectListHolder.value; return (Collection) objectList.getObject(); } private static void deleteUser(ModelPortType modelPort, String oid) throws FaultMessage { ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(UserType.class)); deltaType.setChangeType(ChangeTypeType.DELETE); deltaType.setOid(oid); ObjectDeltaListType deltaListType = new ObjectDeltaListType(); deltaListType.getDelta().add(deltaType); ModelExecuteOptionsType executeOptionsType = new ModelExecuteOptionsType(); executeOptionsType.setRaw(true); modelPort.executeChanges(deltaListType, executeOptionsType); } private static void deleteRole(ModelPortType modelPort, String oid) throws FaultMessage { ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(RoleType.class)); deltaType.setChangeType(ChangeTypeType.DELETE); deltaType.setOid(oid); ObjectDeltaListType deltaListType = new ObjectDeltaListType(); deltaListType.getDelta().add(deltaType); ModelExecuteOptionsType executeOptionsType = new ModelExecuteOptionsType(); executeOptionsType.setRaw(true); modelPort.executeChanges(deltaListType, executeOptionsType); } private static void deleteTask(ModelPortType modelPort, String oid) throws FaultMessage { ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(TaskType.class)); deltaType.setChangeType(ChangeTypeType.DELETE); deltaType.setOid(oid); ObjectDeltaListType deltaListType = new ObjectDeltaListType(); deltaListType.getDelta().add(deltaType); ModelExecuteOptionsType executeOptionsType = new ModelExecuteOptionsType(); executeOptionsType.setRaw(true); modelPort.executeChanges(deltaListType, executeOptionsType); } public static ModelPortType createModelPort(String[] args) { String endpointUrl = DEFAULT_ENDPOINT_URL; if (args.length > 0) { endpointUrl = args[0]; } System.out.println("Endpoint URL: "+endpointUrl); // uncomment this if you want to use Fiddler or any other proxy //ProxySelector.setDefault(new MyProxySelector("127.0.0.1", 8888)); ModelService modelService = new ModelService(); ModelPortType modelPort = modelService.getModelPort(); BindingProvider bp = (BindingProvider)modelPort; Map<String, Object> requestContext = bp.getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointUrl); org.apache.cxf.endpoint.Client client = ClientProxy.getClient(modelPort); org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint(); Map<String,Object> outProps = new HashMap<String,Object>(); outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); outProps.put(WSHandlerConstants.USER, ADM_USERNAME); outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST); outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName()); WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps); cxfEndpoint.getOutInterceptors().add(wssOut); // enable the following to get client-side logging of outgoing requests and incoming responses cxfEndpoint.getOutInterceptors().add(new LoggingOutInterceptor()); cxfEndpoint.getInInterceptors().add(new LoggingInInterceptor()); return modelPort; } }
apache-2.0
usc-isi-i2/fril-service
src/main/java/cdc/impl/datasource/wrappers/propertiescache/CacheInterface.java
2154
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * 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 the FRIL Framework. * * The Initial Developers of the Original Code are * The Department of Math and Computer Science, Emory University and * The Centers for Disease Control and Prevention. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package cdc.impl.datasource.wrappers.propertiescache; import java.io.IOException; import cdc.datamodel.DataRow; import cdc.utils.RJException; public interface CacheInterface { public CachedObjectInterface cacheObject(DataRow data) throws IOException; public DataRow getObject(CachedObjectInterface co) throws IOException, RJException; public void trash() throws IOException; }
apache-2.0
ChinmaySKulkarni/hbase
hbase-rest/src/main/java/org/apache/hadoop/hbase/rest/model/ScannerModel.java
29407
/* * * 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.rest.model; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.NavigableSet; import javax.ws.rs.core.MediaType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.apache.hadoop.hbase.CompareOperator; import org.apache.hadoop.hbase.HConstants; import org.apache.yetus.audience.InterfaceAudience; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.filter.BinaryPrefixComparator; import org.apache.hadoop.hbase.filter.BitComparator; import org.apache.hadoop.hbase.filter.ByteArrayComparable; import org.apache.hadoop.hbase.filter.ColumnCountGetFilter; import org.apache.hadoop.hbase.filter.ColumnPaginationFilter; import org.apache.hadoop.hbase.filter.ColumnPrefixFilter; import org.apache.hadoop.hbase.filter.ColumnRangeFilter; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.filter.DependentColumnFilter; import org.apache.hadoop.hbase.filter.FamilyFilter; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.filter.InclusiveStopFilter; import org.apache.hadoop.hbase.filter.KeyOnlyFilter; import org.apache.hadoop.hbase.filter.MultiRowRangeFilter; import org.apache.hadoop.hbase.filter.MultiRowRangeFilter.RowRange; import org.apache.hadoop.hbase.filter.MultipleColumnPrefixFilter; import org.apache.hadoop.hbase.filter.NullComparator; import org.apache.hadoop.hbase.filter.PageFilter; import org.apache.hadoop.hbase.filter.PrefixFilter; import org.apache.hadoop.hbase.filter.QualifierFilter; import org.apache.hadoop.hbase.filter.RandomRowFilter; import org.apache.hadoop.hbase.filter.RegexStringComparator; import org.apache.hadoop.hbase.filter.RowFilter; import org.apache.hadoop.hbase.filter.SingleColumnValueExcludeFilter; import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; import org.apache.hadoop.hbase.filter.SkipFilter; import org.apache.hadoop.hbase.filter.SubstringComparator; import org.apache.hadoop.hbase.filter.TimestampsFilter; import org.apache.hadoop.hbase.filter.ValueFilter; import org.apache.hadoop.hbase.filter.WhileMatchFilter; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.rest.ProtobufMessageHandler; import org.apache.hadoop.hbase.rest.protobuf.generated.ScannerMessage.Scanner; import org.apache.hadoop.hbase.security.visibility.Authorizations; import org.apache.hadoop.hbase.util.ByteStringer; import org.apache.hadoop.hbase.util.Bytes; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.google.protobuf.ByteString; /** * A representation of Scanner parameters. * * <pre> * &lt;complexType name="Scanner"&gt; * &lt;sequence&gt; * &lt;element name="column" type="base64Binary" minOccurs="0" maxOccurs="unbounded"/&gt; * &lt;element name="filter" type="string" minOccurs="0" maxOccurs="1"&gt;&lt;/element&gt; * &lt;/sequence&gt; * &lt;attribute name="startRow" type="base64Binary"&gt;&lt;/attribute&gt; * &lt;attribute name="endRow" type="base64Binary"&gt;&lt;/attribute&gt; * &lt;attribute name="batch" type="int"&gt;&lt;/attribute&gt; * &lt;attribute name="caching" type="int"&gt;&lt;/attribute&gt; * &lt;attribute name="startTime" type="int"&gt;&lt;/attribute&gt; * &lt;attribute name="endTime" type="int"&gt;&lt;/attribute&gt; * &lt;attribute name="maxVersions" type="int"&gt;&lt;/attribute&gt; * &lt;/complexType&gt; * </pre> */ @XmlRootElement(name="Scanner") @JsonInclude(JsonInclude.Include.NON_NULL) @InterfaceAudience.Private public class ScannerModel implements ProtobufMessageHandler, Serializable { private static final long serialVersionUID = 1L; private byte[] startRow = HConstants.EMPTY_START_ROW; private byte[] endRow = HConstants.EMPTY_END_ROW; private List<byte[]> columns = new ArrayList<>(); private int batch = Integer.MAX_VALUE; private long startTime = 0; private long endTime = Long.MAX_VALUE; private String filter = null; private int maxVersions = Integer.MAX_VALUE; private int caching = -1; private List<String> labels = new ArrayList<>(); private boolean cacheBlocks = true; /** * Implement lazily-instantiated singleton as per recipe * here: http://literatejava.com/jvm/fastest-threadsafe-singleton-jvm/ */ private static class JaxbJsonProviderHolder { static final JacksonJaxbJsonProvider INSTANCE = new JacksonJaxbJsonProvider(); } @XmlRootElement static class FilterModel { @XmlRootElement static class ByteArrayComparableModel { @XmlAttribute public String type; @XmlAttribute public String value; @XmlAttribute public String op; static enum ComparatorType { BinaryComparator, BinaryPrefixComparator, BitComparator, NullComparator, RegexStringComparator, SubstringComparator } public ByteArrayComparableModel() { } public ByteArrayComparableModel( ByteArrayComparable comparator) { String typeName = comparator.getClass().getSimpleName(); ComparatorType type = ComparatorType.valueOf(typeName); this.type = typeName; switch (type) { case BinaryComparator: case BinaryPrefixComparator: this.value = Bytes.toString(Base64.getEncoder().encode(comparator.getValue())); break; case BitComparator: this.value = Bytes.toString(Base64.getEncoder().encode(comparator.getValue())); this.op = ((BitComparator)comparator).getOperator().toString(); break; case NullComparator: break; case RegexStringComparator: case SubstringComparator: this.value = Bytes.toString(comparator.getValue()); break; default: throw new RuntimeException("unhandled filter type: " + type); } } public ByteArrayComparable build() { ByteArrayComparable comparator; switch (ComparatorType.valueOf(type)) { case BinaryComparator: comparator = new BinaryComparator(Base64.getDecoder().decode(value)); break; case BinaryPrefixComparator: comparator = new BinaryPrefixComparator(Base64.getDecoder().decode(value)); break; case BitComparator: comparator = new BitComparator(Base64.getDecoder().decode(value), BitComparator.BitwiseOp.valueOf(op)); break; case NullComparator: comparator = new NullComparator(); break; case RegexStringComparator: comparator = new RegexStringComparator(value); break; case SubstringComparator: comparator = new SubstringComparator(value); break; default: throw new RuntimeException("unhandled comparator type: " + type); } return comparator; } } // A grab bag of fields, would have been a union if this were C. // These are null by default and will only be serialized if set (non null). @XmlAttribute public String type; @XmlAttribute public String op; @XmlElement ByteArrayComparableModel comparator; @XmlAttribute public String value; @XmlElement public List<FilterModel> filters; @XmlAttribute public Integer limit; @XmlAttribute public Integer offset; @XmlAttribute public String family; @XmlAttribute public String qualifier; @XmlAttribute public Boolean ifMissing; @XmlAttribute public Boolean latestVersion; @XmlAttribute public String minColumn; @XmlAttribute public Boolean minColumnInclusive; @XmlAttribute public String maxColumn; @XmlAttribute public Boolean maxColumnInclusive; @XmlAttribute public Boolean dropDependentColumn; @XmlAttribute public Float chance; @XmlElement public List<String> prefixes; @XmlElement private List<RowRange> ranges; @XmlElement public List<Long> timestamps; static enum FilterType { ColumnCountGetFilter, ColumnPaginationFilter, ColumnPrefixFilter, ColumnRangeFilter, DependentColumnFilter, FamilyFilter, FilterList, FirstKeyOnlyFilter, InclusiveStopFilter, KeyOnlyFilter, MultipleColumnPrefixFilter, MultiRowRangeFilter, PageFilter, PrefixFilter, QualifierFilter, RandomRowFilter, RowFilter, SingleColumnValueExcludeFilter, SingleColumnValueFilter, SkipFilter, TimestampsFilter, ValueFilter, WhileMatchFilter } public FilterModel() { } public FilterModel(Filter filter) { String typeName = filter.getClass().getSimpleName(); FilterType type = FilterType.valueOf(typeName); this.type = typeName; switch (type) { case ColumnCountGetFilter: this.limit = ((ColumnCountGetFilter)filter).getLimit(); break; case ColumnPaginationFilter: this.limit = ((ColumnPaginationFilter)filter).getLimit(); this.offset = ((ColumnPaginationFilter)filter).getOffset(); break; case ColumnPrefixFilter: byte[] src = ((ColumnPrefixFilter)filter).getPrefix(); this.value = Bytes.toString(Base64.getEncoder().encode(src)); break; case ColumnRangeFilter: ColumnRangeFilter crf = (ColumnRangeFilter)filter; this.minColumn = Bytes.toString(Base64.getEncoder().encode(crf.getMinColumn())); this.minColumnInclusive = crf.getMinColumnInclusive(); this.maxColumn = Bytes.toString(Base64.getEncoder().encode(crf.getMaxColumn())); this.maxColumnInclusive = crf.getMaxColumnInclusive(); break; case DependentColumnFilter: { DependentColumnFilter dcf = (DependentColumnFilter)filter; this.family = Bytes.toString(Base64.getEncoder().encode(dcf.getFamily())); byte[] qualifier = dcf.getQualifier(); if (qualifier != null) { this.qualifier = Bytes.toString(Base64.getEncoder().encode(qualifier)); } this.op = dcf.getCompareOperator().toString(); this.comparator = new ByteArrayComparableModel(dcf.getComparator()); this.dropDependentColumn = dcf.dropDependentColumn(); } break; case FilterList: this.op = ((FilterList)filter).getOperator().toString(); this.filters = new ArrayList<>(); for (Filter child: ((FilterList)filter).getFilters()) { this.filters.add(new FilterModel(child)); } break; case FirstKeyOnlyFilter: case KeyOnlyFilter: break; case InclusiveStopFilter: this.value = Bytes.toString(Base64.getEncoder().encode( ((InclusiveStopFilter)filter).getStopRowKey())); break; case MultipleColumnPrefixFilter: this.prefixes = new ArrayList<>(); for (byte[] prefix: ((MultipleColumnPrefixFilter)filter).getPrefix()) { this.prefixes.add(Bytes.toString(Base64.getEncoder().encode(prefix))); } break; case MultiRowRangeFilter: this.ranges = new ArrayList<>(); for(RowRange range : ((MultiRowRangeFilter)filter).getRowRanges()) { this.ranges.add(new RowRange(range.getStartRow(), range.isStartRowInclusive(), range.getStopRow(), range.isStopRowInclusive())); } break; case PageFilter: this.value = Long.toString(((PageFilter)filter).getPageSize()); break; case PrefixFilter: this.value = Bytes.toString(Base64.getEncoder().encode( ((PrefixFilter)filter).getPrefix())); break; case FamilyFilter: case QualifierFilter: case RowFilter: case ValueFilter: this.op = ((CompareFilter)filter).getCompareOperator().toString(); this.comparator = new ByteArrayComparableModel( ((CompareFilter)filter).getComparator()); break; case RandomRowFilter: this.chance = ((RandomRowFilter)filter).getChance(); break; case SingleColumnValueExcludeFilter: case SingleColumnValueFilter: { SingleColumnValueFilter scvf = (SingleColumnValueFilter) filter; this.family = Bytes.toString(Base64.getEncoder().encode(scvf.getFamily())); byte[] qualifier = scvf.getQualifier(); if (qualifier != null) { this.qualifier = Bytes.toString(Base64.getEncoder().encode(qualifier)); } this.op = scvf.getCompareOperator().toString(); this.comparator = new ByteArrayComparableModel(scvf.getComparator()); if (scvf.getFilterIfMissing()) { this.ifMissing = true; } if (scvf.getLatestVersionOnly()) { this.latestVersion = true; } } break; case SkipFilter: this.filters = new ArrayList<>(); this.filters.add(new FilterModel(((SkipFilter)filter).getFilter())); break; case TimestampsFilter: this.timestamps = ((TimestampsFilter)filter).getTimestamps(); break; case WhileMatchFilter: this.filters = new ArrayList<>(); this.filters.add( new FilterModel(((WhileMatchFilter)filter).getFilter())); break; default: throw new RuntimeException("unhandled filter type " + type); } } public Filter build() { Filter filter; switch (FilterType.valueOf(type)) { case ColumnCountGetFilter: filter = new ColumnCountGetFilter(limit); break; case ColumnPaginationFilter: filter = new ColumnPaginationFilter(limit, offset); break; case ColumnPrefixFilter: filter = new ColumnPrefixFilter(Base64.getDecoder().decode(value)); break; case ColumnRangeFilter: filter = new ColumnRangeFilter(Base64.getDecoder().decode(minColumn), minColumnInclusive, Base64.getDecoder().decode(maxColumn), maxColumnInclusive); break; case DependentColumnFilter: filter = new DependentColumnFilter(Base64.getDecoder().decode(family), qualifier != null ? Base64.getDecoder().decode(qualifier) : null, dropDependentColumn, CompareOperator.valueOf(op), comparator.build()); break; case FamilyFilter: filter = new FamilyFilter(CompareOperator.valueOf(op), comparator.build()); break; case FilterList: { List<Filter> list = new ArrayList<>(filters.size()); for (FilterModel model: filters) { list.add(model.build()); } filter = new FilterList(FilterList.Operator.valueOf(op), list); } break; case FirstKeyOnlyFilter: filter = new FirstKeyOnlyFilter(); break; case InclusiveStopFilter: filter = new InclusiveStopFilter(Base64.getDecoder().decode(value)); break; case KeyOnlyFilter: filter = new KeyOnlyFilter(); break; case MultipleColumnPrefixFilter: { byte[][] values = new byte[prefixes.size()][]; for (int i = 0; i < prefixes.size(); i++) { values[i] = Base64.getDecoder().decode(prefixes.get(i)); } filter = new MultipleColumnPrefixFilter(values); } break; case MultiRowRangeFilter: { filter = new MultiRowRangeFilter(ranges); } break; case PageFilter: filter = new PageFilter(Long.parseLong(value)); break; case PrefixFilter: filter = new PrefixFilter(Base64.getDecoder().decode(value)); break; case QualifierFilter: filter = new QualifierFilter(CompareOperator.valueOf(op), comparator.build()); break; case RandomRowFilter: filter = new RandomRowFilter(chance); break; case RowFilter: filter = new RowFilter(CompareOperator.valueOf(op), comparator.build()); break; case SingleColumnValueFilter: filter = new SingleColumnValueFilter(Base64.getDecoder().decode(family), qualifier != null ? Base64.getDecoder().decode(qualifier) : null, CompareOperator.valueOf(op), comparator.build()); if (ifMissing != null) { ((SingleColumnValueFilter)filter).setFilterIfMissing(ifMissing); } if (latestVersion != null) { ((SingleColumnValueFilter)filter).setLatestVersionOnly(latestVersion); } break; case SingleColumnValueExcludeFilter: filter = new SingleColumnValueExcludeFilter(Base64.getDecoder().decode(family), qualifier != null ? Base64.getDecoder().decode(qualifier) : null, CompareOperator.valueOf(op), comparator.build()); if (ifMissing != null) { ((SingleColumnValueExcludeFilter)filter).setFilterIfMissing(ifMissing); } if (latestVersion != null) { ((SingleColumnValueExcludeFilter)filter).setLatestVersionOnly(latestVersion); } break; case SkipFilter: filter = new SkipFilter(filters.get(0).build()); break; case TimestampsFilter: filter = new TimestampsFilter(timestamps); break; case ValueFilter: filter = new ValueFilter(CompareOperator.valueOf(op), comparator.build()); break; case WhileMatchFilter: filter = new WhileMatchFilter(filters.get(0).build()); break; default: throw new RuntimeException("unhandled filter type: " + type); } return filter; } } /** * Get the <code>JacksonJaxbJsonProvider</code> instance; * * @return A <code>JacksonJaxbJsonProvider</code>. */ private static JacksonJaxbJsonProvider getJasonProvider() { return JaxbJsonProviderHolder.INSTANCE; } /** * @param s the JSON representation of the filter * @return the filter * @throws Exception */ public static Filter buildFilter(String s) throws Exception { FilterModel model = getJasonProvider().locateMapper(FilterModel.class, MediaType.APPLICATION_JSON_TYPE).readValue(s, FilterModel.class); return model.build(); } /** * @param filter the filter * @return the JSON representation of the filter * @throws Exception */ public static String stringifyFilter(final Filter filter) throws Exception { return getJasonProvider().locateMapper(FilterModel.class, MediaType.APPLICATION_JSON_TYPE).writeValueAsString(new FilterModel(filter)); } private static final byte[] COLUMN_DIVIDER = Bytes.toBytes(":"); /** * @param scan the scan specification * @throws Exception */ public static ScannerModel fromScan(Scan scan) throws Exception { ScannerModel model = new ScannerModel(); model.setStartRow(scan.getStartRow()); model.setEndRow(scan.getStopRow()); Map<byte [], NavigableSet<byte []>> families = scan.getFamilyMap(); if (families != null) { for (Map.Entry<byte [], NavigableSet<byte []>> entry : families.entrySet()) { if (entry.getValue() != null) { for (byte[] qualifier: entry.getValue()) { model.addColumn(Bytes.add(entry.getKey(), COLUMN_DIVIDER, qualifier)); } } else { model.addColumn(entry.getKey()); } } } model.setStartTime(scan.getTimeRange().getMin()); model.setEndTime(scan.getTimeRange().getMax()); int caching = scan.getCaching(); if (caching > 0) { model.setCaching(caching); } int batch = scan.getBatch(); if (batch > 0) { model.setBatch(batch); } int maxVersions = scan.getMaxVersions(); if (maxVersions > 0) { model.setMaxVersions(maxVersions); } Filter filter = scan.getFilter(); if (filter != null) { model.setFilter(stringifyFilter(filter)); } // Add the visbility labels if found in the attributes Authorizations authorizations = scan.getAuthorizations(); if (authorizations != null) { List<String> labels = authorizations.getLabels(); for (String label : labels) { model.addLabel(label); } } return model; } /** * Default constructor */ public ScannerModel() {} /** * Constructor * @param startRow the start key of the row-range * @param endRow the end key of the row-range * @param columns the columns to scan * @param batch the number of values to return in batch * @param caching the number of rows that the scanner will fetch at once * @param endTime the upper bound on timestamps of values of interest * @param maxVersions the maximum number of versions to return * @param filter a filter specification * (values with timestamps later than this are excluded) */ public ScannerModel(byte[] startRow, byte[] endRow, List<byte[]> columns, int batch, int caching, long endTime, int maxVersions, String filter) { super(); this.startRow = startRow; this.endRow = endRow; this.columns = columns; this.batch = batch; this.caching = caching; this.endTime = endTime; this.maxVersions = maxVersions; this.filter = filter; } /** * Constructor * @param startRow the start key of the row-range * @param endRow the end key of the row-range * @param columns the columns to scan * @param batch the number of values to return in batch * @param caching the number of rows that the scanner will fetch at once * @param startTime the lower bound on timestamps of values of interest * (values with timestamps earlier than this are excluded) * @param endTime the upper bound on timestamps of values of interest * (values with timestamps later than this are excluded) * @param filter a filter specification */ public ScannerModel(byte[] startRow, byte[] endRow, List<byte[]> columns, int batch, int caching, long startTime, long endTime, String filter) { super(); this.startRow = startRow; this.endRow = endRow; this.columns = columns; this.batch = batch; this.caching = caching; this.startTime = startTime; this.endTime = endTime; this.filter = filter; } /** * Add a column to the column set * @param column the column name, as &lt;column&gt;(:&lt;qualifier&gt;)? */ public void addColumn(byte[] column) { columns.add(column); } /** * Add a visibility label to the scan */ public void addLabel(String label) { labels.add(label); } /** * @return true if a start row was specified */ public boolean hasStartRow() { return !Bytes.equals(startRow, HConstants.EMPTY_START_ROW); } /** * @return start row */ @XmlAttribute public byte[] getStartRow() { return startRow; } /** * @return true if an end row was specified */ public boolean hasEndRow() { return !Bytes.equals(endRow, HConstants.EMPTY_END_ROW); } /** * @return end row */ @XmlAttribute public byte[] getEndRow() { return endRow; } /** * @return list of columns of interest in column:qualifier format, or empty for all */ @XmlElement(name="column") public List<byte[]> getColumns() { return columns; } @XmlElement(name="labels") public List<String> getLabels() { return labels; } /** * @return the number of cells to return in batch */ @XmlAttribute public int getBatch() { return batch; } /** * @return the number of rows that the scanner to fetch at once */ @XmlAttribute public int getCaching() { return caching; } /** * @return true if HFile blocks should be cached on the servers for this scan, false otherwise */ @XmlAttribute public boolean getCacheBlocks() { return cacheBlocks; } /** * @return the lower bound on timestamps of items of interest */ @XmlAttribute public long getStartTime() { return startTime; } /** * @return the upper bound on timestamps of items of interest */ @XmlAttribute public long getEndTime() { return endTime; } /** * @return maximum number of versions to return */ @XmlAttribute public int getMaxVersions() { return maxVersions; } /** * @return the filter specification */ @XmlElement public String getFilter() { return filter; } /** * @param startRow start row */ public void setStartRow(byte[] startRow) { this.startRow = startRow; } /** * @param endRow end row */ public void setEndRow(byte[] endRow) { this.endRow = endRow; } /** * @param columns list of columns of interest in column:qualifier format, or empty for all */ public void setColumns(List<byte[]> columns) { this.columns = columns; } /** * @param batch the number of cells to return in batch */ public void setBatch(int batch) { this.batch = batch; } /** * @param caching the number of rows to fetch at once */ public void setCaching(int caching) { this.caching = caching; } /** * @param value true if HFile blocks should be cached on the servers for this scan, false otherwise */ public void setCacheBlocks(boolean value) { this.cacheBlocks = value; } /** * @param maxVersions maximum number of versions to return */ public void setMaxVersions(int maxVersions) { this.maxVersions = maxVersions; } /** * @param startTime the lower bound on timestamps of values of interest */ public void setStartTime(long startTime) { this.startTime = startTime; } /** * @param endTime the upper bound on timestamps of values of interest */ public void setEndTime(long endTime) { this.endTime = endTime; } /** * @param filter the filter specification */ public void setFilter(String filter) { this.filter = filter; } @Override public byte[] createProtobufOutput() { Scanner.Builder builder = Scanner.newBuilder(); if (!Bytes.equals(startRow, HConstants.EMPTY_START_ROW)) { builder.setStartRow(ByteStringer.wrap(startRow)); } if (!Bytes.equals(endRow, HConstants.EMPTY_START_ROW)) { builder.setEndRow(ByteStringer.wrap(endRow)); } for (byte[] column: columns) { builder.addColumns(ByteStringer.wrap(column)); } if (startTime != 0) { builder.setStartTime(startTime); } if (endTime != 0) { builder.setEndTime(endTime); } builder.setBatch(getBatch()); if (caching > 0) { builder.setCaching(caching); } builder.setMaxVersions(maxVersions); if (filter != null) { builder.setFilter(filter); } if (labels != null && labels.size() > 0) { for (String label : labels) builder.addLabels(label); } builder.setCacheBlocks(cacheBlocks); return builder.build().toByteArray(); } @Override public ProtobufMessageHandler getObjectFromMessage(byte[] message) throws IOException { Scanner.Builder builder = Scanner.newBuilder(); ProtobufUtil.mergeFrom(builder, message); if (builder.hasStartRow()) { startRow = builder.getStartRow().toByteArray(); } if (builder.hasEndRow()) { endRow = builder.getEndRow().toByteArray(); } for (ByteString column: builder.getColumnsList()) { addColumn(column.toByteArray()); } if (builder.hasBatch()) { batch = builder.getBatch(); } if (builder.hasCaching()) { caching = builder.getCaching(); } if (builder.hasStartTime()) { startTime = builder.getStartTime(); } if (builder.hasEndTime()) { endTime = builder.getEndTime(); } if (builder.hasMaxVersions()) { maxVersions = builder.getMaxVersions(); } if (builder.hasFilter()) { filter = builder.getFilter(); } if (builder.getLabelsList() != null) { List<String> labels = builder.getLabelsList(); for(String label : labels) { addLabel(label); } } if (builder.hasCacheBlocks()) { this.cacheBlocks = builder.getCacheBlocks(); } return this; } }
apache-2.0
AK-47-D/cms
src/main/java/com/ak47/cms/cms/controller/UserController.java
1466
package com.ak47.cms.cms.controller; import com.ak47.cms.cms.entity.User; import com.ak47.cms.cms.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.util.Date; @Controller public class UserController { @Autowired private UserService userService; @RequestMapping(value="homePage",method = RequestMethod.GET) public String toHomePage(){ return "cms_layout/calendar_page"; } @RequestMapping(value="saveUser",method = RequestMethod.POST) @ResponseBody public String saveUser(User user){ userService.saveUser(user); return "true"; } @RequestMapping(value="doLogin",method = RequestMethod.POST) @ResponseBody public String doLogin(User user , HttpSession session ){ if(userService.doLogin(user)){ session.setAttribute("currentUser",user.getUserName() ); return "200"; } return "false"; } @RequestMapping(value="logout",method = RequestMethod.POST) @ResponseBody public String logout(User user , HttpSession session ){ session.removeAttribute("currentUser"); return "true"; } }
apache-2.0
Talend/components
components/components-netsuite/components-netsuite-runtime/src/main/java/org/talend/components/netsuite/client/NetSuiteCredentials.java
6945
//============================================================================ // // Copyright (C) 2006-2022 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // //============================================================================ package org.talend.components.netsuite.client; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; import java.util.Properties; import org.apache.cxf.helpers.IOUtils; /** * Holds information required for logging in of a client in NetSuite. */ public class NetSuiteCredentials { private String email; private String password; private String account; private String roleId; private String applicationId; private int numberOfSeats = 1; private String id; private String companyId; private String userId; private String partnerId; private String privateKey; // path to private key in der format private boolean useSsoLogin = false; public NetSuiteCredentials() { } public NetSuiteCredentials(String email, String password, String account, String roleId) { this(email, password, account, roleId, 1); } public NetSuiteCredentials(String email, String password, String account, String roleId, int numberOfSeats) { this.email = email; this.password = password; this.account = account; this.roleId = roleId; this.numberOfSeats = numberOfSeats; } public String getAccount() { return account; } public String getEmail() { return email; } public String getPassword() { return password; } public String getRoleId() { return roleId; } public int getNumberOfSeats() { return numberOfSeats; } public void setAccount(String account) { this.account = account; } public void setEmail(String email) { this.email = email; } public String getApplicationId() { return applicationId; } public void setApplicationId(String applicationId) { this.applicationId = applicationId; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } public void setPassword(String password) { this.password = password; } public void setRoleId(String roleId) { this.roleId = roleId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getPartnerId() { return partnerId; } public void setPartnerId(String partnerId) { this.partnerId = partnerId; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public boolean isUseSsoLogin() { return useSsoLogin; } public void setUseSsoLogin(boolean useSsoLogin) { this.useSsoLogin = useSsoLogin; } public static NetSuiteCredentials loadFromLocation(URI location, String propertyPrefix) throws IOException { InputStream stream; if (location.getScheme().equals("classpath")) { stream = NetSuiteCredentials.class.getResourceAsStream(location.getSchemeSpecificPart()); } else { stream = location.toURL().openStream(); } Properties properties = new Properties(); try { properties.load(stream); } finally { stream.close(); } return loadFromProperties(properties, propertyPrefix); } /** * Load credentials from plain {@code Properties}. * * @param properties properties object * @param prefix prefix for property keys, can be empty * @return credentials object */ public static NetSuiteCredentials loadFromProperties(Properties properties, String prefix) { NetSuiteCredentials credentials = new NetSuiteCredentials(); credentials.setEmail(properties.getProperty(prefix + "email")); credentials.setPassword(properties.getProperty(prefix + "password")); credentials.setRoleId(properties.getProperty(prefix + "roleId")); credentials.setAccount(properties.getProperty(prefix + "account")); credentials.setApplicationId(properties.getProperty(prefix + "applicationId")); return credentials; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NetSuiteCredentials that = (NetSuiteCredentials) o; return numberOfSeats == that.numberOfSeats && useSsoLogin == that.useSsoLogin && Objects.equals(email, that.email) && Objects.equals(account, that.account) && Objects.equals(roleId, that.roleId) && Objects .equals(applicationId, that.applicationId) && Objects.equals(id, that.id) && Objects .equals(companyId, that.companyId) && Objects.equals(userId, that.userId) && Objects .equals(partnerId, that.partnerId) && Objects.equals(privateKey, that.privateKey); } @Override public int hashCode() { return Objects.hash(email, account, roleId, applicationId, numberOfSeats, id, companyId, userId, partnerId, privateKey, useSsoLogin); } @Override public String toString() { final StringBuilder sb = new StringBuilder("NetSuiteCredentials{"); sb.append("email='").append(email).append('\''); sb.append(", password='").append(password).append('\''); sb.append(", account='").append(account).append('\''); sb.append(", roleId='").append(roleId).append('\''); sb.append(", applicationId='").append(applicationId).append('\''); sb.append(", numberOfSeats=").append(numberOfSeats); sb.append(", id='").append(id).append('\''); sb.append(", companyId='").append(companyId).append('\''); sb.append(", userId='").append(userId).append('\''); sb.append(", partnerId='").append(partnerId).append('\''); sb.append(", privateKey='").append(privateKey).append('\''); sb.append(", useSsoLogin=").append(useSsoLogin); sb.append('}'); return sb.toString(); } }
apache-2.0
realityforge/arez
integration-tests/src/test/java/arez/integration/dispose/AllowWriteInDisposeIntegrationTest.java
1993
package arez.integration.dispose; import arez.Arez; import arez.Disposable; import arez.annotations.ArezComponent; import arez.annotations.Observable; import arez.annotations.PreDispose; import arez.integration.AbstractArezIntegrationTest; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nonnull; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; public final class AllowWriteInDisposeIntegrationTest extends AbstractArezIntegrationTest { @Test public void scenario() { final String name = ValueUtil.randomString(); final Model1 model1 = Model1.create( name ); final Model2 model2 = Model2.create( model1 ); final AtomicInteger callCount = new AtomicInteger(); Arez.context().observer( () -> { // Perform observation model1.getName(); callCount.incrementAndGet(); } ); safeAction( () -> assertEquals( model1.getName(), name ) ); assertEquals( callCount.get(), 1 ); Disposable.dispose( model2 ); safeAction( () -> assertEquals( model1.getName(), "X" ) ); assertEquals( callCount.get(), 2 ); } @ArezComponent static abstract class Model1 { @Nonnull static Model1 create( @Nonnull final String name ) { return new AllowWriteInDisposeIntegrationTest_Arez_Model1( name ); } @Observable @Nonnull abstract String getName(); abstract void setName( @Nonnull String name ); } @ArezComponent( allowEmpty = true ) static abstract class Model2 { @SuppressWarnings( "Arez:UnmanagedComponentReference" ) @Nonnull private final Model1 _other; @Nonnull static Model2 create( @Nonnull final Model1 other ) { return new AllowWriteInDisposeIntegrationTest_Arez_Model2( other ); } Model2( @Nonnull final Model1 other ) { _other = other; } @PreDispose void preDispose() { _other.setName( "X" ); } } }
apache-2.0
goodwinnk/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/settings/MergedCompositeConfigurable.java
5530
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xdebugger.impl.settings; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.ui.VerticalFlowLayout; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.TitledSeparator; import com.intellij.xdebugger.settings.DebuggerConfigurableProvider; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; class MergedCompositeConfigurable implements SearchableConfigurable { static final EmptyBorder BOTTOM_INSETS = new EmptyBorder(0, 0, IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET, 0); private static final Insets FIRST_COMPONENT_INSETS = new Insets(0, 0, IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET, 0); private static final Insets N_COMPONENT_INSETS = new Insets(IdeBorderFactory.TITLED_BORDER_TOP_INSET, 0, IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET, 0); protected final Configurable[] children; protected JComponent rootComponent; private final String id; private final String displayName; private final String helpTopic; MergedCompositeConfigurable(@NotNull String id, @NotNull String displayName, @Nullable String helpTopic, @NotNull Configurable[] children) { this.children = children; this.id = id; this.displayName = displayName; this.helpTopic = helpTopic; } @NotNull @Override public String getId() { return id; } @Nls @Override public String getDisplayName() { return displayName; } @Nullable @Override public String getHelpTopic() { if (helpTopic != null) { return helpTopic; } return children.length == 1 ? children[0].getHelpTopic() : null; } /** * false by default. * * If Ruby general settings will be without titled border in RubyMine, user could think that all other debugger categories also about Ruby. */ protected boolean isUseTargetedProductPolicyIfSeveralChildren() { return false; } @Nullable @Override public JComponent createComponent() { if (rootComponent == null) { Configurable firstConfigurable = children[0]; if (children.length == 1) { JComponent component = firstConfigurable.createComponent(); String rootComponentDisplayName = firstConfigurable.getDisplayName(); if (!StringUtil.isEmpty(rootComponentDisplayName) && !isTargetedToProduct(firstConfigurable)) { component.setBorder(IdeBorderFactory.createTitledBorder(rootComponentDisplayName, false, FIRST_COMPONENT_INSETS)); } rootComponent = createPanel(true); rootComponent.add(component); } else { boolean isFirstNamed = true; JPanel panel = createPanel(true); for (Configurable configurable : children) { JComponent component = configurable.createComponent(); assert component != null; String displayName = configurable.getDisplayName(); if (StringUtil.isEmpty(displayName)) { component.setBorder(BOTTOM_INSETS); } else { boolean addBorder = true; if (isUseTargetedProductPolicyIfSeveralChildren() && isFirstNamed) { isFirstNamed = false; if (isTargetedToProduct(configurable)) { addBorder = false; } } if (addBorder) { component.setBorder(IdeBorderFactory.createTitledBorder(displayName, false, firstConfigurable == configurable ? FIRST_COMPONENT_INSETS : N_COMPONENT_INSETS)); } } panel.add(component); } rootComponent = panel; } } return rootComponent; } static boolean isTargetedToProduct(@NotNull Configurable configurable) { for (DebuggerConfigurableProvider provider : DebuggerConfigurableProvider.EXTENSION_POINT.getExtensions()) { if (provider.isTargetedToProduct(configurable)) { return true; } } return false; } @NotNull static JPanel createPanel(boolean isUseTitledBorder) { int verticalGap = TitledSeparator.TOP_INSET; JPanel panel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, isUseTitledBorder ? 0 : verticalGap, true, true)); // VerticalFlowLayout incorrectly use vertical gap as top inset if (!isUseTitledBorder) { panel.setBorder(new EmptyBorder(-verticalGap, 0, 0, 0)); } return panel; } @Override public boolean isModified() { for (Configurable child : children) { if (child.isModified()) { return true; } } return false; } @Override public void apply() throws ConfigurationException { for (Configurable child : children) { if (child.isModified()) { child.apply(); } } } @Override public void reset() { for (Configurable child : children) { child.reset(); } } @Override public void disposeUIResources() { rootComponent = null; for (Configurable child : children) { child.disposeUIResources(); } } }
apache-2.0
atmelino/JATexperimental
src/jat/core/math/arbaxisrot/RotationMatrix.java
6315
/* Copyright 2011 Glenn Murray * * 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 jat.core.math.arbaxisrot; /** * <p>A class to do 3D rotations of a point about a line. </p> * * <p> This uses simplified formulas obtained by normalizing the direction * vector for the line. The matrix obtained is identical to that in {@link * RotationMatrixFull}, but this class may offer better performance. * * @author Glenn Murray */ public class RotationMatrix extends AbstractRotationMatrix { // Static initialization--------------------------------------------- /** For debugging. */ private static final boolean LOG = false; // Instance variables------------------------------------------------ // Constructors------------------------------------------------------ /** * Default constructor. */ public RotationMatrix() {} /** * Build a rotation matrix for rotations about the line through (a, b, c) * parallel to &lt u, v, w &gt by the angle theta. * * @param a x-coordinate of a point on the line of rotation. * @param b y-coordinate of a point on the line of rotation. * @param c z-coordinate of a point on the line of rotation. * @param uUn x-coordinate of the line's direction vector (unnormalized). * @param vUn y-coordinate of the line's direction vector (unnormalized). * @param wUn z-coordinate of the line's direction vector (unnormalized). * @param theta The angle of rotation, in radians. */ public RotationMatrix(double a, double b, double c, double uUn, double vUn, double wUn, double theta) { double l = 0; if ( (l = longEnough(uUn, vUn, wUn)) < 0) { System.out.println("RotationMatrix: direction vector too short!"); return; // Don't bother. } this.a = a; this.b = b; this.c = c; // In this instance we normalize the direction vector. u = uUn/l; v = vUn/l; w = wUn/l; // Set some intermediate values. u2 = u*u; v2 = v*v; w2 = w*w; cosT = Math.cos(theta); oneMinusCosT = 1-cosT; sinT = Math.sin(theta); // Build the matrix entries element by element. m11 = u2 + (v2 + w2) * cosT; m12 = u*v * oneMinusCosT - w*sinT; m13 = u*w * oneMinusCosT + v*sinT; m14 = (a*(v2 + w2) - u*(b*v + c*w))*oneMinusCosT + (b*w - c*v)*sinT; m21 = u*v * oneMinusCosT + w*sinT; m22 = v2 + (u2 + w2) * cosT; m23 = v*w * oneMinusCosT - u*sinT; m24 = (b*(u2 + w2) - v*(a*u + c*w))*oneMinusCosT + (c*u - a*w)*sinT; m31 = u*w * oneMinusCosT - v*sinT; m32 = v*w * oneMinusCosT + u*sinT; m33 = w2 + (u2 + v2) * cosT; m34 = (c*(u2 + v2) - w*(a*u + b*v))*oneMinusCosT + (a*v - b*u)*sinT; if(LOG) logMatrix(); } // Methods----------------------------------------------------------- /** * Compute the rotated point from the formula given in the paper, as opposed * to multiplying this matrix by the given point. Theoretically this should * give the same answer as {@link #timesXYZ(double[])}. For repeated * calculations this will be slower than using {@link * AbstractRotationMatrix#timesXYZ(double[])} because in effect it repeats * the calculations done in the constructor. * * * @param a x-coordinate of a point on the line of rotation. * @param b y-coordinate of a point on the line of rotation. * @param c z-coordinate of a point on the line of rotation. * @param u x-coordinate of the line's direction vector. * @param v y-coordinate of the line's direction vector. * @param w z-coordinate of the line's direction vector. * @param x The point's x-coordinate. * @param y The point's y-coordinate. * @param z The point's z-coordinate. * @param theta The angle of rotation, in radians. * @return The product, in a vector <#, #, #>, representing the * rotated point. */ @Override public double[] rotPointFromFormula(double a, double b, double c, double u, double v, double w, double x, double y, double z, double theta) { // In this instance we normalize the direction vector. double l = 0; if ( (l = longEnough(u, v, w)) < 0) { System.out.println("RotationMatrixFull direction vector too short"); return null; // Don't bother. } // Normalize the direction vector. u = u/l; v = v/l; w = w/l; // Set some intermediate values. double u2 = u*u; double v2 = v*v; double w2 = w*w; double cosT = Math.cos(theta); double oneMinusCosT = 1 - cosT; double sinT = Math.sin(theta); // Use the formula in the paper. double[] p = new double[3]; p[0] = (a*(v2 + w2) - u*(b*v + c*w - u*x - v*y - w*z)) * oneMinusCosT + x*cosT + (-c*v + b*w - w*y + v*z)*sinT; p[1] = (b*(u2 + w2) - v*(a*u + c*w - u*x - v*y - w*z)) * oneMinusCosT + y*cosT + (c*u - a*w + w*x - u*z)*sinT; p[2] = (c*(u2 + v2) - w*(a*u + b*v - u*x - v*y - w*z)) * oneMinusCosT + z*cosT + (-b*u + a*v - v*x + u*y)*sinT; return p; } // Inner classes----------------------------------------------------- }//end class
apache-2.0
hyunsik/incubator-tajo
tajo-core/tajo-core-backend/src/test/java/org/apache/tajo/engine/planner/physical/TestBNLJoinExec.java
8406
/** * 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.tajo.engine.planner.physical; import org.apache.hadoop.fs.Path; import org.apache.tajo.LocalTajoTestingUtility; import org.apache.tajo.TajoTestingCluster; import org.apache.tajo.storage.fragment.FileFragment; import org.apache.tajo.worker.TaskAttemptContext; import org.apache.tajo.algebra.Expr; import org.apache.tajo.catalog.*; import org.apache.tajo.catalog.proto.CatalogProtos.StoreType; import org.apache.tajo.common.TajoDataTypes.Type; import org.apache.tajo.conf.TajoConf; import org.apache.tajo.datum.Datum; import org.apache.tajo.datum.DatumFactory; import org.apache.tajo.engine.parser.SQLAnalyzer; import org.apache.tajo.engine.planner.*; import org.apache.tajo.engine.planner.enforce.Enforcer; import org.apache.tajo.engine.planner.logical.JoinNode; import org.apache.tajo.engine.planner.logical.LogicalNode; import org.apache.tajo.engine.planner.logical.NodeType; import org.apache.tajo.storage.*; import org.apache.tajo.util.CommonTestingUtil; import org.apache.tajo.util.TUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import static org.apache.tajo.ipc.TajoWorkerProtocol.JoinEnforce.JoinAlgorithm; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TestBNLJoinExec { private TajoConf conf; private final String TEST_PATH = "target/test-data/TestBNLJoinExec"; private TajoTestingCluster util; private CatalogService catalog; private SQLAnalyzer analyzer; private LogicalPlanner planner; private AbstractStorageManager sm; private Path testDir; private static int OUTER_TUPLE_NUM = 1000; private static int INNER_TUPLE_NUM = 1000; private TableDesc employee; private TableDesc people; @Before public void setUp() throws Exception { util = new TajoTestingCluster(); catalog = util.startCatalogCluster().getCatalog(); testDir = CommonTestingUtil.getTestDir(TEST_PATH); conf = util.getConfiguration(); sm = StorageManagerFactory.getStorageManager(conf, testDir); Schema schema = new Schema(); schema.addColumn("managerId", Type.INT4); schema.addColumn("empId", Type.INT4); schema.addColumn("memId", Type.INT4); schema.addColumn("deptName", Type.TEXT); TableMeta employeeMeta = CatalogUtil.newTableMeta(StoreType.CSV); Path employeePath = new Path(testDir, "employee.csv"); Appender appender = StorageManagerFactory.getStorageManager(conf).getAppender(employeeMeta, schema, employeePath); appender.init(); Tuple tuple = new VTuple(schema.getColumnNum()); for (int i = 0; i < OUTER_TUPLE_NUM; i++) { tuple.put(new Datum[] { DatumFactory.createInt4(i), DatumFactory.createInt4(i), DatumFactory.createInt4(10 + i), DatumFactory.createText("dept_" + i) }); appender.addTuple(tuple); } appender.flush(); appender.close(); employee = CatalogUtil.newTableDesc("employee", schema, employeeMeta, employeePath); catalog.addTable(employee); Schema peopleSchema = new Schema(); peopleSchema.addColumn("empId", Type.INT4); peopleSchema.addColumn("fk_memId", Type.INT4); peopleSchema.addColumn("name", Type.TEXT); peopleSchema.addColumn("age", Type.INT4); TableMeta peopleMeta = CatalogUtil.newTableMeta(StoreType.CSV); Path peoplePath = new Path(testDir, "people.csv"); appender = StorageManagerFactory.getStorageManager(conf).getAppender(peopleMeta, peopleSchema, peoplePath); appender.init(); tuple = new VTuple(peopleSchema.getColumnNum()); for (int i = 1; i < INNER_TUPLE_NUM; i += 2) { tuple.put(new Datum[] { DatumFactory.createInt4(i), DatumFactory.createInt4(10 + i), DatumFactory.createText("name_" + i), DatumFactory.createInt4(30 + i) }); appender.addTuple(tuple); } appender.flush(); appender.close(); people = CatalogUtil.newTableDesc("people", peopleSchema, peopleMeta, peoplePath); catalog.addTable(people); analyzer = new SQLAnalyzer(); planner = new LogicalPlanner(catalog); } @After public void tearDown() throws Exception { util.shutdownCatalogCluster(); } // employee (managerId, empId, memId, deptName) // people (empId, fk_memId, name, age) String[] QUERIES = { "select managerId, e.empId, deptName, e.memId from employee as e, people p", "select managerId, e.empId, deptName, e.memId from employee as e " + "inner join people as p on e.empId = p.empId and e.memId = p.fk_memId" }; @Test public final void testBNLCrossJoin() throws IOException, PlanningException { Expr expr = analyzer.parse(QUERIES[0]); LogicalNode plan = planner.createPlan(expr).getRootBlock().getRoot(); JoinNode joinNode = PlannerUtil.findTopNode(plan, NodeType.JOIN); Enforcer enforcer = new Enforcer(); enforcer.enforceJoinAlgorithm(joinNode.getPID(), JoinAlgorithm.BLOCK_NESTED_LOOP_JOIN); FileFragment[] empFrags = StorageManager.splitNG(conf, "e", employee.getMeta(), employee.getPath(), Integer.MAX_VALUE); FileFragment[] peopleFrags = StorageManager.splitNG(conf, "p", people.getMeta(), people.getPath(), Integer.MAX_VALUE); FileFragment[] merged = TUtil.concat(empFrags, peopleFrags); Path workDir = CommonTestingUtil.getTestDir("target/test-data/testBNLCrossJoin"); TaskAttemptContext ctx = new TaskAttemptContext(conf, LocalTajoTestingUtility.newQueryUnitAttemptId(), merged, workDir); ctx.setEnforcer(enforcer); PhysicalPlanner phyPlanner = new PhysicalPlannerImpl(conf,sm); PhysicalExec exec = phyPlanner.createPlan(ctx, plan); ProjectionExec proj = (ProjectionExec) exec; assertTrue(proj.getChild() instanceof BNLJoinExec); int i = 0; exec.init(); while (exec.next() != null) { i++; } exec.close(); assertEquals(OUTER_TUPLE_NUM * INNER_TUPLE_NUM / 2, i); // expected 10 * 5 } @Test public final void testBNLInnerJoin() throws IOException, PlanningException { Expr context = analyzer.parse(QUERIES[1]); LogicalNode plan = planner.createPlan(context).getRootBlock().getRoot(); FileFragment[] empFrags = StorageManager.splitNG(conf, "e", employee.getMeta(), employee.getPath(), Integer.MAX_VALUE); FileFragment[] peopleFrags = StorageManager.splitNG(conf, "p", people.getMeta(), people.getPath(), Integer.MAX_VALUE); FileFragment[] merged = TUtil.concat(empFrags, peopleFrags); JoinNode joinNode = PlannerUtil.findTopNode(plan, NodeType.JOIN); Enforcer enforcer = new Enforcer(); enforcer.enforceJoinAlgorithm(joinNode.getPID(), JoinAlgorithm.BLOCK_NESTED_LOOP_JOIN); Path workDir = CommonTestingUtil.getTestDir("target/test-data/testBNLInnerJoin"); TaskAttemptContext ctx = new TaskAttemptContext(conf, LocalTajoTestingUtility.newQueryUnitAttemptId(), merged, workDir); ctx.setEnforcer(enforcer); PhysicalPlanner phyPlanner = new PhysicalPlannerImpl(conf,sm); PhysicalExec exec = phyPlanner.createPlan(ctx, plan); ProjectionExec proj = (ProjectionExec) exec; assertTrue(proj.getChild() instanceof BNLJoinExec); Tuple tuple; int i = 1; int count = 0; exec.init(); while ((tuple = exec.next()) != null) { count++; assertTrue(i == tuple.get(0).asInt4()); assertTrue(i == tuple.get(1).asInt4()); assertTrue(("dept_" + i).equals(tuple.get(2).asChars())); assertTrue(10 + i == tuple.get(3).asInt4()); i += 2; } exec.close(); assertEquals(INNER_TUPLE_NUM / 2, count); } }
apache-2.0
gawkermedia/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201511/MimeType.java
11062
/** * MimeType.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201511; public class MimeType implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected MimeType(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final java.lang.String _ASP = "ASP"; public static final java.lang.String _AUDIO_AIFF = "AUDIO_AIFF"; public static final java.lang.String _AUDIO_BASIC = "AUDIO_BASIC"; public static final java.lang.String _AUDIO_FLAC = "AUDIO_FLAC"; public static final java.lang.String _AUDIO_MID = "AUDIO_MID"; public static final java.lang.String _AUDIO_MP3 = "AUDIO_MP3"; public static final java.lang.String _AUDIO_MP4 = "AUDIO_MP4"; public static final java.lang.String _AUDIO_MPEG_URL = "AUDIO_MPEG_URL"; public static final java.lang.String _AUDIO_MS_WMA = "AUDIO_MS_WMA"; public static final java.lang.String _AUDIO_OGG = "AUDIO_OGG"; public static final java.lang.String _AUDIO_REAL_AUDIO_PLUGIN = "AUDIO_REAL_AUDIO_PLUGIN"; public static final java.lang.String _AUDIO_WAV = "AUDIO_WAV"; public static final java.lang.String _BINARY = "BINARY"; public static final java.lang.String _DIRECTOR = "DIRECTOR"; public static final java.lang.String _FLASH = "FLASH"; public static final java.lang.String _GRAPHIC_CONVERTER = "GRAPHIC_CONVERTER"; public static final java.lang.String _JAVASCRIPT = "JAVASCRIPT"; public static final java.lang.String _JSON = "JSON"; public static final java.lang.String _IMAGE_BITMAP = "IMAGE_BITMAP"; public static final java.lang.String _IMAGE_BMP = "IMAGE_BMP"; public static final java.lang.String _IMAGE_GIF = "IMAGE_GIF"; public static final java.lang.String _IMAGE_JPEG = "IMAGE_JPEG"; public static final java.lang.String _IMAGE_PHOTOSHOP = "IMAGE_PHOTOSHOP"; public static final java.lang.String _IMAGE_PNG = "IMAGE_PNG"; public static final java.lang.String _IMAGE_TIFF = "IMAGE_TIFF"; public static final java.lang.String _IMAGE_WBMP = "IMAGE_WBMP"; public static final java.lang.String _M3U8 = "M3U8"; public static final java.lang.String _MAC_BIN_HEX_40 = "MAC_BIN_HEX_40"; public static final java.lang.String _MS_EXCEL = "MS_EXCEL"; public static final java.lang.String _MS_POWERPOINT = "MS_POWERPOINT"; public static final java.lang.String _MS_WORD = "MS_WORD"; public static final java.lang.String _OCTET_STREAM = "OCTET_STREAM"; public static final java.lang.String _PDF = "PDF"; public static final java.lang.String _POSTSCRIPT = "POSTSCRIPT"; public static final java.lang.String _RN_REAL_MEDIA = "RN_REAL_MEDIA"; public static final java.lang.String _RFC_822 = "RFC_822"; public static final java.lang.String _RTF = "RTF"; public static final java.lang.String _TEXT_CALENDAR = "TEXT_CALENDAR"; public static final java.lang.String _TEXT_CSS = "TEXT_CSS"; public static final java.lang.String _TEXT_CSV = "TEXT_CSV"; public static final java.lang.String _TEXT_HTML = "TEXT_HTML"; public static final java.lang.String _TEXT_JAVA = "TEXT_JAVA"; public static final java.lang.String _TEXT_PLAIN = "TEXT_PLAIN"; public static final java.lang.String _VIDEO_3GPP = "VIDEO_3GPP"; public static final java.lang.String _VIDEO_3GPP2 = "VIDEO_3GPP2"; public static final java.lang.String _VIDEO_AVI = "VIDEO_AVI"; public static final java.lang.String _VIDEO_FLV = "VIDEO_FLV"; public static final java.lang.String _VIDEO_MP4 = "VIDEO_MP4"; public static final java.lang.String _VIDEO_MP4V_ES = "VIDEO_MP4V_ES"; public static final java.lang.String _VIDEO_MPEG = "VIDEO_MPEG"; public static final java.lang.String _VIDEO_MS_ASF = "VIDEO_MS_ASF"; public static final java.lang.String _VIDEO_MS_WM = "VIDEO_MS_WM"; public static final java.lang.String _VIDEO_MS_WMV = "VIDEO_MS_WMV"; public static final java.lang.String _VIDEO_MS_WVX = "VIDEO_MS_WVX"; public static final java.lang.String _VIDEO_OGG = "VIDEO_OGG"; public static final java.lang.String _VIDEO_QUICKTIME = "VIDEO_QUICKTIME"; public static final java.lang.String _VIDEO_WEBM = "VIDEO_WEBM"; public static final java.lang.String _XAML = "XAML"; public static final java.lang.String _XHTML = "XHTML"; public static final java.lang.String _XML = "XML"; public static final java.lang.String _ZIP = "ZIP"; public static final MimeType UNKNOWN = new MimeType(_UNKNOWN); public static final MimeType ASP = new MimeType(_ASP); public static final MimeType AUDIO_AIFF = new MimeType(_AUDIO_AIFF); public static final MimeType AUDIO_BASIC = new MimeType(_AUDIO_BASIC); public static final MimeType AUDIO_FLAC = new MimeType(_AUDIO_FLAC); public static final MimeType AUDIO_MID = new MimeType(_AUDIO_MID); public static final MimeType AUDIO_MP3 = new MimeType(_AUDIO_MP3); public static final MimeType AUDIO_MP4 = new MimeType(_AUDIO_MP4); public static final MimeType AUDIO_MPEG_URL = new MimeType(_AUDIO_MPEG_URL); public static final MimeType AUDIO_MS_WMA = new MimeType(_AUDIO_MS_WMA); public static final MimeType AUDIO_OGG = new MimeType(_AUDIO_OGG); public static final MimeType AUDIO_REAL_AUDIO_PLUGIN = new MimeType(_AUDIO_REAL_AUDIO_PLUGIN); public static final MimeType AUDIO_WAV = new MimeType(_AUDIO_WAV); public static final MimeType BINARY = new MimeType(_BINARY); public static final MimeType DIRECTOR = new MimeType(_DIRECTOR); public static final MimeType FLASH = new MimeType(_FLASH); public static final MimeType GRAPHIC_CONVERTER = new MimeType(_GRAPHIC_CONVERTER); public static final MimeType JAVASCRIPT = new MimeType(_JAVASCRIPT); public static final MimeType JSON = new MimeType(_JSON); public static final MimeType IMAGE_BITMAP = new MimeType(_IMAGE_BITMAP); public static final MimeType IMAGE_BMP = new MimeType(_IMAGE_BMP); public static final MimeType IMAGE_GIF = new MimeType(_IMAGE_GIF); public static final MimeType IMAGE_JPEG = new MimeType(_IMAGE_JPEG); public static final MimeType IMAGE_PHOTOSHOP = new MimeType(_IMAGE_PHOTOSHOP); public static final MimeType IMAGE_PNG = new MimeType(_IMAGE_PNG); public static final MimeType IMAGE_TIFF = new MimeType(_IMAGE_TIFF); public static final MimeType IMAGE_WBMP = new MimeType(_IMAGE_WBMP); public static final MimeType M3U8 = new MimeType(_M3U8); public static final MimeType MAC_BIN_HEX_40 = new MimeType(_MAC_BIN_HEX_40); public static final MimeType MS_EXCEL = new MimeType(_MS_EXCEL); public static final MimeType MS_POWERPOINT = new MimeType(_MS_POWERPOINT); public static final MimeType MS_WORD = new MimeType(_MS_WORD); public static final MimeType OCTET_STREAM = new MimeType(_OCTET_STREAM); public static final MimeType PDF = new MimeType(_PDF); public static final MimeType POSTSCRIPT = new MimeType(_POSTSCRIPT); public static final MimeType RN_REAL_MEDIA = new MimeType(_RN_REAL_MEDIA); public static final MimeType RFC_822 = new MimeType(_RFC_822); public static final MimeType RTF = new MimeType(_RTF); public static final MimeType TEXT_CALENDAR = new MimeType(_TEXT_CALENDAR); public static final MimeType TEXT_CSS = new MimeType(_TEXT_CSS); public static final MimeType TEXT_CSV = new MimeType(_TEXT_CSV); public static final MimeType TEXT_HTML = new MimeType(_TEXT_HTML); public static final MimeType TEXT_JAVA = new MimeType(_TEXT_JAVA); public static final MimeType TEXT_PLAIN = new MimeType(_TEXT_PLAIN); public static final MimeType VIDEO_3GPP = new MimeType(_VIDEO_3GPP); public static final MimeType VIDEO_3GPP2 = new MimeType(_VIDEO_3GPP2); public static final MimeType VIDEO_AVI = new MimeType(_VIDEO_AVI); public static final MimeType VIDEO_FLV = new MimeType(_VIDEO_FLV); public static final MimeType VIDEO_MP4 = new MimeType(_VIDEO_MP4); public static final MimeType VIDEO_MP4V_ES = new MimeType(_VIDEO_MP4V_ES); public static final MimeType VIDEO_MPEG = new MimeType(_VIDEO_MPEG); public static final MimeType VIDEO_MS_ASF = new MimeType(_VIDEO_MS_ASF); public static final MimeType VIDEO_MS_WM = new MimeType(_VIDEO_MS_WM); public static final MimeType VIDEO_MS_WMV = new MimeType(_VIDEO_MS_WMV); public static final MimeType VIDEO_MS_WVX = new MimeType(_VIDEO_MS_WVX); public static final MimeType VIDEO_OGG = new MimeType(_VIDEO_OGG); public static final MimeType VIDEO_QUICKTIME = new MimeType(_VIDEO_QUICKTIME); public static final MimeType VIDEO_WEBM = new MimeType(_VIDEO_WEBM); public static final MimeType XAML = new MimeType(_XAML); public static final MimeType XHTML = new MimeType(_XHTML); public static final MimeType XML = new MimeType(_XML); public static final MimeType ZIP = new MimeType(_ZIP); public java.lang.String getValue() { return _value_;} public static MimeType fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { MimeType enumeration = (MimeType) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static MimeType fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(MimeType.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "MimeType")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
apache-2.0
BrunoEberhard/minimal-j
example/004_Library/src/main/java/org/minimalj/example/library/model/ExampleFormats.java
117
package org.minimalj.example.library.model; public class ExampleFormats { public static final int NAME = 30; }
apache-2.0
OSGP/Platform
osgp-adapter-domain-smartmetering/src/test/java/org/opensmartgridplatform/adapter/domain/smartmetering/application/services/PushSetupSmsMappingTest.java
11593
/** * Copyright 2014-2016 Smart Society Services B.V. * * 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 */ package org.opensmartgridplatform.adapter.domain.smartmetering.application.services; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.ArrayList; import org.junit.Test; import org.opensmartgridplatform.adapter.domain.smartmetering.application.mapping.ConfigurationMapper; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.ClockStatus; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.CosemDate; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.CosemDateTime; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.CosemObisCode; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.CosemObjectDefinition; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.CosemTime; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.PushSetupSms; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.SendDestinationAndMethod; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.WindowElement; import org.opensmartgridplatform.dto.valueobjects.smartmetering.ClockStatusDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.CosemDateDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.CosemDateTimeDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.CosemObisCodeDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.CosemObjectDefinitionDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.CosemTimeDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.PushSetupSmsDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.SendDestinationAndMethodDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.WindowElementDto; public class PushSetupSmsMappingTest { private ConfigurationMapper configurationMapper = new ConfigurationMapper(); // To test if a PushSetupAlarm can be mapped if instance variables are // null. @Test public void testPushSetupSmsMappingNull() { // build test data final PushSetupSms pushSetupSms = new PushSetupSmsBuilder().withNullValues().build(); // actual mapping final PushSetupSmsDto pushSetupSmsDto = this.configurationMapper.map(pushSetupSms, PushSetupSmsDto.class); // check values assertNotNull(pushSetupSmsDto); assertNull(pushSetupSmsDto.getLogicalName()); assertNull(pushSetupSmsDto.getPushObjectList()); assertNull(pushSetupSmsDto.getSendDestinationAndMethod()); assertNull(pushSetupSmsDto.getCommunicationWindow()); assertNull(pushSetupSmsDto.getRandomisationStartInterval()); assertNull(pushSetupSmsDto.getNumberOfRetries()); assertNull(pushSetupSmsDto.getRepetitionDelay()); } // To test if a PushSetupAlarm can be mapped if instance variables are // initialized and lists are empty. @Test public void testPushSetupSmsMappingWithEmptyLists() { // build test data final ArrayList<CosemObjectDefinition> pushObjectList = new ArrayList<>(); final ArrayList<WindowElement> communicationWindow = new ArrayList<>(); final PushSetupSms pushSetupSms = new PushSetupSmsBuilder().withEmptyLists(pushObjectList, communicationWindow) .build(); // actual mapping final PushSetupSmsDto pushSetupSmsDto = this.configurationMapper.map(pushSetupSms, PushSetupSmsDto.class); // check values this.checkCosemObisCodeMapping(pushSetupSms.getLogicalName(), pushSetupSmsDto.getLogicalName()); this.checkSendDestinationAndMethodMapping(pushSetupSms, pushSetupSmsDto); this.checkIntegerMapping(pushSetupSms, pushSetupSmsDto); assertNotNull(pushSetupSmsDto.getPushObjectList()); assertNotNull(pushSetupSmsDto.getCommunicationWindow()); } // To test Mapping if lists contain values @Test public void testPushSetupSmsMappingWithLists() { // build test data final CosemObisCode logicalName = new CosemObisCode(new int[] { 1, 2, 3, 4, 5, 6 }); final CosemObjectDefinition cosemObjectDefinition = new CosemObjectDefinition(1, logicalName, 2); final CosemDateTime startTime = new CosemDateTime(new CosemDate(2016, 3, 17), new CosemTime(11, 52, 45), 0, new ClockStatus(ClockStatus.STATUS_NOT_SPECIFIED)); final CosemDateTime endTime = new CosemDateTime(new CosemDate(2016, 3, 17), new CosemTime(11, 52, 45), 0, new ClockStatus(ClockStatus.STATUS_NOT_SPECIFIED)); final WindowElement windowElement = new WindowElement(startTime, endTime); final PushSetupSms pushSetupSms = new PushSetupSmsBuilder() .withFilledLists(cosemObjectDefinition, windowElement).build(); // actual mapping final PushSetupSmsDto pushSetupSmsDto = this.configurationMapper.map(pushSetupSms, PushSetupSmsDto.class); // check values this.checkCosemObisCodeMapping(pushSetupSms.getLogicalName(), pushSetupSmsDto.getLogicalName()); this.checkSendDestinationAndMethodMapping(pushSetupSms, pushSetupSmsDto); this.checkIntegerMapping(pushSetupSms, pushSetupSmsDto); this.checkNonEmptyListMapping(pushSetupSms, pushSetupSmsDto); } // method to test Integer object mapping private void checkIntegerMapping(final PushSetupSms pushSetupSms, final PushSetupSmsDto pushSetupSmsDto) { // make sure none is null assertNotNull(pushSetupSmsDto.getRandomisationStartInterval()); assertNotNull(pushSetupSmsDto.getNumberOfRetries()); assertNotNull(pushSetupSmsDto.getRepetitionDelay()); // make sure all values are equal assertEquals(pushSetupSms.getRandomisationStartInterval(), pushSetupSmsDto.getRandomisationStartInterval()); assertEquals(pushSetupSms.getNumberOfRetries(), pushSetupSmsDto.getNumberOfRetries()); assertEquals(pushSetupSms.getRepetitionDelay(), pushSetupSmsDto.getRepetitionDelay()); } // method to test CosemObisCode object mapping private void checkCosemObisCodeMapping(final CosemObisCode cosemObisCode, final CosemObisCodeDto cosemObisCodeDto) { // make sure neither is null assertNotNull(cosemObisCode); assertNotNull(cosemObisCodeDto); // make sure all instance variables are equal assertEquals(cosemObisCode.getA(), cosemObisCodeDto.getA()); assertEquals(cosemObisCode.getB(), cosemObisCodeDto.getB()); assertEquals(cosemObisCode.getC(), cosemObisCodeDto.getC()); assertEquals(cosemObisCode.getD(), cosemObisCodeDto.getD()); assertEquals(cosemObisCode.getE(), cosemObisCodeDto.getE()); assertEquals(cosemObisCode.getF(), cosemObisCodeDto.getF()); } // method to test SendDestinationAndMethod mapping private void checkSendDestinationAndMethodMapping(final PushSetupSms pushSetupSms, final PushSetupSmsDto pushSetupSmsDto) { final SendDestinationAndMethod sendDestinationAndMethod = pushSetupSms.getSendDestinationAndMethod(); final SendDestinationAndMethodDto sendDestinationAndMethodDto = pushSetupSmsDto.getSendDestinationAndMethod(); // make sure neither is null assertNotNull(sendDestinationAndMethod); assertNotNull(sendDestinationAndMethodDto); // make sure all instance variables are equal assertEquals(sendDestinationAndMethod.getTransportService().name(), sendDestinationAndMethodDto.getTransportService().name()); assertEquals(sendDestinationAndMethod.getMessage().name(), sendDestinationAndMethodDto.getMessage().name()); assertEquals(sendDestinationAndMethod.getDestination(), sendDestinationAndMethodDto.getDestination()); } // method to test non-empty list mapping private void checkNonEmptyListMapping(final PushSetupSms pushSetupSms, final PushSetupSmsDto pushSetupSmsDto) { // test pushObjectList mapping assertNotNull(pushSetupSms.getPushObjectList()); assertNotNull(pushSetupSmsDto.getPushObjectList()); assertEquals(pushSetupSms.getPushObjectList().size(), pushSetupSmsDto.getPushObjectList().size()); final CosemObjectDefinition cosemObjectDefinition = pushSetupSms.getPushObjectList().get(0); final CosemObjectDefinitionDto cosemObjectDefinitionDto = pushSetupSmsDto.getPushObjectList().get(0); assertEquals(cosemObjectDefinition.getAttributeIndex(), cosemObjectDefinitionDto.getAttributeIndex()); assertEquals(cosemObjectDefinition.getClassId(), cosemObjectDefinitionDto.getClassId()); assertEquals(cosemObjectDefinition.getDataIndex(), cosemObjectDefinitionDto.getDataIndex()); this.checkCosemObisCodeMapping(cosemObjectDefinition.getLogicalName(), cosemObjectDefinitionDto.getLogicalName()); // test communicationWindow mapping assertNotNull(pushSetupSms.getCommunicationWindow()); assertNotNull(pushSetupSmsDto.getCommunicationWindow()); assertEquals(pushSetupSms.getCommunicationWindow().size(), pushSetupSmsDto.getCommunicationWindow().size()); final WindowElement windowElement = pushSetupSms.getCommunicationWindow().get(0); final WindowElementDto windowElementDto = pushSetupSmsDto.getCommunicationWindow().get(0); this.checkCosemDateTimeMapping(windowElement.getStartTime(), windowElementDto.getStartTime()); this.checkCosemDateTimeMapping(windowElement.getEndTime(), windowElementDto.getEndTime()); } // method to test mapping of CosemDateTime objects private void checkCosemDateTimeMapping(final CosemDateTime cosemDateTime, final CosemDateTimeDto cosemDateTimeDto) { // make sure neither is null assertNotNull(cosemDateTime); assertNotNull(cosemDateTimeDto); // check variables assertEquals(cosemDateTime.getDeviation(), cosemDateTimeDto.getDeviation()); final ClockStatus clockStatus = cosemDateTime.getClockStatus(); final ClockStatusDto clockStatusDto = cosemDateTimeDto.getClockStatus(); assertEquals(clockStatus.getStatus(), clockStatusDto.getStatus()); assertEquals(clockStatus.isSpecified(), clockStatusDto.isSpecified()); final CosemDate cosemDate = cosemDateTime.getDate(); final CosemDateDto cosemDateDto = cosemDateTimeDto.getDate(); assertEquals(cosemDate.getYear(), cosemDateDto.getYear()); assertEquals(cosemDate.getMonth(), cosemDateDto.getMonth()); assertEquals(cosemDate.getDayOfMonth(), cosemDateDto.getDayOfMonth()); assertEquals(cosemDate.getDayOfWeek(), cosemDateDto.getDayOfWeek()); final CosemTime cosemTime = cosemDateTime.getTime(); final CosemTimeDto cosemTimeDto = cosemDateTimeDto.getTime(); assertEquals(cosemTime.getHour(), cosemTimeDto.getHour()); assertEquals(cosemTime.getMinute(), cosemTimeDto.getMinute()); assertEquals(cosemTime.getSecond(), cosemTimeDto.getSecond()); assertEquals(cosemTime.getHundredths(), cosemTimeDto.getHundredths()); } }
apache-2.0
nodekit-io/nodekit-android
nkelectro/src/main/java/io/nodekit/nkelectro/NKE_App.java
7398
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. 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.nodekit.nkelectro; import android.content.pm.PackageInfo; import android.os.Environment; import android.webkit.JavascriptInterface; import io.nodekit.nkscripting.NKApplication; import io.nodekit.nkscripting.NKScriptExport; import io.nodekit.nkscripting.util.NKEventEmitter; import io.nodekit.nkscripting.util.NKEventHandler; import io.nodekit.nkscripting.NKScriptContext; import io.nodekit.nkscripting.NKScriptValue; import java.util.HashMap; import java.util.Map; import io.nodekit.nkscripting.util.NKLogging; final class NKE_App implements NKScriptExport { static void attachTo(NKScriptContext context, Map<String, Object> appOptions) throws Exception { HashMap<String,Object> options = new HashMap<String, Object>(); options.put("js","lib_electro/app.js"); NKE_App app = new NKE_App(); NKScriptValue jsv = context.loadPlugin(app, "io.nodekit.electro.app", options); app.initWithJSValue(jsv); } private static int windowCount; private NKScriptValue jsValue; private static NKEventEmitter events = NKEventEmitter.global; private void initWithJSValue(NKScriptValue jsv) throws Exception { this.jsValue = jsv; windowCount = 0; events.on("NK.AppReady", new NKEventHandler<String>() { protected void call(String event, String test) { jsValue.invokeMethod("emit", new String[] { "ready" }); } }); events.once("NK.AppDidFinishLaunching", new NKEventHandler<String>() { protected void call(String event, String test) { jsValue.invokeMethod("emit", new String[] { "will-finish-launching" }); } }); events.once("NK.AppWillTerminate", new NKEventHandler<String>() { protected void call(String event, String test) { jsValue.invokeMethod("emit", new String[] { "will-quit" }); jsValue.invokeMethod("emit", new String[] { "quit" }); } }); events.once("NK.ProcessAdded", new NKEventHandler<String>() { protected void call(String event, String test) { windowCount++; } }); events.once("NK.WindowAdded", new NKEventHandler<String>() { protected void call(String event, String test) { windowCount++; } }); events.once("NK.ProcessRemoved", new NKEventHandler<String>() { protected void call(String event, String test) { windowCount--; if (windowCount == 0) events.emit("NKE.WindowAllClosed", ""); } }); events.once("NK.WindowRemoved", new NKEventHandler<String>() { protected void call(String event, String test) { windowCount--; if (windowCount == 0) events.emit("NKE.WindowAllClosed", ""); } }); events.once("NK.WindowAllClosed", new NKEventHandler<String>() { protected void call(String event, String test) { jsValue.invokeMethod("emit", new String[] { "window-all-closed" }); } }); } @JavascriptInterface public void quit() throws Exception { } @JavascriptInterface public void exit(int exitCode) throws Exception { } @JavascriptInterface public String getAppPath() throws Exception { return getSpecialPath("exe"); } @JavascriptInterface public String getPath(String name) throws Exception { return getSpecialPath(name); } @JavascriptInterface public String getVersion() throws Exception { PackageInfo pInfo = NKApplication.getAppContext().getPackageManager().getPackageInfo( NKApplication.getAppContext().getPackageName(), 0); return pInfo.versionName; } @JavascriptInterface public String getName() throws Exception { return NKApplication.getAppContext().getPackageName(); } // NOT IMPLEMENTED public void addRecentDocument(String path) { } public void allowNTLMCredentialsForAllDomains(boolean allow) { } public void appendArgument(String value) { } public void appendSwitch(String switchvalue, String value) { } public void clearRecentDocuments(String path) { } public int dockBounce(String type) { return 0; } public void dockCancelBounce(int id) { } public String dockGetBadge() { return null; } public void dockHide() { } public void dockSetBadge(String text) { } public void dockSetMenu(Object menu) { } public void dockShow() { } public String getLocale() { return null; } public void makeSingleInstance() { } public void setAppUserModelId(String id) { } public String setPath(String name, String path) { return null; } public void setUserTasks(HashMap<String, Object> tasks) { } private String getSpecialPath(String name) { switch(name) { case "home": return NKApplication.getAppContext().getFilesDir().getAbsolutePath(); case "appData": return NKApplication.getAppContext().getFilesDir().getAbsolutePath(); case "userData": return NKApplication.getAppContext().getFilesDir().getAbsolutePath(); case "temp": return NKApplication.getAppContext().getCacheDir().getAbsolutePath(); case "exe": return NKApplication.getAppContext().getApplicationInfo().dataDir; case "module": return ""; case "desktop": return ""; case "documents": return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath(); case "downloads": return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); case "music": return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath(); case "pictures": return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath(); case "videos": return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath(); default: return ""; } } } // Event: 'before-quit' // Event: 'will-quit' // Event: 'quit' // Event: 'open-file' OS X // Event: 'open-url' OS X // Event: 'activate' OS X // Event: 'browser-window-blur' // Event: 'browser-window-focus' // Event: 'browser-window-created' // Event: 'certificate-error' // Event: 'select-client-certificate' // Event: 'login' // Event: 'gpu-process-crashed'
apache-2.0
ow2-xlcloud/vca
ext/hpc/impl/src/main/java/org/xlcloud/xsa/ext/hpc/service/parser/ParserUtils.java
3723
/* * Copyright 2012 AMG.lab, a Bull Group Company * * 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.xlcloud.xsa.ext.hpc.service.parser; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.xlcloud.rest.exception.BaseException; import org.xlcloud.rest.exception.InternalErrorException; import org.xlcloud.xsa.ext.hpc.service.process.ProcessExecutionResult; /** * Utility class for process output parsers. * * @author Krzysztof Szafrański, AMG.net */ public class ParserUtils { private static final Logger LOG = Logger.getLogger(ParserUtils.class); public static final Integer SUCCESS_EXIT_CODE = 0; /** * Returns the first capturing group of the first match for the given * pattern in the specified text. * * @param text * @param pattern * @return */ public static String getValue(String text, Pattern pattern) { Matcher matcher = pattern.matcher(text); if (matcher.find()) { return matcher.group(1); } else { throw new InternalErrorException("Unexpected process result", text); } } /** * Returns a list of first capturing groups of all the matches for the given * pattern in the specified text. * * @param text * @param pattern * @return */ public static List<String> getValues(String text, Pattern pattern) { List<String> values = new ArrayList<>(); Matcher matcher = pattern.matcher(text); while (matcher.find()) { values.add(matcher.group(1)); } return values; } /** * Validates that the result, exit code and output are not null. * * @param result * @throws InternalErrorException */ public static void validateResult(ProcessExecutionResult result) throws InternalErrorException { if (result == null) { String message = "Process execution result cannot be null"; LOG.error(message); throw new InternalErrorException(message); } if (result.getExitCode() == null || result.getOutput() == null) { String message = "Process execution output nor its exit code cannot be null"; String details = "Exit code: " + result.getExitCode() + ", output: " + result.getOutput(); LOG.error(message + ", details: " + details); throw new InternalErrorException(message, details); } } /** * Validates that exit code is 0. * * @param result * @throws InternalErrorException */ public static void validateExitCodeSuccessful(ProcessExecutionResult result) throws InternalErrorException { if (!SUCCESS_EXIT_CODE.equals(result.getExitCode())) { String message = "Process execution finished with errors"; String details = "Exit code: " + result.getExitCode() + ", output: " + result.getOutput(); LOG.error(message + ", details" + details); throw new InternalErrorException(message, details); } } }
apache-2.0
ov3rflow/eFaps-Kernel
src/main/java/org/efaps/bpm/compiler/KnowledgeBuilderFactoryServiceImpl.java
2674
/* * Copyright 2003 - 2013 The eFaps 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.bpm.compiler; import java.util.Properties; import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl; import org.drools.compiler.rule.builder.dialect.java.JavaDialectConfiguration; import org.efaps.admin.EFapsSystemConfiguration; import org.efaps.admin.KernelSettings; import org.efaps.admin.program.esjp.EFapsClassLoader; import org.efaps.util.EFapsException; import org.kie.internal.builder.conf.ClassLoaderCacheOption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO comment! * * @author The eFaps Team * @version $Id: KnowledgeBuilderFactoryServiceImpl.java 11598 2014-01-07 * 00:02:12Z jan@moxter.net $ */ public class KnowledgeBuilderFactoryServiceImpl extends org.drools.compiler.builder.impl.KnowledgeBuilderFactoryServiceImpl { /** * Logging instance used in this class. */ private static final Logger LOG = LoggerFactory.getLogger(KnowledgeBuilderFactoryServiceImpl.class); @Override public KnowledgeBuilder newKnowledgeBuilder() { String level = null; try { level = EFapsSystemConfiguration.get().getAttributeValue(KernelSettings.BPM_COMPILERLEVEL); } catch (final EFapsException e) { KnowledgeBuilderFactoryServiceImpl.LOG.error("Catched error on retireving SystemConfiguration", e); } // set compiler to eclipse final Properties knowledgeBldrProps = new Properties(); knowledgeBldrProps.setProperty(JavaDialectConfiguration.JAVA_COMPILER_PROPERTY, "ECLIPSE"); knowledgeBldrProps.setProperty("drools.dialect.java.compiler.lnglevel", level == null ? "1.7" : level); knowledgeBldrProps.setProperty(ClassLoaderCacheOption.PROPERTY_NAME, "false"); final KnowledgeBuilderConfigurationImpl conf = new KnowledgeBuilderConfigurationImpl(knowledgeBldrProps, EFapsClassLoader.getInstance()); return new KnowledgeBuilder(conf); } }
apache-2.0
dash-/apache-openaz
openaz-xacml/src/main/java/org/apache/openaz/xacml/api/Decision.java
4023
/* * 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.openaz.xacml.api; /** * Enumeration of the XACML 3.0 decisions and extended decisions that can be returned as part of a * {@link Result}. */ public enum Decision { /** * Indicates the request is permitted */ PERMIT("Permit"), /** * Indicates the request is denied */ DENY("Deny"), /** * Indicates no decision could be reached due to a processing error */ INDETERMINATE("Indeterminate"), /** * Indicates no decision could be reached due to a processing error, but it would have been permitted had * the error not occurred */ INDETERMINATE_PERMIT("Indeterminate{P}", true, INDETERMINATE), /** * Indicates no decision could be reached due to a processing error, but it would have been denied had the * error not occurred. */ INDETERMINATE_DENY("Indeterminate{D}", true, INDETERMINATE), /** * Indicates no decision could be reached due to a processing error, but either a deny or permit would * have been returned had the error not occurred. */ INDETERMINATE_DENYPERMIT("Indeterminate{DP}", true, INDETERMINATE), /** * Indicates the policy in question is not applicable to the request */ NOTAPPLICABLE("NotApplicable"); private String name; private boolean extended; private Decision basicDecision; private Decision(String nameIn, Boolean extendedIn, Decision basicDecisionIn) { this.name = nameIn; this.extended = extendedIn; this.basicDecision = basicDecisionIn; } private Decision(String nameIn) { this(nameIn, false, null); } /** * Returns true if this <code>Decision</code> represents a XACML 3.0 extended Decision. * * @return true if this <code>Decision</code> is a XACML 3.0 extended Decision. */ public boolean isExtended() { return this.extended; } /** * Returns the <code>Decision</code> representing the XACML 3.0 basic Decision for this * <code>Decision</code>. * * @return the <code>Decision</code> representing the XACML 3.0 basic Decision for this * <code>Decision</code>. */ public Decision getBasicDecision() { return this.isExtended() ? this.basicDecision : this; } /** * Gets the <code>Decision</code> whose <code>String</code> representation matches the given * <code>String</code>. * * @param decisionName the <code>String</code> decision name * @return the <code>Decision</code> with the name matching the given <code>String</code> or null if no * match is found */ public static Decision get(String decisionName) { for (Decision decision : Decision.values()) { if (decision.toString().equalsIgnoreCase(decisionName)) { return decision; } } return null; } /** * Returns the canonical XACML 3.0 name for this <code>Decision</code>> * * @return the canonical XACML 3.0 <code>String</code> name for this <code>Decision</code> */ @Override public String toString() { return this.name; } }
apache-2.0