code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public ApiResponse<TaskByDidListEnvelope> getAllByDidWithHttpInfo(String did, Integer count, Integer offset, String status, String order, String sort) throws ApiException { com.squareup.okhttp.Call call = getAllByDidValidateBeforeCall(did, count, offset, status, order, sort, null, null); Type localVarReturnType = new TypeToken<TaskByDidListEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Returns the list of tasks for a particular device id with optional status filter. Returns the list of tasks for a particular device id with optional status filter. @param did Device ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param status Status filter. Comma-separated statuses. (optional) @param order Sort results by a field. Valid fields: createdOn. (optional) @param sort Sort order. Valid values: asc or desc. (optional) @return ApiResponse&lt;TaskByDidListEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public DeviceTypesInfoEnvelope getDeviceTypesInfo(String dtid) throws ApiException { ApiResponse<DeviceTypesInfoEnvelope> resp = getDeviceTypesInfoWithHttpInfo(dtid); return resp.getData(); }
Read a device type device management information. Read a device type device management information. @param dtid Device type ID. (required) @return DeviceTypesInfoEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<DeviceTypesInfoEnvelope> getDeviceTypesInfoWithHttpInfo(String dtid) throws ApiException { com.squareup.okhttp.Call call = getDeviceTypesInfoValidateBeforeCall(dtid, null, null); Type localVarReturnType = new TypeToken<DeviceTypesInfoEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Read a device type device management information. Read a device type device management information. @param dtid Device type ID. (required) @return ApiResponse&lt;DeviceTypesInfoEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public MetadataPropertiesEnvelope getManifestProperties(String dtid) throws ApiException { ApiResponse<MetadataPropertiesEnvelope> resp = getManifestPropertiesWithHttpInfo(dtid); return resp.getData(); }
Get a device type&#39;s device management manifest properties Get a device type&#39;s device management manifest properties @param dtid Device Type ID. (required) @return MetadataPropertiesEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<MetadataPropertiesEnvelope> getManifestPropertiesWithHttpInfo(String dtid) throws ApiException { com.squareup.okhttp.Call call = getManifestPropertiesValidateBeforeCall(dtid, null, null); Type localVarReturnType = new TypeToken<MetadataPropertiesEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Get a device type&#39;s device management manifest properties Get a device type&#39;s device management manifest properties @param dtid Device Type ID. (required) @return ApiResponse&lt;MetadataPropertiesEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public MetadataEnvelope getProperties(String did, Boolean includeTimestamp) throws ApiException { ApiResponse<MetadataEnvelope> resp = getPropertiesWithHttpInfo(did, includeTimestamp); return resp.getData(); }
Read a device&#39;s properties. Read a device&#39;s properties. @param did Device ID. (required) @param includeTimestamp Include timestamp. (optional) @return MetadataEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<MetadataEnvelope> getPropertiesWithHttpInfo(String did, Boolean includeTimestamp) throws ApiException { com.squareup.okhttp.Call call = getPropertiesValidateBeforeCall(did, includeTimestamp, null, null); Type localVarReturnType = new TypeToken<MetadataEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Read a device&#39;s properties. Read a device&#39;s properties. @param did Device ID. (required) @param includeTimestamp Include timestamp. (optional) @return ApiResponse&lt;MetadataEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public TaskStatusesEnvelope getStatuses(String tid, Integer count, Integer offset, String status, String dids) throws ApiException { ApiResponse<TaskStatusesEnvelope> resp = getStatusesWithHttpInfo(tid, count, offset, status, dids); return resp.getData(); }
Returns the details and status of a task id and the individual statuses of each device id in the list. Returns the details and status of a task id and the individual statuses of each device id in the list. @param tid Task ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param status Status filter. Comma-separated statuses. (optional) @param dids Devices filter. Comma-separated device IDs. (optional) @return TaskStatusesEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<TaskStatusesEnvelope> getStatusesWithHttpInfo(String tid, Integer count, Integer offset, String status, String dids) throws ApiException { com.squareup.okhttp.Call call = getStatusesValidateBeforeCall(tid, count, offset, status, dids, null, null); Type localVarReturnType = new TypeToken<TaskStatusesEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Returns the details and status of a task id and the individual statuses of each device id in the list. Returns the details and status of a task id and the individual statuses of each device id in the list. @param tid Task ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param status Status filter. Comma-separated statuses. (optional) @param dids Devices filter. Comma-separated device IDs. (optional) @return ApiResponse&lt;TaskStatusesEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public com.squareup.okhttp.Call getStatusesAsync(String tid, Integer count, Integer offset, String status, String dids, final ApiCallback<TaskStatusesEnvelope> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getStatusesValidateBeforeCall(tid, count, offset, status, dids, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<TaskStatusesEnvelope>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
Returns the details and status of a task id and the individual statuses of each device id in the list. (asynchronously) Returns the details and status of a task id and the individual statuses of each device id in the list. @param tid Task ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param status Status filter. Comma-separated statuses. (optional) @param dids Devices filter. Comma-separated device IDs. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
public TaskStatusesHistoryEnvelope getStatusesHistory(String tid, String did) throws ApiException { ApiResponse<TaskStatusesHistoryEnvelope> resp = getStatusesHistoryWithHttpInfo(tid, did); return resp.getData(); }
Returns the history of the status changes for a specific task id, or for a specific device id in that task. Returns the history of the status changes for a specific task id, or for a specific device id in that task. @param tid Task ID. (required) @param did Device ID. Optional. (optional) @return TaskStatusesHistoryEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<TaskStatusesHistoryEnvelope> getStatusesHistoryWithHttpInfo(String tid, String did) throws ApiException { com.squareup.okhttp.Call call = getStatusesHistoryValidateBeforeCall(tid, did, null, null); Type localVarReturnType = new TypeToken<TaskStatusesHistoryEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Returns the history of the status changes for a specific task id, or for a specific device id in that task. Returns the history of the status changes for a specific task id, or for a specific device id in that task. @param tid Task ID. (required) @param did Device ID. Optional. (optional) @return ApiResponse&lt;TaskStatusesHistoryEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public TaskEnvelope getTaskByID(String tid) throws ApiException { ApiResponse<TaskEnvelope> resp = getTaskByIDWithHttpInfo(tid); return resp.getData(); }
Returns the details and global status of a specific task id. Returns the details and global status of a specific task id. @param tid Task ID. (required) @return TaskEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<TaskEnvelope> getTaskByIDWithHttpInfo(String tid) throws ApiException { com.squareup.okhttp.Call call = getTaskByIDValidateBeforeCall(tid, null, null); Type localVarReturnType = new TypeToken<TaskEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Returns the details and global status of a specific task id. Returns the details and global status of a specific task id. @param tid Task ID. (required) @return ApiResponse&lt;TaskEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public TaskListEnvelope getTasks(String dtid, Integer count, Integer offset, String status, String order, String sort) throws ApiException { ApiResponse<TaskListEnvelope> resp = getTasksWithHttpInfo(dtid, count, offset, status, order, sort); return resp.getData(); }
Returns the all the tasks for a device type. Returns the all the tasks for a device type. @param dtid Device Type ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param status Status filter. Comma-separated statuses. (optional) @param order Sort results by a field. Valid fields: createdOn. (optional) @param sort Sort order. Valid values: asc or desc. (optional) @return TaskListEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<TaskListEnvelope> getTasksWithHttpInfo(String dtid, Integer count, Integer offset, String status, String order, String sort) throws ApiException { com.squareup.okhttp.Call call = getTasksValidateBeforeCall(dtid, count, offset, status, order, sort, null, null); Type localVarReturnType = new TypeToken<TaskListEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Returns the all the tasks for a device type. Returns the all the tasks for a device type. @param dtid Device Type ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param status Status filter. Comma-separated statuses. (optional) @param order Sort results by a field. Valid fields: createdOn. (optional) @param sort Sort order. Valid values: asc or desc. (optional) @return ApiResponse&lt;TaskListEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public com.squareup.okhttp.Call getTasksAsync(String dtid, Integer count, Integer offset, String status, String order, String sort, final ApiCallback<TaskListEnvelope> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getTasksValidateBeforeCall(dtid, count, offset, status, order, sort, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<TaskListEnvelope>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
Returns the all the tasks for a device type. (asynchronously) Returns the all the tasks for a device type. @param dtid Device Type ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param status Status filter. Comma-separated statuses. (optional) @param order Sort results by a field. Valid fields: createdOn. (optional) @param sort Sort order. Valid values: asc or desc. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
public MetadataQueryEnvelope queryProperties(String dtid, Integer count, Integer offset, String filter, Boolean includeTimestamp) throws ApiException { ApiResponse<MetadataQueryEnvelope> resp = queryPropertiesWithHttpInfo(dtid, count, offset, filter, includeTimestamp); return resp.getData(); }
Query device properties across devices. Query device properties across devices. @param dtid Device Type ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param filter Query filter. Comma-separated key&#x3D;value pairs (optional) @param includeTimestamp Include timestamp. (optional) @return MetadataQueryEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<MetadataQueryEnvelope> queryPropertiesWithHttpInfo(String dtid, Integer count, Integer offset, String filter, Boolean includeTimestamp) throws ApiException { com.squareup.okhttp.Call call = queryPropertiesValidateBeforeCall(dtid, count, offset, filter, includeTimestamp, null, null); Type localVarReturnType = new TypeToken<MetadataQueryEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Query device properties across devices. Query device properties across devices. @param dtid Device Type ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param filter Query filter. Comma-separated key&#x3D;value pairs (optional) @param includeTimestamp Include timestamp. (optional) @return ApiResponse&lt;MetadataQueryEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public com.squareup.okhttp.Call queryPropertiesAsync(String dtid, Integer count, Integer offset, String filter, Boolean includeTimestamp, final ApiCallback<MetadataQueryEnvelope> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = queryPropertiesValidateBeforeCall(dtid, count, offset, filter, includeTimestamp, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<MetadataQueryEnvelope>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
Query device properties across devices. (asynchronously) Query device properties across devices. @param dtid Device Type ID. (required) @param count Max results count. (optional) @param offset Result starting offset. (optional) @param filter Query filter. Comma-separated key&#x3D;value pairs (optional) @param includeTimestamp Include timestamp. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
public DeviceTypesInfoEnvelope updateDeviceTypesInfo(String dtid, DeviceTypesInfo deviceTypeInfo) throws ApiException { ApiResponse<DeviceTypesInfoEnvelope> resp = updateDeviceTypesInfoWithHttpInfo(dtid, deviceTypeInfo); return resp.getData(); }
Updates a device type information Updates a device type information @param dtid Device type ID. (required) @param deviceTypeInfo Device type info object to be set (required) @return DeviceTypesInfoEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<DeviceTypesInfoEnvelope> updateDeviceTypesInfoWithHttpInfo(String dtid, DeviceTypesInfo deviceTypeInfo) throws ApiException { com.squareup.okhttp.Call call = updateDeviceTypesInfoValidateBeforeCall(dtid, deviceTypeInfo, null, null); Type localVarReturnType = new TypeToken<DeviceTypesInfoEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Updates a device type information Updates a device type information @param dtid Device type ID. (required) @param deviceTypeInfo Device type info object to be set (required) @return ApiResponse&lt;DeviceTypesInfoEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public MetadataEnvelope updateServerProperties(String did, Object deviceProperties) throws ApiException { ApiResponse<MetadataEnvelope> resp = updateServerPropertiesWithHttpInfo(did, deviceProperties); return resp.getData(); }
Updates a device&#39;s server properties. Updates a device&#39;s server properties. @param did Device ID. (required) @param deviceProperties Device properties object to be set (required) @return MetadataEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<MetadataEnvelope> updateServerPropertiesWithHttpInfo(String did, Object deviceProperties) throws ApiException { com.squareup.okhttp.Call call = updateServerPropertiesValidateBeforeCall(did, deviceProperties, null, null); Type localVarReturnType = new TypeToken<MetadataEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Updates a device&#39;s server properties. Updates a device&#39;s server properties. @param did Device ID. (required) @param deviceProperties Device properties object to be set (required) @return ApiResponse&lt;MetadataEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public TaskUpdateResponse updateTask(String tid, TaskUpdateRequest taskUpdateRequest) throws ApiException { ApiResponse<TaskUpdateResponse> resp = updateTaskWithHttpInfo(tid, taskUpdateRequest); return resp.getData(); }
Updates a task for all devices - For now just allows changing the state to cancelled. Updates a task for all devices - For now just allows changing the state to cancelled. @param tid Task ID. (required) @param taskUpdateRequest Task update request (required) @return TaskUpdateResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<TaskUpdateResponse> updateTaskWithHttpInfo(String tid, TaskUpdateRequest taskUpdateRequest) throws ApiException { com.squareup.okhttp.Call call = updateTaskValidateBeforeCall(tid, taskUpdateRequest, null, null); Type localVarReturnType = new TypeToken<TaskUpdateResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Updates a task for all devices - For now just allows changing the state to cancelled. Updates a task for all devices - For now just allows changing the state to cancelled. @param tid Task ID. (required) @param taskUpdateRequest Task update request (required) @return ApiResponse&lt;TaskUpdateResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public DeviceTaskUpdateResponse updateTaskForDevice(String tid, String did, DeviceTaskUpdateRequest deviceTaskUpdateRequest) throws ApiException { ApiResponse<DeviceTaskUpdateResponse> resp = updateTaskForDeviceWithHttpInfo(tid, did, deviceTaskUpdateRequest); return resp.getData(); }
Updates a task for a specific device - For now just allows changing the state to cancelled. Updates a task for a specific device - For now just allows changing the state to cancelled. @param tid Task ID. (required) @param did Device ID. (required) @param deviceTaskUpdateRequest Device task update request (required) @return DeviceTaskUpdateResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<DeviceTaskUpdateResponse> updateTaskForDeviceWithHttpInfo(String tid, String did, DeviceTaskUpdateRequest deviceTaskUpdateRequest) throws ApiException { com.squareup.okhttp.Call call = updateTaskForDeviceValidateBeforeCall(tid, did, deviceTaskUpdateRequest, null, null); Type localVarReturnType = new TypeToken<DeviceTaskUpdateResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Updates a task for a specific device - For now just allows changing the state to cancelled. Updates a task for a specific device - For now just allows changing the state to cancelled. @param tid Task ID. (required) @param did Device ID. (required) @param deviceTaskUpdateRequest Device task update request (required) @return ApiResponse&lt;DeviceTaskUpdateResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
@ApiModelProperty(example = "null", required = true, value = "") public Map<String, Object> getData() { return data; }
Get data @return data
public static double Function1D(double x, double mean, double amplitude, double position, double width, double phase, double frequency) { double envelope = mean + amplitude * Math.exp(-Math.pow((x - position), 2) / Math.pow((2 * width), 2)); double carry = Math.cos(2 * Math.PI * frequency * (x - position) + phase); return envelope * carry; }
1-D Gabor function. @param x Value. @param mean Mean. @param amplitude Amplitude. @param position Position. @param width Width. @param phase Phase. @param frequency Frequency. @return Gabor response.
public static ComplexNumber Function2D(int x, int y, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio) { double X = x * Math.cos(orientation) + y * Math.sin(orientation); double Y = -x * Math.sin(orientation) + y * Math.cos(orientation); double envelope = Math.exp(-((X * X + aspectRatio * aspectRatio * Y * Y) / (2 * gaussVariance * gaussVariance))); double real = Math.cos(2 * Math.PI * (X / wavelength) + phaseOffset); double imaginary = Math.sin(2 * Math.PI * (X / wavelength) + phaseOffset); return new ComplexNumber(envelope * real, envelope * imaginary); }
2-D Complex Gabor function. @param x X axis coordinate. @param y Y axis coordinate. @param wavelength Wavelength. @param orientation Orientation. @param phaseOffset Phase offset. @param gaussVariance Gaussian variance. @param aspectRatio Aspect ratio. @return Gabor response.
public static double RealFunction2D(int x, int y, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio) { double X = x * Math.cos(orientation) + y * Math.sin(orientation); double Y = -x * Math.sin(orientation) + y * Math.cos(orientation); double envelope = Math.exp(-((X * X + aspectRatio * aspectRatio * Y * Y) / (2 * gaussVariance * gaussVariance))); double carrier = Math.cos(2 * Math.PI * (X / wavelength) + phaseOffset); return envelope * carrier; }
2-D Gabor function. compute only real part. @param x X axis coordinate. @param y Y axis coordinate. @param wavelength Wavelength. @param orientation Orientation. @param phaseOffset Phase offset. @param gaussVariance Gaussian variance. @param aspectRatio Aspect ratio. @return Gabor response.
public static double[][] Kernel2D(int size, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio) { double sigmaX = gaussVariance; double sigmaY = gaussVariance / aspectRatio; int xMax = (int) Math.ceil(Math.max(1, Math.max(Math.abs(size * sigmaX * Math.cos(orientation)), Math.abs(size * sigmaY * Math.sin(orientation))))); int yMax = (int) Math.ceil(Math.max(1, Math.max(Math.abs(size * sigmaX * Math.sin(orientation)), Math.abs(size * sigmaY * Math.cos(orientation))))); double[][] kernel = new double[2 * xMax + 1][2 * yMax + 1]; double sum = 0; for (int x = -xMax; x <= xMax; x++) { for (int y = -yMax; y <= yMax; y++) { kernel[x + xMax][y + yMax] = Gabor.ImaginaryFunction2D(x, y, wavelength, orientation, phaseOffset, gaussVariance, aspectRatio); sum += kernel[x + xMax][y + yMax]; } } for (int x = -xMax; x <= xMax; x++) { for (int y = -yMax; y <= yMax; y++) { kernel[x + xMax][y + yMax] /= sum; } } return kernel; }
2-D Gabor kernel. @param size Kernel size (should be odd). @param wavelength Wavelength. @param orientation Orientation. @param phaseOffset Phase offset. @param gaussVariance Gaussian variance. @param aspectRatio Aspect ratio. @return Gabor kernel.
public static double[][] Kernel2D(int size, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio, Config config) { double sigmaX = gaussVariance; double sigmaY = gaussVariance / aspectRatio; int xMax = (int) Math.ceil(Math.max(1, Math.max(Math.abs(size * sigmaX * Math.cos(orientation)), Math.abs(size * sigmaY * Math.sin(orientation))))); int yMax = (int) Math.ceil(Math.max(1, Math.max(Math.abs(size * sigmaX * Math.sin(orientation)), Math.abs(size * sigmaY * Math.cos(orientation))))); double[][] kernel = new double[2 * xMax + 1][2 * yMax + 1]; double sum = 0; switch (config) { case Real: for (int x = -xMax; x <= xMax; x++) { for (int y = -yMax; y <= yMax; y++) { kernel[x + xMax][y + yMax] = Gabor.RealFunction2D(x, y, wavelength, orientation, phaseOffset, gaussVariance, aspectRatio); sum += kernel[x + xMax][y + yMax]; } } break; case Imaginary: for (int x = -xMax; x <= xMax; x++) { for (int y = -yMax; y <= yMax; y++) { kernel[x + xMax][y + yMax] = Gabor.ImaginaryFunction2D(x, y, wavelength, orientation, phaseOffset, gaussVariance, aspectRatio); sum += kernel[x + xMax][y + yMax]; } } break; case Magnitude: for (int x = -xMax; x <= xMax; x++) { for (int y = -yMax; y <= yMax; y++) { ComplexNumber c = Gabor.Function2D(x, y, wavelength, orientation, phaseOffset, gaussVariance, aspectRatio); kernel[x + xMax][y + yMax] = c.getMagnitude(); sum += kernel[x + xMax][y + yMax]; } } break; case SquaredMagnitude: for (int x = -xMax; x <= xMax; x++) { for (int y = -yMax; y <= yMax; y++) { ComplexNumber c = Gabor.Function2D(x, y, wavelength, orientation, phaseOffset, gaussVariance, aspectRatio); kernel[x + xMax][y + yMax] = c.getSquaredMagnitude(); sum += kernel[x + xMax][y + yMax]; } } break; } for (int x = -xMax; x <= xMax; x++) { for (int y = -yMax; y <= yMax; y++) { kernel[x + xMax][y + yMax] /= sum; } } return kernel; }
2-D Gabor kernel. @param size Kernel size (should be odd). @param wavelength Wavelength. @param orientation Orientation. @param phaseOffset Phase offset. @param gaussVariance Gaussian variance. @param aspectRatio Aspect ratio. @param config Gabor configuration. @return Gabor kernel.
public static <T> TracedParallelBatch<T> of(Iterable<? extends Promise<T>> promises) { return new TracedParallelBatch<>(promises); }
Create a {@link TracedParallelBatch} for list of {@link Promise}s. @param promises an iterable of Promises @param <T> the type of value produced by each promise @return an instance of {@link TracedParallelBatch}.
public static <T> TracedParallelBatch<T> of(Promise<T>... promises) { return new TracedParallelBatch<>(Arrays.asList(promises)); }
Create a {@link TracedParallelBatch} for list of {@link Promise}s. @param promises vararg containing a list of {@link Promise}s. @param <T> the type of value produced by each promise @return an instance of {@link TracedParallelBatch}.
public static <T> ParallelBatch<T> of(final TraceContext context, Iterable<? extends Promise<T>> promises) { return ParallelBatch.of(promises) .execInit(execution -> execution.add(RatpackCurrentTraceContext.wrap(context))); }
Create a {@link TracedParallelBatch} for list of {@link Promise}s, with the specified trace context. @param context the trace context @param promises an iterable of Promises @param <T> the type of value produced by each promise @return an instance of {@link ParallelBatch}.
public static <T> ParallelBatch<T> of(final TraceContext context, Promise<T>... promises) { return of(context, Arrays.asList(promises)); }
Create a {@link TracedParallelBatch} for list of {@link Promise}s, with the specified trace context. @param context the trace context. @param promises vararg containing a list of {@link Promise}s. @param <T> the type of value produced by each promise @return an instance of {@link ParallelBatch}.
public Long getOldestTaskCreatedTime(){ Timer.Context ctx = getOldestTaskTimeTimer.time(); try { long oldest = Long.MAX_VALUE; /* * I am asking this question first, because if I ask it after I could * miss the oldest time if the oldest is polled and worked on */ Long oldestQueueTime = this.taskQueue.getOldestQueueTime(); if(oldestQueueTime != null) oldest = oldestQueueTime; //there is a tiny race condition here... but we just want to make our best attempt long inProgressOldestTime = tasksInProgressTracker.getOldestTime(); if(inProgressOldestTime < oldest) oldest = inProgressOldestTime; return oldest; } finally { ctx.stop(); } }
We want to get the best result possible as this value is used to determine what work needs to be recovered. @return
public Map<G, Integer> getGroupSizes(Predicate<G> predicate) { Timer.Context ctx = getGroupSizesTimer.time(); try { return this.taskQueue.getGroupSizes(predicate); } finally { ctx.stop(); } }
TODO: should we index this predicate somehow? @param predicate @return
@SuppressWarnings({ "unchecked", "rawtypes" }) public List<HazeltaskTask<G>> shutdownNow() { return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow(); }
SuppressWarnings I really want to return HazeltaskTasks instead of Runnable
public boolean containsKey(K key) { if(guavaMultiMap != null) return guavaMultiMap.containsKey(key); return hcMultiMap.containsKey(key); }
}
public void registerCollectionSizeGauge( CollectionSizeGauge collectionSizeGauge) { String name = createMetricName(LocalTaskExecutorService.class, "queue-size"); metrics.register(name, collectionSizeGauge); }
Calling this twice will not actually overwrite the gauge @param collectionSizeGauge
public ITrackedQueue<E> getQueueByGroup(G group) { lock.readLock().lock(); try { return this.queuesByGroup.get(group); } finally { lock.readLock().unlock(); } }
}
private Queue<E> getOrCreateGroupQueue(G group) { Queue<E> q = getQueueByGroup(group); if (q == null) { lock.writeLock().lock(); try { q = getQueueByGroup(group); if (q == null) { ITrackedQueue<E> newQ = new TrackedPriorityBlockingQueue<E>(); if (queuesByGroup.put(group, newQ) == null) { q = newQ; GroupMetadata<G> metadata = new GroupMetadata<G>(group, 0); long priority = groupPrioritizer.computePriority(metadata); groupRoute.add(new GroupMetadata<G>(group, priority)); emptyQueues.put(group, new GroupMetadata<G>(group, priority)); groups.add(group); } else { q = queuesByGroup.get(group); } } } finally { lock.writeLock().unlock(); } } return q; }
}
public boolean offer(E e) { G partition = e.getGroup(); lock.writeLock().lock(); try { Queue<E> q = getOrCreateGroupQueue(partition); if (q.size() == 0) { // remove from empty list and push onto available routes GroupMetadata<G> metadata = emptyQueues.remove(partition); if(metadata != null) groupRoute.add(metadata); } boolean result = q.offer(e); notEmpty.signal(); return result; } finally { lock.writeLock().unlock(); } }
Only 1 thread can write an element at a time... but multiple threads can read as long as they are using poll() or peek() Using poll(timeout) or take() will block writers and wait if the queue is empty
public ExecutorLoadBalancingConfig<GROUP> useEnumOrdinalPrioritizer(Class<GROUP> groupClass) { if(!groupClass.isEnum()) { throw new IllegalArgumentException("The group class "+groupClass+" is not an enum"); } groupPrioritizer = new EnumOrdinalPrioritizer<GROUP>(); return this; }
Use this if you have an enum used for your group type that defines the priority of a task and you ALWAYS want to execute high priority items over low priority items. You should really check out the <code>useLoadBalancedEnumOrdinalPrioritizer</code> which works similarly but prevents starvation of low priority items by allowing them to run some of the time @param groupClass @return
public ExecutorLoadBalancingConfig<GROUP> useLoadBalancedEnumOrdinalPrioritizer(Class<GROUP> groupClass) { if(!groupClass.isEnum()) { throw new IllegalArgumentException("The group class "+groupClass+" is not an enum"); } groupPrioritizer = new LoadBalancedPriorityPrioritizer<GROUP>(new EnumOrdinalPrioritizer<GROUP>()); return this; }
If you have priorities based on enums, this is the recommended prioritizer to use as it will prevent starvation of low priority items @param groupClass @return
public static <GROUP extends Serializable> ExecutorConfig<GROUP> basicGroupable() { return new ExecutorConfig<GROUP>() .withTaskIdAdapter((TaskIdAdapter<Groupable<GROUP>, GROUP, ?>) new DefaultGroupableTaskIdAdapter<GROUP>()); }
This configuration requires that all your tasks you submit to the system implement the Groupable interface. By default, it will round robin tasks from each group Tasks will be tracked internally in the system by randomly generated UUIDs @return
@Override public int compareTo(GroupMetadata<G> o) { //return ((Long)priority).compareTo(o.priority); int comparison = ((Long)priority).compareTo(o.priority); if(comparison == 0) { if(!group.equals(o.group)) { return -1; } } return comparison; }
compareTo must be consistent with equals. If the priority is equal however, and the groups are NOT equal, we want to place *this* item at the end of the priority queue. TODO: do we still need to do this "hack" now that we use a skiplist and not a priority queue that breaks ties arbitrarily?
public Collection<HazeltaskTask<GROUP>> call() throws Exception { try { if(isShutdownNow) return this.getDistributedExecutorService().shutdownNowWithHazeltask(); else this.getDistributedExecutorService().shutdown(); } catch(IllegalStateException e) {} return Collections.emptyList(); }
I promise that this is always a collection of HazeltaskTasks
public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) { return executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS); }
Will wait a maximum of 1 minute for each node to response with their result. If an error occurs on any member, we will always attempt to continue execution and collect as many results as possible. @param execSvc @param members @param callable @return
public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable, long maxWaitTime, TimeUnit unit) { Collection<MemberResponse<T>> result = new ArrayList<MemberResponse<T>>(members.size()); Map<Member, Future<T>> resultFutures = execSvc.submitToMembers(callable, members); for(Entry<Member, Future<T>> futureEntry : resultFutures.entrySet()) { Future<T> future = futureEntry.getValue(); Member member = futureEntry.getKey(); try { if(maxWaitTime > 0) { result.add(new MemberResponse<T>(member, future.get(maxWaitTime, unit))); } else { result.add(new MemberResponse<T>(member, future.get())); } //ignore exceptions... return what you can } catch (InterruptedException e) { Thread.currentThread().interrupt(); //restore interrupted status and return what we have return result; } catch (MemberLeftException e) { log.warn("Member {} left while trying to get a distributed callable result", member); } catch (ExecutionException e) { if(e.getCause() instanceof InterruptedException) { //restore interrupted state and return Thread.currentThread().interrupt(); return result; } else { log.warn("Unable to execute callable on "+member+". There was an error.", e); } } catch (TimeoutException e) { log.error("Unable to execute task on "+member+" within 10 seconds."); } catch (RuntimeException e) { log.error("Unable to execute task on "+member+". An unexpected error occurred.", e); } } return result; }
We will always try to gather as many results as possible and never throw an exception. TODO: Make MemberResponse hold an exception that we can populate if something bad happens so we always get to return something for a member in order to indicate a failure. Getting the result when there is an error should throw an exception. @param execSvc @param members @param callable @param maxWaitTime - a value of 0 indicates forever @param unit @return
@NotNull public List<SxGeoResult> getList(@NotNull String ip) { if (!IPV4_COMMA_SEPARATED_PATTERN.matcher(ip).matches()) { throw new IllegalArgumentException("Illegal IP address or list: " + ip); } clientQueriesCount++; List<SxGeoResult> cachedResult = cache == null ? null : cache.getList(ip); if (cachedResult != null) { return cachedResult; } try { NodeList ipNodes = query(ip); ArrayList<SxGeoResult> result = new ArrayList<>(); for (int i = 0; i < ipNodes.getLength(); i++) { result.add(parseIp((Element) ipNodes.item(i))); } if (cache != null) { cache.add(ip, result); } return result; } catch (ParserConfigurationException | SAXException | IOException e) { throw new RuntimeException(e); } }
Executes REST request and return results for a given IPs. Normally there is only 1 result in the list per IP. @param ip IP to get geo info for. Multiple IPs can be used with comma as separator. @return list of SxGeoResult results @throws IllegalArgumentException if IP address is invalid.
@Nullable public SxGeoResult get(@NotNull String ip) { if (!IPV4_PATTERN.matcher(ip).matches()) { throw new IllegalArgumentException("Illegal IP address: " + ip); } clientQueriesCount++; List<SxGeoResult> cachedResult = cache == null ? null : cache.getList(ip); if (cachedResult != null) { return cachedResult.isEmpty() ? null : cachedResult.get(0); } try { NodeList ipNodes = query(ip); SxGeoResult result = ipNodes.getLength() == 0 ? null : parseIp((Element) ipNodes.item(0)); if (cache != null) { cache.add(ip, Collections.singletonList(result)); } return result; } catch (ParserConfigurationException | SAXException | IOException e) { throw new RuntimeException(e); } }
Executes REST request for a single IP address.
@SuppressWarnings("unchecked") public <T> DistributedFuture<GROUP, T> createFuture(HazeltaskTask<GROUP> task) { DistributedFuture<GROUP, T> future = new DistributedFuture<GROUP, T>(topologyService, task.getGroup(), task.getId()); this.futures.put(task.getId(), (DistributedFuture<GROUP, Serializable>) future); return future; }
It is required that T be Serializable
public void errorFuture(UUID taskId, Exception e) { DistributedFuture<GROUP, Serializable> future = remove(taskId); if(future != null) { future.setException(e); } }
handles when a member leaves and hazelcast partition data is lost. We want to find the Futures that are waiting on lost data and error them
public void schedule(BackoffTask task, long initialDelay, long fixedDelay) { synchronized (queue) { start(); queue.put(new DelayedTimerTask(task, initialDelay, fixedDelay)); } }
Schedules the task with a fixed delay period and an initialDelay period. This functions like the normal java Timer. @param task @param initialDelay @param fixedDelay
public boolean addPendingTask(HazeltaskTask<GROUP> task, boolean replaceIfExists) { if(!replaceIfExists) return pendingTask.putIfAbsent(task.getId(), task) == null; pendingTask.put(task.getId(), task); return true; }
Add to the write ahead log (hazelcast IMap) that tracks all the outstanding tasks
public Future<HazeltaskTask<GROUP>> addPendingTaskAsync(HazeltaskTask<GROUP> task) { return pendingTask.putAsync(task.getId(), task); }
Asynchronously put the work into the pending map so we can work on submitting it to the worker if we wanted. Could possibly cause duplicate work if we execute the work, then add to the map. @param task @return
@Override public void handleApplicationCommandRequest(SerialMessage serialMessage, int offset, int endpoint) { logger.trace("Handle Message Manufacture Specific Request"); logger.debug(String.format("Received Manufacture Specific Information for Node ID = %d", this.getNode().getNodeId())); int command = serialMessage.getMessagePayloadByte(offset); switch (command) { case MANUFACTURER_SPECIFIC_GET: logger.warn(String.format("Command 0x%02X not implemented.", command)); return; case MANUFACTURER_SPECIFIC_REPORT: logger.trace("Process Manufacturer Specific Report"); int tempMan = ((serialMessage.getMessagePayloadByte(offset + 1)) << 8) | (serialMessage.getMessagePayloadByte(offset + 2)); int tempDeviceType = ((serialMessage.getMessagePayloadByte(offset + 3)) << 8) | (serialMessage.getMessagePayloadByte(offset + 4)); int tempDeviceId = ((serialMessage.getMessagePayloadByte(offset + 5)) << 8) | (serialMessage.getMessagePayloadByte(offset + 6)); this.getNode().setManufacturer(tempMan); this.getNode().setDeviceType(tempDeviceType); this.getNode().setDeviceId(tempDeviceId); logger.debug(String.format("Node %d Manufacturer ID = 0x%04x", this.getNode().getNodeId(), this.getNode().getManufacturer())); logger.debug(String.format("Node %d Device Type = 0x%04x", this.getNode().getNodeId(), this.getNode().getDeviceType())); logger.debug(String.format("Node %d Device ID = 0x%04x", this.getNode().getNodeId(), this.getNode().getDeviceId())); this.getNode().advanceNodeStage(); break; default: logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).", command, this.getCommandClass().getLabel(), this.getCommandClass().getKey())); } }
{@inheritDoc}
public static final synchronized void useValueFormat(String pattern) { if (pattern == null) sdf = null; else if (sdf == null) { sdf = new SimpleDateFormat(pattern); sdf.setCalendar(getCalendar()); } else sdf.applyPattern(pattern); }
Sets a user defined time value format used by all instances of this class. <p> The pattern is specified according to {@link SimpleDateFormat}. Subsequent time information, supplied and returned in textual representation, will use a layout formatted according this pattern.<br> Note, the format will rely on calendar default time symbols (i.e. language for example), and does not support the KNX DPT identifier "no-day" for day of week. This identifier can not be used therefore. @param pattern the new pattern specifying the value time format, <code>null</code> to reset to default value format
public String[] getAllValues() { final String[] buf = new String[data.length / 3]; for (int i = 0; i < buf.length; ++i) buf[i] = fromDPT(i); return buf; }
/* (non-Javadoc) @see tuwien.auto.calimero.dptxlator.DPTXlator#getAllValues()
public final void setValue(int dayOfWeek, int hour, int minute, int second) { data = set(dayOfWeek, hour, minute, second, new short[3], 0); }
Sets the day of week, hour, minute and second information for the first time item. <p> Any other items in the translator are discarded on successful set.<br> A day of week value of 0 corresponds to "no-day", indicating the day of week is not used. The first day of week is Monday with a value of 1, the last day is Sunday with a value of 7. <br> @param dayOfWeek day of week, 0 &lt;= day &lt;= 7 @param hour hour value, 0 &lt;= hour &lt;= 23 @param minute minute value, 0 &lt;= minute &lt;= 59 @param second second value, 0 &lt;= second &lt;= 59
public byte[] getData(byte[] dst, int offset) { final int end = Math.min(data.length, dst.length - offset) / 3 * 3; for (int i = 0; i < end; ++i) dst[offset + i] = (byte) data[i]; return dst; } /* (non-Javadoc) * @see tuwien.auto.calimero.dptxlator.DPTXlator#getSubTypes() */ public Map getSubTypes() { return types; } /** * @return the subtypes of the time translator type * @see DPTXlator#getSubTypesStatic() */ protected static Map getSubTypesStatic() { return types; } private String fromDPT(int index) { if (sdf != null) synchronized (DPTXlatorTime.class) { return sdf.format(new Date(fromDPTMillis(index))); } final int i = index * 3; // dow, hh:mm:ss final int h = data[i + HOUR] & 0x1F; final int m = data[i + MINUTE]; final int s = data[i + SECOND]; return DAYS[data[i + DOW] >> 5] + ", " + align(h) + h + ':' + align(m) + m + ':' + align(s) + s; } private long fromDPTMillis(int index) { synchronized (DPTXlatorTime.class) { getCalendar().clear(); final int i = index * 3; final int dow = data[i] >> 5 & 0x7; if (dow > 0) c.set(Calendar.DAY_OF_WEEK, dow == 7 ? 1 : dow + 1); c.set(Calendar.HOUR_OF_DAY, data[i + HOUR] & 0x1F); c.set(Calendar.MINUTE, data[i + MINUTE]); c.set(Calendar.SECOND, data[i + SECOND]); long ms = 0; try { ms = c.getTimeInMillis(); } catch (final IllegalArgumentException e) { DPTXlator.logger.error("from DPT in milliseconds not possible"); } return ms; } } protected void toDPT(String value, short[] dst, int index) throws KNXFormatException { if (sdf != null) synchronized (DPTXlatorTime.class) { toDPT(parse(value), dst, index); return; } final StringTokenizer t = new StringTokenizer(value, ": ,"); final int maxTokens = 4; final String[] tokens = new String[maxTokens]; // extract tokens int count = 0; for (; count < maxTokens && t.hasMoreTokens(); ++count) tokens[count] = t.nextToken(); // we allow day of week to be omitted in value if (count < 3) throw logThrow(LogLevel.WARN, "invalid time " + value, null, value); // on 4 tokens, day of week is included final int dow = count == 4 ? getDOW(tokens[0]) : 0; try { final int s = Short.parseShort(tokens[--count]); final int m = Short.parseShort(tokens[--count]); final int h = Short.parseShort(tokens[--count]); set(dow, h, m, s, dst, index); } catch (final KNXIllegalArgumentException e) { throw logThrow(LogLevel.WARN, "invalid time " + value, e.getMessage(), value); } catch (final NumberFormatException e) { throw logThrow(LogLevel.WARN, "invalid number in " + value, null, value); } } private short[] toDPT(long milliseconds, short[] dst, int index) { synchronized (DPTXlatorTime.class) { getCalendar().clear(); c.setTimeInMillis(milliseconds); final int dow = c.get(Calendar.DAY_OF_WEEK); set(dow == Calendar.SUNDAY ? 7 : dow - 1, c .get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c .get(Calendar.SECOND), dst, index); } return dst; } private short[] set(int dow, int hour, int minute, int second, short[] dst, int index) { if (dow < 0 || dow > 7) throw new KNXIllegalArgumentException("day of week out of range [0..7]"); if (hour < 0 || hour > 23) throw new KNXIllegalArgumentException("hour out of range [0..23]"); if (minute < 0 || minute > 59) throw new KNXIllegalArgumentException("minute out of range [0..59]"); if (second < 0 || second > 59) throw new KNXIllegalArgumentException("second out of range [0..59]"); final int i = 3 * index; dst[i + DOW] = (short) (dow << 5 | hour); dst[i + MINUTE] = (short) minute; dst[i + SECOND] = (short) second; return dst; } private int getDOW(String dow) throws KNXFormatException { for (int i = 0; i < DAYS.length; ++i) if (DAYS[i].equalsIgnoreCase(dow)) return i; throw logThrow(LogLevel.WARN, "invalid day of week " + dow, null, dow); } private long parse(String value) throws KNXFormatException { try { return sdf.parse(value).getTime(); } catch (final ParseException e) { throw logThrow(LogLevel.WARN, "invalid time format", e.getMessage(), value); } } private static String align(int number) { return number > 9 ? "" : "0"; } private static Calendar getCalendar() { // don't need to synchronize, it's harmless if we have 2 instances // and we synchronize on class anyway if (c == null) { final Calendar calendar = Calendar.getInstance(); calendar.setLenient(false); c = calendar; } return c; } }
/* (non-Javadoc) @see tuwien.auto.calimero.dptxlator.DPTXlator#getData(byte[], int)
public void send(CEMI frame, BlockingMode mode) throws KNXTimeoutException, KNXConnectionClosedException { if (layer == BUSMONITOR_LAYER) throw new KNXIllegalStateException("send not permitted in busmonitor mode"); if (!(frame instanceof CEMILData)) throw new KNXIllegalArgumentException("unsupported cEMI type"); super.send(frame, mode); }
Sends a cEMI frame to the remote server communicating with this endpoint. <p> Sending in busmonitor mode is not permitted.<br> @param frame cEMI message to send, the expected cEMI type is according to the used tunneling layer
void handleService(KNXnetIPHeader h, byte[] data, int offset) throws KNXFormatException, IOException { final int svc = h.getServiceType(); if (svc == KNXnetIPHeader.TUNNELING_REQ) { ServiceRequest req; try { req = PacketHelper.getServiceRequest(h, data, offset); } catch (final KNXFormatException e) { // check if at least the connection header of the service request // is correct and try to get its values req = PacketHelper.getEmptyServiceRequest(h, data, offset); final byte[] junk = new byte[h.getTotalLength() - h.getStructLength() - 4]; System.arraycopy(data, offset + 4, junk, 0, junk.length); logger.warn("received tunneling request with unknown cEMI part " + DataUnitBuilder.toHex(junk, " "), e); } if (req.getChannelID() != getChannelID()) { logger.warn("received wrong request channel-ID " + req.getChannelID() + ", expected " + getChannelID() + " - ignored"); return; } final short seq = req.getSequenceNumber(); if (seq == getSeqNoRcv() || seq + 1 == getSeqNoRcv()) { final short status = h.getVersion() == KNXNETIP_VERSION_10 ? ErrorCodes.NO_ERROR : ErrorCodes.VERSION_NOT_SUPPORTED; final byte[] buf = PacketHelper.toPacket(new ServiceAck( KNXnetIPHeader.TUNNELING_ACK, getChannelID(), seq, status)); final DatagramPacket p = new DatagramPacket(buf, buf.length, dataEP.getAddress(), dataEP.getPort()); socket.send(p); if (status == ErrorCodes.VERSION_NOT_SUPPORTED) { close(ConnectionCloseEvent.INTERNAL, "protocol version changed", LogLevel.ERROR, null); return; } } else logger.warn("tunneling request invalid receive-sequence " + seq + ", expected " + getSeqNoRcv()); if (seq == getSeqNoRcv()) { incSeqNoRcv(); final CEMI cemi = req.getCEMI(); // leave if we are working with an empty (broken) service request if (cemi == null) return; if (cemi.getMessageCode() == CEMILData.MC_LDATA_IND || cemi.getMessageCode() == CEMIBusMon.MC_BUSMON_IND) fireFrameReceived(cemi); else if (cemi.getMessageCode() == CEMILData.MC_LDATA_CON) { // invariant: notify listener before return from blocking send fireFrameReceived(cemi); setStateNotify(OK); } else if (cemi.getMessageCode() == CEMILData.MC_LDATA_REQ) logger.warn("received L-Data request - ignored"); } } else logger.warn("received unknown frame (service type 0x" + Integer.toHexString(svc) + ") - ignored"); }
/* (non-Javadoc) @see tuwien.auto.calimero.knxnetip.ConnectionImpl#handleService (tuwien.auto.calimero.knxnetip.servicetype.KNXnetIPHeader, byte[], int)
public void setKNXMedium(KNXMediumSettings settings) { if (settings == null) throw new KNXIllegalArgumentException("medium settings are mandatory"); if (medium != null && !settings.getClass().isAssignableFrom(medium.getClass()) && !medium.getClass().isAssignableFrom(settings.getClass())) throw new KNXIllegalArgumentException("medium differs"); medium = settings; }
/* (non-Javadoc) @see tuwien.auto.calimero.link.KNXNetworkLink#setKNXMedium (tuwien.auto.calimero.link.medium.KNXMediumSettings)
public final void setHopCount(int count) { if (count < 0 || count > 7) throw new KNXIllegalArgumentException("hop count out of range [0..7]"); hopCount = (byte) count; logger.info("hop count set to " + count); }
/* (non-Javadoc) @see tuwien.auto.calimero.link.KNXNetworkLink#setHopCount(int)
public void sendRequest(KNXAddress dst, Priority p, byte[] nsdu) throws KNXLinkClosedException, KNXTimeoutException { send(dst, p, nsdu, false); }
{@inheritDoc} When communicating with a KNX network which uses open medium, messages are broadcasted within domain (as opposite to system broadcast) by default. Specify <code>dst null</code> for system broadcast.
public void sendRequestWait(KNXAddress dst, Priority p, byte[] nsdu) throws KNXTimeoutException, KNXLinkClosedException { send(dst, p, nsdu, true); }
{@inheritDoc} When communicating with a KNX network which uses open medium, messages are broadcasted within domain (as opposite to system broadcast) by default. Specify <code>dst null</code> for system broadcast.
public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException, KNXLinkClosedException { doSend(adjustMsgType(msg), waitForCon); }
/* (non-Javadoc) @see tuwien.auto.calimero.link.KNXNetworkLink#send (tuwien.auto.calimero.cemi.CEMILData, boolean)
public String getName() { // do our own IP:port string, since InetAddress.toString() always prepends a '/' final InetSocketAddress a = conn.getRemoteAddress(); return "link " + a.getAddress().getHostAddress() + ":" + a.getPort(); }
/* (non-Javadoc) @see tuwien.auto.calimero.link.KNXNetworkLink#getName()
public void applyXMLDSigAsFirstChild (@Nonnull final PrivateKey aPrivateKey, @Nonnull final X509Certificate aCertificate, @Nonnull final Document aDocument) throws Exception { ValueEnforcer.notNull (aPrivateKey, "privateKey"); ValueEnforcer.notNull (aCertificate, "certificate"); ValueEnforcer.notNull (aDocument, "document"); ValueEnforcer.notNull (aDocument.getDocumentElement (), "Document is missing a document element"); if (aDocument.getDocumentElement ().getChildNodes ().getLength () == 0) throw new IllegalArgumentException ("Document element has no children!"); // Check that the document does not contain another Signature element final NodeList aNodeList = aDocument.getElementsByTagNameNS (XMLSignature.XMLNS, XMLDSigSetup.ELEMENT_SIGNATURE); if (aNodeList.getLength () > 0) throw new IllegalArgumentException ("Document already contains an XMLDSig Signature element!"); // Create the XMLSignature, but don't sign it yet. final XMLSignature aXMLSignature = createXMLSignature (aCertificate); // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. // -> The signature is always the first child element of the document // element for ebInterface final DOMSignContext aDOMSignContext = new DOMSignContext (aPrivateKey, aDocument.getDocumentElement (), aDocument.getDocumentElement ().getFirstChild ()); // The namespace prefix to be used for the signed XML aDOMSignContext.setDefaultNamespacePrefix (DEFAULT_NS_PREFIX); // Marshal, generate, and sign the enveloped signature. aXMLSignature.sign (aDOMSignContext); }
Apply an XMLDSig onto the passed document. @param aPrivateKey The private key used for signing. May not be <code>null</code>. @param aCertificate The certificate to be used. May not be <code>null</code>. @param aDocument The document to be signed. The signature will always be the first child element of the document element. The document may not contains any disg:Signature element. This element is inserted manually. @throws Exception In case something goes wrong @see #createXMLSignature(X509Certificate)
private static String determineMessage(@Nullable final String argumentName, @Nullable final Pattern pattern) { return argumentName != null && !argumentName.isEmpty() ? format(argumentName, pattern) : format(pattern); }
Determines the message to be used, depending on the passed argument name. If if the given argument name is {@code null} or empty {@code DEFAULT_MESSAGE} will be returned, otherwise a formatted {@code MESSAGE_WITH_NAME} with the passed name and pattern which the argument must match. @param argumentName the name of the passed argument @param pattern Pattern, that a string or character sequence should correspond to @return {@code DEFAULT_MESSAGE} if the given argument name is {@code null} or empty, otherwise a formatted {@code MESSAGE_WITH_NAME}
private static String format(@Nullable final Pattern pattern) { return String.format(DEFAULT_MESSAGE, patternToString(pattern)); }
Returns the formatted string {@link IllegalPatternArgumentException#DEFAULT_MESSAGE} with the given pattern which the argument must match. @param argumentName the name of the passed argument @param pattern Pattern, that a string or character sequence should correspond to @return a formatted string of message with the given argument name
private static String format(@Nullable final String argumentName, @Nullable final Pattern pattern) { final String p = patternToString(pattern); return String.format(MESSAGE_WITH_NAME, argumentName, p); }
Returns the formatted string {@link IllegalPatternArgumentException#MESSAGE_WITH_NAME} with the given {@code argumentName} and pattern which the argument must match. @param argumentName the name of the passed argument @param pattern Pattern, that a string or character sequence should correspond to @return a formatted string of message with the given argument name
private static String patternToString(@Nullable final Pattern pattern) { return pattern != null ? pattern.pattern() + " (flags: " + pattern.flags() + ")" : NO_PATTERN_PLACEHOLDER; }
Converts a {@link Pattern} to a string representation. @param pattern Pattern @return string representation of a pattern
public void setValues(String[] values) throws KNXFormatException { if (values.length > 0) { final short[] buf = new short[(typeSize > 0 ? typeSize : 1) * values.length]; for (int i = 0; i < values.length; ++i) toDPT(values[i], buf, i); data = buf; } }
Translates the array of strings according to the set datapoint ID. <p> If, and only if, all items in <code>values</code> can successfully be translated, they get stored by the translator, replacing any old items. On <code>values.length == 0</code>, no action is performed.<br> Textual commands contained in <code>values</code> are treated case insensitive. @param values string array holding values for translation @throws KNXFormatException if an item in <code>values</code> can't be translated due to a wrong formatted content, or if <code>value</code>doesn't fit into KNX data type
public void setValue(String value) throws KNXFormatException { final short[] buf = new short[typeSize > 0 ? typeSize : 1]; toDPT(value, buf, 0); data = buf; }
Translates the <code>value</code> according to the set datapoint ID. <p> If, and only if, <code>value</code> can successfully be translated, it gets stored by the translator, replacing any old items. Textual commands contained in <code>value</code> are treated case insensitive.<br> The <code>value</code> string might have its unit of measure appended (units are case sensitive). @param value value represented as string for translation, case insensitive @throws KNXFormatException if <code>value</code> can't be translated due to wrong formatted content, or if <code>value</code>doesn't fit into KNX data type
protected void setTypeID(Map availableTypes, String dptID) throws KNXFormatException { final DPT t = (DPT) availableTypes.get(dptID); if (t == null) { // don't call logThrow since dpt is not set yet final String s = "DPT " + dptID + " is not available"; logger.warn(s); throw new KNXFormatException(s, dptID); } dpt = t; }
Sets the DPT for the translator to use for translation, doing a lookup before in the translator's map containing the available, implemented datapoint types. <p> @param availableTypes map of the translator with available, implemented DPTs; the map key is a dptID string, map value is of type {@link DPT} @param dptID the ID as string of the datapoint type to set @throws KNXFormatException on DPT not available
final String removeUnit(String value) { final int i; if (dpt.getUnit().length() > 0 && (i = value.lastIndexOf(dpt.getUnit())) > -1) return value.substring(0, i).trim(); // java number parsing routines are really picky, remove WS return value.trim(); }
Returns value with unit cut off at end of string, if current DPT has a unit specified. <p> Whitespace are removed from both ends. @param value value string representation @return trimmed value string without unit
final KNXFormatException logThrow(LogLevel level, String msg, String excMsg, String item) { final KNXFormatException e = new KNXFormatException(excMsg != null ? excMsg : msg, item); if (excMsg != null) logger.log(level, dpt.getID() + " - " + msg, e); else logger.log(level, dpt.getID() + " - " + msg); return e; }
Helper which logs message and creates a format exception. <p> Adds the current dpt ID as prefix to log output. @param level log level @param msg log output, exception message if <code>excMsg</code> is <code>null</code> @param excMsg exception message, if <code>null</code> <code>msg</code> is used @param item item in KNXFormatException, might be <code>null</code>
public byte[] getData(byte[] dst, int offset) { final int end = Math.min(data.length, dst.length - offset) & ~0x03; for (int i = 0; i < end; ++i) dst[offset + i] = (byte) data[i]; return dst; } /* (non-Javadoc) * @see tuwien.auto.calimero.dptxlator.DPTXlator#getSubTypes() */ public final Map getSubTypes() { return types; } /** * @return the subtypes of the 4-byte unsigned translator type * @see DPTXlator#getSubTypesStatic() */ protected static Map getSubTypesStatic() { return types; } private long fromDPT(int index) { final int i = 4 * index; return (long) data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]; } private String makeString(int index) { return appendUnit(Long.toString(fromDPT(index))); } protected void toDPT(String value, short[] dst, int index) throws KNXFormatException { try { toDPT(Long.decode(removeUnit(value)).longValue(), dst, index); } catch (final NumberFormatException e) { throw logThrow(LogLevel.WARN, "wrong value format " + value, null, value); } } private short[] toDPT(long value, short[] dst, int index) throws KNXFormatException { if (value < 0 || value > 0xFFFFFFFFL) throw logThrow(LogLevel.WARN, "translation error for " + value, "input value out of range", Long.toString(value)); final int i = 4 * index; dst[i] = (short) ((value >> 24) & 0xFF); dst[i + 1] = (short) ((value >> 16) & 0xFF); dst[i + 2] = (short) ((value >> 8) & 0xFF); dst[i + 3] = (short) (value & 0xFF); return dst; } }
/* (non-Javadoc) @see tuwien.auto.calimero.dptxlator.DPTXlator#getData(byte[], int)
public static <K> Map<K, Integer> rankMapOnIntegerValue(Map<K, Integer> inputMap) { Map<K, Integer> newMap = new TreeMap<K, Integer>(new IntegerValueComparator(inputMap)); newMap.putAll(inputMap); Map<K, Integer> linkedMap = new LinkedHashMap<K, Integer>(newMap); return linkedMap; }
Ranks a map based on integer values @param inputMap Input @return The ranked map
@Override public int compare(Object a, Object b) { if (base.get(a) >= base.get(b)) { return -1; } return 1; }
/* (non-Javadoc) @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
public double intersectionVolume(AbstractSphereObstacle o) { if(dimension != o.getDimension()){ throw new IllegalArgumentException("Obstacles have different dimensions"); } double result = 0; double distance = 0; for(int i = 0; i < dimension; i++){ distance += Math.pow(position[i]-o.getPosition()[i],2); } distance = Math.sqrt(distance); if(distance<0.0000000001){ return Math.min(getVolume(), o.getVolume()); } double r = getRadius(); double r_ = o.getRadius(); if(distance> Math.max(r, r_)){ return 0; } double d = distance; if(dimension==2){ result = r*r*Math.acos( (d*d+r*r-r_*r_)/(2*d*r) )+ r_*r_*Math.acos( (d*d+r_*r_-r*r)/(2*d*r_) )- 0.5*Math.sqrt( (-d+r+r_)*(d+r-r_)*(d-r+r_)*(d+r+r_) ); } else if(dimension==3){ result = Math.PI*Math.pow(r_+r-d,2)*(d*d+2*d*r-3*r*r+2*d*r_+6*r*r_-3*r_*r_)/(12*d); } return result; }
For 2D: Implements formula 14 of http://mathworld.wolfram.com/Circle-CircleIntersection.html For 3D: Implements formula 16 of http://mathworld.wolfram.com/Sphere-SphereIntersection.html
byte[] toByteArray(ByteArrayOutputStream os) { byte[] buf = ctrlPt.toByteArray(); os.write(buf, 0, buf.length); buf = dataPt.toByteArray(); os.write(buf, 0, buf.length); buf = cri.toByteArray(); os.write(buf, 0, buf.length); return os.toByteArray(); }
/* (non-Javadoc) @see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#toByteArray (java.io.ByteArrayOutputStream)
@Descriptor("Gets info about the declarations available") public void declarations(@Descriptor("declarations [--type import|export]") String... parameters) { String type = getArgumentValue("--type", parameters); try { if ((type == null) || "import".equals(type)) { List<ServiceReference> allServiceRef = getAllServiceRefs(ImportDeclaration.class); displayDeclarationList(allServiceRef); } if ((type == null) || "export".equals(type)) { List<ServiceReference> allServiceRef = getAllServiceRefs(ExportDeclaration.class); displayDeclarationList(allServiceRef); } } catch (Exception e) { LOG.error("failed to execute command", e); print("failed to execute the command"); } }
---------------- DECLARATION
@Descriptor("Gets the importation/exportation linker available") public void linker(@Descriptor("linker [-(import|export)] [ID name]") String... parameters) { List<ServiceReference> exportationLinkerRef = getAllServiceRefs(ExportationLinker.class); List<ServiceReference> importationLinkerRef = getAllServiceRefs(ImportationLinker.class); StringBuilder sbFinal = new StringBuilder(); if (exportationLinkerRef.isEmpty() && importationLinkerRef.isEmpty()) { sbFinal.append("No linkers available.\n"); } else { if (!exportationLinkerRef.isEmpty()) { for (ServiceReference reference : exportationLinkerRef) { StringBuilder sb = new StringBuilder(); sb.append(displayServiceInfo(reference)); sb.append(createASCIIBox("Properties", displayServiceProperties(reference))); sbFinal.append(createASCIIBox("Exportation Linker", sb)); } } if (!importationLinkerRef.isEmpty()) { for (ServiceReference reference : importationLinkerRef) { StringBuilder sb = new StringBuilder(); sb.append(displayServiceInfo(reference)); sb.append(createASCIIBox("Properties", displayServiceProperties(reference))); sbFinal.append(createASCIIBox("Importation Linker", sb)); } } } print(sbFinal.toString()); }
---------------- LINKER
@Descriptor("Gets the discovery available in the platform") public void discovery(@Descriptor("discovery [discovery name]") String... parameters) { List<ServiceReference> discoveryRef = getAllServiceRefs(DiscoveryService.class); StringBuilder sbFinal = new StringBuilder(); if (discoveryRef.isEmpty()) { sbFinal.append("No discovery available.\n"); } else { for (ServiceReference reference : discoveryRef) { StringBuilder sb = new StringBuilder(); sb.append(displayServiceInfo(reference)); sb.append(createASCIIBox("Properties", displayServiceProperties(reference))); sbFinal.append(createASCIIBox("Discovery", sb)); } } print(sbFinal.toString()); }
---------------- DISCOVERY
@Descriptor("Gets the importer available in the platform") public void importer(@Descriptor("importer [importer name]") String... parameters) { Map<ServiceReference, ImporterService> importerRefsAndServices = getAllServiceRefsAndServices(ImporterService.class); StringBuilder sbFinal = new StringBuilder(); if (importerRefsAndServices.isEmpty()) { sbFinal.append("No importers available.\n"); } else { for (Map.Entry<ServiceReference, ImporterService> e : importerRefsAndServices.entrySet()) { StringBuilder sb = new StringBuilder(); sb.append(displayServiceInfo(e.getKey())); sb.append(String.format("importer name = %s%n", e.getValue().getName())); sb.append(createASCIIBox("Properties", displayServiceProperties(e.getKey()))); sbFinal.append(createASCIIBox("Importer", sb)); } } print(sbFinal.toString()); }
---------------- IMPORTER
@Descriptor("Gets the exporter available in the platform") public void exporter(@Descriptor("exporter [exporter name]") String... parameters) { Map<ServiceReference, ExporterService> exporterRefsAndServices = getAllServiceRefsAndServices(ExporterService.class); StringBuilder sbFinal = new StringBuilder(); if (exporterRefsAndServices.isEmpty()) { print("No exporter available."); } else { for (Map.Entry<ServiceReference, ExporterService> e : exporterRefsAndServices.entrySet()) { StringBuilder sb = new StringBuilder(); sb.append(displayServiceInfo(e.getKey())); sb.append(String.format("exporter name = %s%n", e.getValue().getName())); sb.append(createASCIIBox("Properties", displayServiceProperties(e.getKey()))); sbFinal.append(createASCIIBox("Exporter", sb)); } } print(sbFinal.toString()); }
---------------- EXPORTER
@Descriptor("Send event admin messages") public void sendmessage(@Descriptor("sendmessage BUS [KEY=VALUE ]*") String... parameters) { assert parameters[0] != null; String bus = parameters[0]; Dictionary eventAdminPayload = new Hashtable(); for (String m : parameters) { if (m.contains("=")) { StringTokenizer st = new StringTokenizer(m, "="); assert st.countTokens() == 2; String key = st.nextToken(); String value = st.nextToken(); eventAdminPayload.put(key, value); } } Event eventAdminMessage = new Event(bus, eventAdminPayload); print(String.format("Sending message to the bus %s with the arguments %s", bus, eventAdminPayload)); print("Event admin message sent"); eventAdmin.sendEvent(eventAdminMessage); }
---------------- SEND MESSAGE
private <T> List<ServiceReference> getAllServiceRefs(Class<T> klass) { ServiceReference[] importDeclarationsRef; try { importDeclarationsRef = context.getAllServiceReferences(klass.getName(), null); } catch (InvalidSyntaxException e) { LOG.error("Failed to retrieved services " + klass.getName(), e); return new ArrayList<ServiceReference>(); } if (importDeclarationsRef != null) { return Arrays.asList(importDeclarationsRef); } return new ArrayList<ServiceReference>(); }
---------------- UTILS SERVICES
private static StringBuilder displayServiceProperties(ServiceReference reference) { StringBuilder sb = new StringBuilder(); for (String propertyKey : reference.getPropertyKeys()) { sb.append(String.format("%s = %s%n", propertyKey, reference.getProperty(propertyKey))); } if (reference.getPropertyKeys().length == 0) { sb.append("EMPTY"); } return sb; }
---------------- UTILS DISPLAY
public static void main(String[] args) { try { // read the command line options and run the client final Map options = new HashMap(); if (parseOptions(args, options)) new PropClient().run(options); } catch (final Throwable t) { if (t.getMessage() != null) System.out.println(t.getMessage()); } }
Entry point for running the PropClient. <p> An IP host or port identifier has to be supplied to specify the endpoint for the KNX network access.<br> To show the usage message of this tool on the console, supply the command line option -help (or -h).<br> Command line options are treated case sensitive. Available options for the property client: <ul> <li><code>-help -h</code> show help message</li> <li><code>-version</code> show tool/library version and exit</li> <li><code>-verbose -v</code> enable verbose status output</li> <li><code>-local -l</code> local device management</li> <li><code>-remote -r</code> <i>KNX addr</i> &nbsp;remote property service</li> <li><code>-definitions -d</code> <i>file</i> &nbsp;use property definition file</li> <li><code>-localhost</code> <i>id</i> &nbsp;local IP/host name</li> <li><code>-localport</code> <i>number</i> &nbsp;local UDP port (default system assigned)</li> <li><code>-port -p</code> <i>number</i> &nbsp;UDP port on host (default 3671)</li> <li><code>-nat -n</code> enable Network Address Translation</li> <li><code>-serial -s</code> use FT1.2 serial communication</li> </ul> For local device management these options are available: <ul> <li><code>-emulatewriteenable -e</code> check write-enable of a property</li> </ul> For remote property service these options are available: <ul> <li><code>-routing</code> use KNXnet/IP routing</li> <li><code>-medium -m</code> <i>id</i> &nbsp;KNX medium [tp0|tp1|p110|p132|rf] (defaults to tp1)</li> <li><code>-connect -c</code> connection oriented mode</li> <li><code>-authorize -a</code> <i>key</i> &nbsp;authorize key to access KNX device</li> </ul> @param args command line options for property client
private PropertyAdapter create(Map options) throws KNXException { // add a log writer for the console (System.out), setting a // user log level, if specified LogManager.getManager().addWriter(null, new ConsoleWriter(options.containsKey("verbose"))); // create local and remote socket address for use in adapter final InetSocketAddress local = createLocalSocket((InetAddress) options.get("localhost"), (Integer) options .get("localport")); final InetSocketAddress host = new InetSocketAddress((InetAddress) options.get("host"), ((Integer) options .get("port")).intValue()); // decide what type of adapter to create if (options.containsKey("localDM")) return createLocalDMAdapter(local, host, options); return createRemoteAdapter(local, host, options); }
Creates the property adapter to be used with the property client depending on the supplied user <code>options</code>. <p> There are two types of property adapters. One uses KNXnet/IP local device management to access KNX properties in an interface object, the other type uses remote property services. The remote adapter needs a KNX network link to access the KNX network, the link is also created by this method if this adapter type is requested. @param options contains parameters for property adapter creation @return the created adapter @throws KNXException on adapter creation problem
private PropertyAdapter createLocalDMAdapter(InetSocketAddress local, InetSocketAddress host, Map options) throws KNXException { return new KnIPDeviceMgmtAdapter(local, host, options.containsKey("nat"), new PropertyListener(), options.containsKey("emulatewrite")); }
Creates a local device management adapter. <p> @param local local socket address @param host remote socket address of host @param options contains parameters for property adapter creation @return local DM adapter @throws KNXException on adapter creation problem
private String[] readLine(BufferedReader r) throws IOException { System.out.print("> "); final String line = r.readLine(); return line != null ? split(line) : null; }
Writes command prompt and waits for command request from user. <p> @param r input reader @return array with command and command arguments @throws IOException on I/O error