code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
package android_testsuite;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android_testsuite.mytest.application_search.AppSearchActivity;
import android_testsuite.mytest.application_search.UidActivity;
import android_testsuite.mytest.camera.CameraActivity;
import android_testsuite.mytest.camera.CameraIntentTestActivity;
import android_testsuite.mytest.custom_loading.CustomLoadingActivity;
import android_testsuite.mytest.media.MediaPlayerTestActivity;
import android_testsuite.mytest.network_test.HttpActivity;
import android_testsuite.mytest.network_test.SocketActivity;
import android_testsuite.mytest.rsa.RsaActivity;
import android_testsuite.mytest.seekbar.SeekBarActivity;
/**
* @author Ren Hui
* @since 1.0.1.058
*/
public class GuideActivity extends Activity {
private Button mBtSelHttp;
private Button mBtSelSocket;
private Button mBtSearchApp;
private Button mBtRSa;
private Button mBtUid;
private Button mBtMedia;
private Button mCameraBt;
private Button mCustomLoadingBt;
private Button mCameraNewBtn;
private Button mSeekBarBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guide);
this.mBtSelHttp = (Button) findViewById(R.id.bt_selHttp);
mBtSelHttp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(GuideActivity.this, HttpActivity.class);
GuideActivity.this.startActivity(intent);
}
});
this.mBtSelSocket = (Button) findViewById(R.id.bt_selSocket);
mBtSelSocket.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(GuideActivity.this, SocketActivity.class);
GuideActivity.this.startActivity(intent);
}
});
this.mBtSearchApp = (Button) findViewById(R.id.bt_searchApp);
mBtSearchApp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(GuideActivity.this, AppSearchActivity.class);
GuideActivity.this.startActivity(intent);
}
});
this.mBtRSa = (Button) findViewById(R.id.RSA);
mBtRSa.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(GuideActivity.this, RsaActivity.class);
GuideActivity.this.startActivity(intent);
}
});
this.mBtUid = (Button) findViewById(R.id.uid);
mBtUid.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(GuideActivity.this, UidActivity.class);
GuideActivity.this.startActivity(intent);
}
});
this.mBtMedia = (Button) findViewById(R.id.media);
mBtMedia.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(GuideActivity.this, MediaPlayerTestActivity.class);
GuideActivity.this.startActivity(intent);
}
});
this.mCameraBt = (Button) findViewById(R.id.camera_intent);
mCameraBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(GuideActivity.this, CameraIntentTestActivity.class);
GuideActivity.this.startActivity(intent);
}
});
this.mCustomLoadingBt = (Button) findViewById(R.id.custom_loading);
mCustomLoadingBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(GuideActivity.this, CustomLoadingActivity.class));
}
});
mCameraNewBtn = (Button) findViewById(R.id.camera);
mCameraNewBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(GuideActivity.this, CameraActivity.class));
}
});
mSeekBarBtn = (Button) findViewById(R.id.seek_bar);
mSeekBarBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(GuideActivity.this, SeekBarActivity.class));
}
});
}
}
| renhui/android_career | business/android_testsuite/android_testsuite/android_testsuite/src/main/java/android_testsuite/GuideActivity.java | Java | apache-2.0 | 5,130 |
// 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.cloudstack.api.command.user.loadbalancer;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.DomainResponse;
import org.apache.cloudstack.api.response.ProjectResponse;
import org.apache.cloudstack.api.response.SslCertResponse;
import org.apache.cloudstack.context.CallContext;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import org.apache.cloudstack.network.tls.CertService;
@APICommand(name = "uploadSslCert", description = "Upload a certificate to CloudStack", responseObject = SslCertResponse.class,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class UploadSslCertCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UploadSslCertCmd.class.getName());
private static final String s_name = "uploadsslcertresponse";
@Inject
CertService _certService;
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name = ApiConstants.CERTIFICATE, type = CommandType.STRING, required = true, description = "SSL certificate", length = 16384)
private String cert;
@Parameter(name = ApiConstants.PRIVATE_KEY, type = CommandType.STRING, required = true, description = "Private key", length = 16384)
private String key;
@Parameter(name = ApiConstants.CERTIFICATE_CHAIN, type = CommandType.STRING, description = "Certificate chain of trust", length = 2097152)
private String chain;
@Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "Password for the private key")
private String password;
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account that will own the SSL certificate")
private String accountName;
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "an optional project for the SSL certificate")
private Long projectId;
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "domain ID of the account owning the SSL certificate")
private Long domainId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public String getCert() {
return cert;
}
public String getKey() {
return key;
}
public String getChain() {
return chain;
}
public String getPassword() {
return password;
}
public String getAccountName() {
return accountName;
}
public Long getDomainId() {
return domainId;
}
public Long getProjectId() {
return projectId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
ResourceAllocationException, NetworkRuleConflictException {
try {
SslCertResponse response = _certService.uploadSslCert(this);
setResponseObject(response);
response.setResponseName(getCommandName());
} catch (Exception e) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return CallContext.current().getCallingAccount().getId();
}
}
| jcshen007/cloudstack | api/src/org/apache/cloudstack/api/command/user/loadbalancer/UploadSslCertCmd.java | Java | apache-2.0 | 5,159 |
package info.cyanac.plugin.bukkit;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
public class CyanACTabCompleter implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if(command.getName().equalsIgnoreCase("cyanac")){
List<String> tabCompletionList = new ArrayList();
tabCompletionList.add("help");
tabCompletionList.add("resync");
tabCompletionList.add("license");
return tabCompletionList;
}
return null;
}
}
| Moritz30-Projects/CyanAC-Plugin | src/info/cyanac/plugin/bukkit/CyanACTabCompleter.java | Java | apache-2.0 | 675 |
package pe.com.ccpl.siconc.web.service;
import pe.com.ccpl.siconc.web.model.Role;
public interface RoleService {
public Role getRole(int id);
}
| JR-CCPL87/ccpl-affirmation | src/main/java/pe/com/ccpl/siconc/web/service/RoleService.java | Java | apache-2.0 | 150 |
/*
* Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) 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.wso2.developerstudio.eclipse.artifact.proxyservice.validators;
import org.apache.axiom.om.OMElement;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.wso2.developerstudio.eclipse.artifact.proxyservice.model.ProxyServiceModel;
import org.wso2.developerstudio.eclipse.artifact.proxyservice.model.ProxyServiceModel.TargetEPType;
import org.wso2.developerstudio.eclipse.artifact.proxyservice.utils.PsArtifactConstants;
import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBArtifact;
import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBProjectArtifact;
import org.wso2.developerstudio.eclipse.platform.core.exception.FieldValidationException;
import org.wso2.developerstudio.eclipse.platform.core.model.AbstractFieldController;
import org.wso2.developerstudio.eclipse.platform.core.project.model.ProjectDataModel;
import org.wso2.developerstudio.eclipse.project.extensions.templates.ArtifactTemplate;
import org.wso2.developerstudio.eclipse.platform.ui.validator.CommonFieldValidator;
import java.util.List;
public class ProxyServiceProjectFieldController extends AbstractFieldController {
public void validate(String modelProperty, Object value, ProjectDataModel model)
throws FieldValidationException {
boolean optWsdlbasedProxy = false;
boolean optCustomProxy = false;
ArtifactTemplate selectedTemplate = (ArtifactTemplate)model.getModelPropertyValue("ps.type");
if(selectedTemplate!=null){
optWsdlbasedProxy = selectedTemplate.getId().equalsIgnoreCase(PsArtifactConstants.WSDL_BASED_PROXY_TEMPL_ID);
optCustomProxy = (selectedTemplate.isCustom() || selectedTemplate.getId()
.equalsIgnoreCase(PsArtifactConstants.CUSTOM_PROXY_TEMPL_ID));
}
if (modelProperty.equals("ps.name")) {
CommonFieldValidator.validateArtifactName(value);
if (value != null) {
String resource = value.toString();
ProxyServiceModel proxyModel = (ProxyServiceModel) model;
if (proxyModel != null) {
IContainer resLocation = proxyModel.getProxyServiceSaveLocation();
if (resLocation != null) {
IProject project = resLocation.getProject();
ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact();
try {
esbProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile());
List<ESBArtifact> allArtifacts = esbProjectArtifact.getAllESBArtifacts();
for (ESBArtifact artifact : allArtifacts) {
if (resource.equals(artifact.getName())) {
throw new FieldValidationException("");
}
}
} catch (Exception e) {
throw new FieldValidationException("Specified proxy service name already exsits.");
}
}
}
}
} else if (modelProperty.equals("import.file")) {
CommonFieldValidator.validateImportFile(value);
} else if (modelProperty.equals("proxy.target.ep.type")) {
/** //TODO:
if((((ProxyServiceModel)model).getTargetEPType()==TargetEPType.URL) && !(optWsdlbasedProxy||optCustomProxy)){
throw new FieldValidationException("Specified Target Endpoint");
}**/
} else if (modelProperty.equals("templ.common.ps.epurl")) {
if (((ProxyServiceModel)model).getTargetEPType() == TargetEPType.URL && !(optWsdlbasedProxy||optCustomProxy)) {
if (value == null || value.toString().equals("")) {
throw new FieldValidationException("Target Endpoint URL cannot be empty. Please specify a valid Endpoint URL.");
} else {
CommonFieldValidator.isValidUrl(value.toString().trim(), "Endpoint URL");
}
}
} else if (modelProperty.equals("templ.common.ps.epkey")) {
if ((((ProxyServiceModel)model).getTargetEPType() == TargetEPType.REGISTRY) && (value == null ||
value.toString().equals("")) && !(optWsdlbasedProxy||optCustomProxy)) {
throw new FieldValidationException("Target Registry Endpoint key is invalid or empty. Please specify a valid Endpoint Key.");
}
} else if (modelProperty.equals("templ.secure.ps.secpolicy")) {
} else if (modelProperty.equals("templ.wsdl.ps.wsdlurl")) {
if (optWsdlbasedProxy) {
if (value == null || value.toString().equals("")) {
throw new FieldValidationException("Target WSDL URL cannot be empty. Please specify a valid WSDL URI.");
} else {
CommonFieldValidator.isValidUrl(value.toString().trim(), "WSDL URL");
}
}
} else if (modelProperty.equals("templ.wsdl.ps.wsdlservice")) {
if (optWsdlbasedProxy && (value == null || value.toString().equals(""))) {
throw new FieldValidationException("Target WSDL service is invalid or empty. Please specify a valid WSDL Service.");
}
} else if (modelProperty.equals("templ.wsdl.ps.wsdlport")) {
if (optWsdlbasedProxy && (value == null || value.toString().equals(""))) {
throw new FieldValidationException("Target WSDL port is invalid or empty. Please specify a valid WSDL Port.");
}
} else if (modelProperty.equals("templ.wsdl.ps.publishsame")) {
} else if (modelProperty.equals("templ.logging.ps.reqloglevel")) {
} else if (modelProperty.equals("templ.logging.ps.resloglevel")) {
} else if (modelProperty.equals("templ.transformer.ps.xslt")) {
if (selectedTemplate.getId().equalsIgnoreCase(PsArtifactConstants.TRANSFORMER_PROXY_TEMPL_ID)) {
if (value == null || StringUtils.isBlank(value.toString())) {
throw new FieldValidationException("Request XSLT key cannot be empty. Please specify a valid XSLT key.");
}
}
} else if (modelProperty.equals("templ.common.ps.eplist")) {
if ((((ProxyServiceModel)model).getTargetEPType()==TargetEPType.PREDEFINED) && (value==null || value.toString().equals(""))) {
throw new FieldValidationException("Target Predefined Endpoint key cannot be empty. Please specify a valid Predefined Endpoint.");
}
} else if (modelProperty.equals("save.file")) {
IResource resource = (IResource)value;
if (resource == null || !resource.exists()) {
throw new FieldValidationException("Please specify a valid ESB Project to Save the proxy service.");
}
} else if (modelProperty.equals("templ.transformer.ps.transformresponses")) {
if (selectedTemplate.getId().equalsIgnoreCase(PsArtifactConstants.TRANSFORMER_PROXY_TEMPL_ID)) {
if ((Boolean)value && ((ProxyServiceModel)model).getResponseXSLT().equals("")) {
throw new FieldValidationException("Response XSLT key cannot be empty. Please specify a valid XSLT key.");
}
}
}
}
public boolean isEnableField(String modelProperty, ProjectDataModel model) {
boolean enableField = super.isEnableField(modelProperty, model);
if (modelProperty.equals("import.file")) {
enableField = true;
}
return enableField;
}
public List<String> getUpdateFields(String modelProperty, ProjectDataModel model) {
List<String> updateFields = super.getUpdateFields(modelProperty, model);
if (modelProperty.equals("import.file")) {
updateFields.add("available.ps");
} else if (modelProperty.equals("create.esb.prj")) {
updateFields.add("save.file");
} else if (modelProperty.equals("ps.type")) {
updateFields.add("proxy.AdvancedConfig");
}
return updateFields;
}
public boolean isVisibleField(String modelProperty, ProjectDataModel model) {
boolean visibleField = super.isVisibleField(modelProperty, model);
if (modelProperty.equals("available.ps")) {
List<OMElement> availableEPList = ((ProxyServiceModel) model).getAvailablePSList();
visibleField = (availableEPList != null && availableEPList.size() > 0);
}
return visibleField;
}
public boolean isReadOnlyField(String modelProperty, ProjectDataModel model) {
boolean readOnlyField = super.isReadOnlyField(modelProperty, model);
if (modelProperty.equals("save.file")) {
readOnlyField = true;
}
return readOnlyField;
}
}
| prabushi/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.artifact.proxyservice/src/org/wso2/developerstudio/eclipse/artifact/proxyservice/validators/ProxyServiceProjectFieldController.java | Java | apache-2.0 | 8,585 |
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xys.libzxing.zxing.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.google.zxing.Result;
import com.xys.libzxing.R;
import com.xys.libzxing.zxing.camera.CameraManager;
import com.xys.libzxing.zxing.decode.DecodeThread;
import com.xys.libzxing.zxing.utils.BeepManager;
import com.xys.libzxing.zxing.utils.CaptureActivityHandler;
import com.xys.libzxing.zxing.utils.InactivityTimer;
import java.io.IOException;
import java.lang.reflect.Field;
/**
* This activity opens the camera and does the actual scanning on a background
* thread. It draws a viewfinder to help the user place the barcode correctly,
* shows feedback as the image processing is happening, and then overlays the
* results when a scan is successful.
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/
public final class CaptureActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private static final String TAG = CaptureActivity.class.getSimpleName();
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private SurfaceView scanPreview = null;
private RelativeLayout scanContainer;
private RelativeLayout scanCropView;
private ImageView scanLine;
private Rect mCropRect = null;
private boolean isHasSurface = false;
public Handler getHandler() {
return handler;
}
public CameraManager getCameraManager() {
return cameraManager;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_capture);
scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
scanLine = (ImageView) findViewById(R.id.capture_scan_line);
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation
.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
0.9f);
animation.setDuration(4500);
animation.setRepeatCount(-1);
animation.setRepeatMode(Animation.RESTART);
scanLine.startAnimation(animation);
}
@Override
protected void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is
// necessary because we don't
// want to open the camera driver and measure the screen size if we're
// going to show the help on
// first launch. That led to bugs where the scanning rectangle was the
// wrong size and partially
// off screen.
cameraManager = new CameraManager(getApplication());
handler = null;
if (isHasSurface) {
// The activity was paused but not stopped, so the surface still
// exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(scanPreview.getHolder());
} else {
// Install the callback and wait for surfaceCreated() to init the
// camera.
scanPreview.getHolder().addCallback(this);
}
inactivityTimer.onResume();
}
@Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
beepManager.close();
cameraManager.closeDriver();
if (!isHasSurface) {
scanPreview.getHolder().removeCallback(this);
}
super.onPause();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!isHasSurface) {
isHasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
isHasSurface = false;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show
* the results.
*
* @param rawResult The contents of the barcode.
* @param bundle The extras
*/
public void handleDecode(Result rawResult, Bundle bundle) {
inactivityTimer.onActivity();
beepManager.playBeepSoundAndVibrate();
Intent resultIntent = new Intent();
bundle.putInt("width", mCropRect.width());
bundle.putInt("height", mCropRect.height());
bundle.putString("result", rawResult.getText());
resultIntent.putExtras(bundle);
this.setResult(RESULT_OK, resultIntent);
CaptureActivity.this.finish();
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a
// RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
}
initCrop();
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
// camera error
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.zxing_bar_name));
builder.setMessage("Camera error");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
}
public Rect getCropRect() {
return mCropRect;
}
/**
* 初始化截取的矩形区域
*/
private void initCrop() {
int cameraWidth = cameraManager.getCameraResolution().y;
int cameraHeight = cameraManager.getCameraResolution().x;
/** 获取布局中扫描框的位置信息 */
int[] location = new int[2];
scanCropView.getLocationInWindow(location);
int cropLeft = location[0];
int cropTop = location[1] - getStatusBarHeight();
int cropWidth = scanCropView.getWidth();
int cropHeight = scanCropView.getHeight();
/** 获取布局容器的宽高 */
int containerWidth = scanContainer.getWidth();
int containerHeight = scanContainer.getHeight();
/** 计算最终截取的矩形的左上角顶点x坐标 */
int x = cropLeft * cameraWidth / containerWidth;
/** 计算最终截取的矩形的左上角顶点y坐标 */
int y = cropTop * cameraHeight / containerHeight;
/** 计算最终截取的矩形的宽度 */
int width = cropWidth * cameraWidth / containerWidth;
/** 计算最终截取的矩形的高度 */
int height = cropHeight * cameraHeight / containerHeight;
/** 生成最终的截取的矩形 */
mCropRect = new Rect(x, y, width + x, height + y);
}
private int getStatusBarHeight() {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
return getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
} | WindFromFarEast/SmartButler | libzxing/src/main/java/com/xys/libzxing/zxing/activity/CaptureActivity.java | Java | apache-2.0 | 10,672 |
/**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao Licensed under the Apache License, Version 2.0 (the
* "License");
*/
package com.yang.spinach.common.utils.spring;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.sf.ehcache.Ehcache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.cache.support.SimpleValueWrapper;
/**
* 包装Spring cache抽象
*/
public class SpringCacheManagerWrapper implements CacheManager {
private org.springframework.cache.CacheManager cacheManager;
/**
* 设置spring cache manager
*
* @param cacheManager
*/
public void setCacheManager(
org.springframework.cache.CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
org.springframework.cache.Cache springCache = cacheManager
.getCache(name);
return new SpringCacheWrapper(springCache);
}
static class SpringCacheWrapper implements Cache {
private final org.springframework.cache.Cache springCache;
SpringCacheWrapper(org.springframework.cache.Cache springCache) {
this.springCache = springCache;
}
@Override
public Object get(Object key) throws CacheException {
Object value = springCache.get(key);
if (value instanceof SimpleValueWrapper) {
return ((SimpleValueWrapper) value).get();
}
return value;
}
@Override
public Object put(Object key, Object value) throws CacheException {
springCache.put(key, value);
return value;
}
@Override
public Object remove(Object key) throws CacheException {
springCache.evict(key);
return null;
}
@Override
public void clear() throws CacheException {
springCache.clear();
}
@Override
public int size() {
if (springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
return ehcache.getSize();
}
throw new UnsupportedOperationException(
"invoke spring cache abstract size method not supported");
}
@Override
public Set keys() {
if (springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
return new HashSet(ehcache.getKeys());
}
throw new UnsupportedOperationException(
"invoke spring cache abstract keys method not supported");
}
@Override
public Collection values() {
if (springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
System.out.println("cache savePath:"
+ ehcache.getCacheManager().getDiskStorePath()
+ "--------------");
List keys = ehcache.getKeys();
if (!CollectionUtils.isEmpty(keys)) {
List values = new ArrayList(keys.size());
for (Object key : keys) {
Object value = get(key);
if (value != null) {
values.add(value);
}
}
return Collections.unmodifiableList(values);
} else {
return Collections.emptyList();
}
}
throw new UnsupportedOperationException(
"invoke spring cache abstract values method not supported");
}
}
}
| yangb0/spinach | spinach/spinach-web/src/main/java/com/yang/spinach/common/utils/spring/SpringCacheManagerWrapper.java | Java | apache-2.0 | 3,363 |
package org.javacore.io.zip;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/*
* Copyright [2015] [Jeff Lee]
*
* 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.
*/
/**
* @author admin
* @since 2015-10-17 14:58:59
* 利用Zip进行多文件保存
*/
public class ZipCompress {
private static String filePath = "src" + File.separator +
"org" + File.separator +
"javacore" + File.separator +
"io" + File.separator;
private static String[] fileNames= new String[] {
filePath + "BufferedInputFileT.java",
filePath + "ChangeSystemOut.java"
};
public static void main(String[] args) throws IOException {
zipFiles(fileNames);
}
private static void zipFiles(String[] fileNames)
throws IOException {
// 获取zip文件输出流
FileOutputStream f = new FileOutputStream("test.zip");
// 从文件输出流中获取数据校验和输出流,并设置Adler32
CheckedOutputStream csum = new CheckedOutputStream(f,new Adler32());
// 从数据校验和输出流中获取Zip输出流
ZipOutputStream zos = new ZipOutputStream(csum);
// 从Zip输出流中获取缓冲输出流
BufferedOutputStream out = new BufferedOutputStream(zos);
// 设置Zip文件注释
zos.setComment("测试 java zip stream");
for (String file : fileNames) {
System.out.println("写入文件: " + file);
// 获取文件输入字符流
BufferedReader in =
new BufferedReader(new FileReader(file));
// 想Zip处理写入新的文件条目,并流定位到数据开始处
zos.putNextEntry(new ZipEntry(file));
int c;
while ((c = in.read()) > 0)
out.write(c);
in.close();
// 刷新Zip输出流,将缓冲的流写入该流
out.flush();
}
// 文件全部写入Zip输出流后,关闭
out.close();
// 输出数据校验和
System.out.println("数据校验和: " + csum.getChecksum().getValue());
System.out.println("读取zip文件");
// 读取test.zip文件输入流
FileInputStream fi = new FileInputStream("test.zip");
// 从文件输入流中获取数据校验和流
CheckedInputStream csumi = new CheckedInputStream(fi,new Adler32());
// 从数据校验和流中获取Zip解压流
ZipInputStream in2 = new ZipInputStream(csumi);
// 从Zip解压流中获取缓冲输入流
BufferedInputStream bis = new BufferedInputStream(in2);
// 创建文件条目
ZipEntry zipEntry;
while ((zipEntry = in2.getNextEntry()) != null) {
System.out.println("读取文件: " + zipEntry);
int x;
while ((x = bis.read()) > 0)
System.out.write(x);
}
if (fileNames.length == 1)
System.out.println("数据校验和: " + csumi.getChecksum().getValue());
bis.close();
// 获取Zip文件
ZipFile zf = new ZipFile("test.zip");
// 获取文件条目枚举
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
// 从Zip文件的枚举中获取文件条目
ZipEntry ze2 = (ZipEntry) e.nextElement();
System.out.println("文件: " + ze2);
}
}
}
| tzpBingo/java-example | src/main/java/org/javacore/io/zip/ZipCompress.java | Java | apache-2.0 | 4,471 |
/**
*
* Copyright 2014-2017 Florian Schmaus
*
* 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 eu.geekplace.javapinning.pin;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.logging.Level;
import java.util.logging.Logger;
import eu.geekplace.javapinning.util.HexUtilities;
public abstract class Pin {
private static final Logger LOGGER = Logger.getLogger(Sha256Pin.class.getName());
protected static final MessageDigest sha256md;
static {
MessageDigest sha256mdtemp = null;
try {
sha256mdtemp = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
LOGGER.log(Level.WARNING, "SHA-256 MessageDigest not available", e);
}
sha256md = sha256mdtemp;
}
protected final byte[] pinBytes;
protected Pin(byte[] pinBytes) {
this.pinBytes = pinBytes;
}
protected Pin(String pinHexString) {
pinBytes = HexUtilities.decodeFromHex(pinHexString);
}
public abstract boolean pinsCertificate(X509Certificate x509certificate) throws CertificateEncodingException;
protected abstract boolean pinsCertificate(byte[] pubkey);
/**
* Create a new {@link Pin} from the given String.
* <p>
* The Pin String must be in the format <tt>[type]:[hex-string]</tt>, where
* <tt>type</tt> denotes the type of the Pin and <tt>hex-string</tt> is the
* binary value of the Pin encoded in hex. Currently supported types are
* <ul>
* <li>PLAIN</li>
* <li>SHA256</li>
* <li>CERTPLAIN</li>
* <li>CERTSHA256</li>
* </ul>
* The hex-string must contain only of whitespace characters, colons (':'),
* numbers [0-9] and ASCII letters [a-fA-F]. It must be a valid hex-encoded
* binary representation. First the string is lower-cased, then all
* whitespace characters and colons are removed before the string is decoded
* to bytes.
* </p>
*
* @param string
* the Pin String.
* @return the Pin for the given Pin String.
* @throws IllegalArgumentException
* if the given String is not a valid Pin String
*/
public static Pin fromString(String string) {
// The Pin's string may have multiple colons (':'), assume that
// everything before the first colon is the Pin type and everything
// after the colon is the Pin's byte encoded in hex.
String[] pin = string.split(":", 2);
if (pin.length != 2) {
throw new IllegalArgumentException("Invalid pin string, expected: 'format-specifier:hex-string'.");
}
String type = pin[0];
String pinHex = pin[1];
switch (type) {
case "SHA256":
return new Sha256Pin(pinHex);
case "PLAIN":
return new PlainPin(pinHex);
case "CERTSHA256":
return new CertSha256Pin(pinHex);
case "CERTPLAIN":
return new CertPlainPin(pinHex);
default:
throw new IllegalArgumentException();
}
}
/**
* Returns a clone of the bytes that represent this Pin.
* <p>
* This method is meant for unit testing only and therefore not public.
* </p>
*
* @return a clone of the bytes that represent this Pin.
*/
byte[] getPinBytes() {
return pinBytes.clone();
}
}
| Flowdalic/java-pinning | java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/Pin.java | Java | apache-2.0 | 3,689 |
/*
* Copyright 2014 Richard Thurston.
*
* 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.northernwall.hadrian.handlers.service.dao;
import com.northernwall.hadrian.domain.Audit;
import java.util.LinkedList;
import java.util.List;
public class GetAuditData {
public List<Audit> audits = new LinkedList<>();
}
| Jukkorsis/Hadrian | src/main/java/com/northernwall/hadrian/handlers/service/dao/GetAuditData.java | Java | apache-2.0 | 840 |
/**
* Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.client.dsl.internal;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.api.model.ListOptions;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.http.HttpClient;
import io.fabric8.kubernetes.client.http.HttpRequest;
import io.fabric8.kubernetes.client.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WatchHTTPManager<T extends HasMetadata, L extends KubernetesResourceList<T>> extends AbstractWatchManager<T> {
private static final Logger logger = LoggerFactory.getLogger(WatchHTTPManager.class);
private CompletableFuture<HttpResponse<InputStream>> call;
public WatchHTTPManager(final HttpClient client,
final BaseOperation<T, L, ?> baseOperation,
final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval,
final int reconnectLimit)
throws MalformedURLException {
// Default max 32x slowdown from base interval
this(client, baseOperation, listOptions, watcher, reconnectInterval, reconnectLimit, 5);
}
public WatchHTTPManager(final HttpClient client,
final BaseOperation<T, L, ?> baseOperation,
final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval,
final int reconnectLimit, int maxIntervalExponent)
throws MalformedURLException {
super(
watcher, baseOperation, listOptions, reconnectLimit, reconnectInterval, maxIntervalExponent,
() -> client.newBuilder()
.readTimeout(0, TimeUnit.MILLISECONDS)
.forStreaming()
.build());
}
@Override
protected synchronized void run(URL url, Map<String, String> headers) {
HttpRequest.Builder builder = client.newHttpRequestBuilder().url(url);
headers.forEach(builder::header);
call = client.sendAsync(builder.build(), InputStream.class);
call.whenComplete((response, t) -> {
if (!call.isCancelled() && t != null) {
logger.info("Watch connection failed. reason: {}", t.getMessage());
}
if (response != null) {
try (InputStream body = response.body()){
if (!response.isSuccessful()) {
if (onStatus(OperationSupport.createStatus(response.code(), response.message()))) {
return; // terminal state
}
} else {
resetReconnectAttempts();
BufferedReader source = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8));
String message = null;
while ((message = source.readLine()) != null) {
onMessage(message);
}
}
} catch (Exception e) {
logger.info("Watch terminated unexpectedly. reason: {}", e.getMessage());
}
}
if (!call.isCancelled()) {
scheduleReconnect();
}
});
}
@Override
protected synchronized void closeRequest() {
if (call != null) {
call.cancel(true);
call = null;
}
}
}
| fabric8io/kubernetes-client | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java | Java | apache-2.0 | 4,143 |
package com.google.api.ads.adwords.jaxws.v201406.cm;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
*
* Service used to manage campaign feed links, and matching functions.
*
*
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.4-b01
* Generated source version: 2.1
*
*/
@WebService(name = "CampaignFeedServiceInterface", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
@XmlSeeAlso({
ObjectFactory.class
})
public interface CampaignFeedServiceInterface {
/**
*
* Returns a list of CampaignFeeds that meet the selector criteria.
*
* @param selector Determines which CampaignFeeds to return. If empty all
* Campaign feeds are returned.
* @return The list of CampaignFeeds.
* @throws ApiException Indicates a problem with the request.
*
*
* @param selector
* @return
* returns com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedPage
* @throws ApiException_Exception
*/
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
@RequestWrapper(localName = "get", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfaceget")
@ResponseWrapper(localName = "getResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacegetResponse")
public CampaignFeedPage get(
@WebParam(name = "selector", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
Selector selector)
throws ApiException_Exception
;
/**
*
* Adds, sets or removes CampaignFeeds.
*
* @param operations The operations to apply.
* @return The resulting Feeds.
* @throws ApiException Indicates a problem with the request.
*
*
* @param operations
* @return
* returns com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedReturnValue
* @throws ApiException_Exception
*/
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
@RequestWrapper(localName = "mutate", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacemutate")
@ResponseWrapper(localName = "mutateResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacemutateResponse")
public CampaignFeedReturnValue mutate(
@WebParam(name = "operations", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
List<CampaignFeedOperation> operations)
throws ApiException_Exception
;
/**
*
* Returns a list of {@link CampaignFeed}s inside a {@link CampaignFeedPage} that matches
* the query.
*
* @param query The SQL-like AWQL query string.
* @throws ApiException when there are one or more errors with the request.
*
*
* @param query
* @return
* returns com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedPage
* @throws ApiException_Exception
*/
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
@RequestWrapper(localName = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacequery")
@ResponseWrapper(localName = "queryResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacequeryResponse")
public CampaignFeedPage query(
@WebParam(name = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
String query)
throws ApiException_Exception
;
}
| nafae/developer | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/cm/CampaignFeedServiceInterface.java | Java | apache-2.0 | 4,521 |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.query.extraction;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.metamx.common.StringUtils;
import java.nio.ByteBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*/
public class MatchingDimExtractionFn extends DimExtractionFn
{
private final String expr;
private final Pattern pattern;
@JsonCreator
public MatchingDimExtractionFn(
@JsonProperty("expr") String expr
)
{
Preconditions.checkNotNull(expr, "expr must not be null");
this.expr = expr;
this.pattern = Pattern.compile(expr);
}
@Override
public byte[] getCacheKey()
{
byte[] exprBytes = StringUtils.toUtf8(expr);
return ByteBuffer.allocate(1 + exprBytes.length)
.put(ExtractionCacheHelper.CACHE_TYPE_ID_MATCHING_DIM)
.put(exprBytes)
.array();
}
@Override
public String apply(String dimValue)
{
Matcher matcher = pattern.matcher(Strings.nullToEmpty(dimValue));
return matcher.find() ? Strings.emptyToNull(dimValue) : null;
}
@JsonProperty("expr")
public String getExpr()
{
return expr;
}
@Override
public boolean preservesOrdering()
{
return false;
}
@Override
public ExtractionType getExtractionType()
{
return ExtractionType.MANY_TO_ONE;
}
@Override
public String toString()
{
return String.format("regex_matches(%s)", expr);
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MatchingDimExtractionFn that = (MatchingDimExtractionFn) o;
if (!expr.equals(that.expr)) {
return false;
}
return true;
}
@Override
public int hashCode()
{
return expr.hashCode();
}
}
| pdeva/druid | processing/src/main/java/io/druid/query/extraction/MatchingDimExtractionFn.java | Java | apache-2.0 | 2,777 |
/*
* Copyright 2009-2020 Aarhus University
*
* 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 dk.brics.tajs.analysis.dom.event;
import dk.brics.tajs.analysis.InitialStateBuilder;
import dk.brics.tajs.analysis.PropVarOperations;
import dk.brics.tajs.analysis.Solver;
import dk.brics.tajs.analysis.dom.DOMObjects;
import dk.brics.tajs.analysis.dom.DOMWindow;
import dk.brics.tajs.lattice.ObjectLabel;
import dk.brics.tajs.lattice.State;
import dk.brics.tajs.lattice.Value;
import static dk.brics.tajs.analysis.dom.DOMFunctions.createDOMProperty;
public class EventException {
public static ObjectLabel CONSTRUCTOR;
public static ObjectLabel PROTOTYPE;
public static ObjectLabel INSTANCES;
public static void build(Solver.SolverInterface c) {
State s = c.getState();
PropVarOperations pv = c.getAnalysis().getPropVarOperations();
CONSTRUCTOR = ObjectLabel.make(DOMObjects.EVENT_EXCEPTION_CONSTRUCTOR, ObjectLabel.Kind.FUNCTION);
PROTOTYPE = ObjectLabel.make(DOMObjects.EVENT_EXCEPTION_PROTOTYPE, ObjectLabel.Kind.OBJECT);
INSTANCES = ObjectLabel.make(DOMObjects.EVENT_EXCEPTION_INSTANCES, ObjectLabel.Kind.OBJECT);
// Constructor Object
s.newObject(CONSTRUCTOR);
pv.writePropertyWithAttributes(CONSTRUCTOR, "length", Value.makeNum(0).setAttributes(true, true, true));
pv.writePropertyWithAttributes(CONSTRUCTOR, "prototype", Value.makeObject(PROTOTYPE).setAttributes(true, true, true));
s.writeInternalPrototype(CONSTRUCTOR, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE));
pv.writeProperty(DOMWindow.WINDOW, "EventException", Value.makeObject(CONSTRUCTOR));
// Prototype object.
s.newObject(PROTOTYPE);
s.writeInternalPrototype(PROTOTYPE, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE));
// Multiplied object.
s.newObject(INSTANCES);
s.writeInternalPrototype(INSTANCES, Value.makeObject(PROTOTYPE));
/*
* Properties.
*/
createDOMProperty(INSTANCES, "code", Value.makeAnyNumUInt(), c);
s.multiplyObject(INSTANCES);
INSTANCES = INSTANCES.makeSingleton().makeSummary();
/*
* Constants.
*/
createDOMProperty(PROTOTYPE, "UNSPECIFIED_EVENT_TYPE_ERR", Value.makeNum(0), c);
/*
* Functions.
*/
}
}
| cs-au-dk/TAJS | src/dk/brics/tajs/analysis/dom/event/EventException.java | Java | apache-2.0 | 2,982 |
package com.svcet.cashportal.service;
import com.svcet.cashportal.web.beans.UserRequest;
import com.svcet.cashportal.web.beans.UserRolesScreenRequest;
import com.svcet.cashportal.web.beans.UserRolesScreenResponse;
public interface UserRoleService {
UserRolesScreenResponse editUserRoles(UserRequest userRequest);
void updateUserRoles(UserRolesScreenRequest userRolesScreenRequest);
}
| blessonkavala/cp | cashportal/src/main/java/com/svcet/cashportal/service/UserRoleService.java | Java | apache-2.0 | 391 |
package com.igoldin.qa.school.appmanager;
import com.igoldin.qa.school.model.ContactData;
import com.igoldin.qa.school.model.Contacts;
import com.igoldin.qa.school.model.GroupData;
import com.igoldin.qa.school.model.Groups;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import java.util.List;
public class DbHelper {
private final SessionFactory sessionFactory;
public DbHelper() {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
public Groups groups() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List<GroupData> result = session.createQuery("from GroupData" ).list();
session.getTransaction().commit();
session.close();
return new Groups(result);
}
public Contacts contacts() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List<ContactData> result = session.createQuery("from ContactData where deprecated = '0000-00-00 00:00:00'" ).list();
session.getTransaction().commit();
session.close();
return new Contacts(result);
}
}
| igoldin74/java_for_testers | addressbook_tests/src/test/java/com/igoldin/qa/school/appmanager/DbHelper.java | Java | apache-2.0 | 1,614 |
package org.netbeans.modules.manifestsupport.dataobject;
import org.openide.loaders.DataNode;
import org.openide.nodes.Children;
public class ManifestDataNode extends DataNode {
private static final String IMAGE_ICON_BASE = "SET/PATH/TO/ICON/HERE";
public ManifestDataNode(ManifestDataObject obj) {
super(obj, Children.LEAF);
// setIconBaseWithExtension(IMAGE_ICON_BASE);
}
// /** Creates a property sheet. */
// protected Sheet createSheet() {
// Sheet s = super.createSheet();
// Sheet.Set ss = s.get(Sheet.PROPERTIES);
// if (ss == null) {
// ss = Sheet.createPropertiesSet();
// s.put(ss);
// }
// // TODO add some relevant properties: ss.put(...)
// return s;
// }
}
| bernhardhuber/netbeansplugins | nb-manifest-support/zip/ManifestSupport/src/org/netbeans/modules/manifestsupport/dataobject/ManifestDataNode.java | Java | apache-2.0 | 805 |
/**
* Copyright [2009-2010] [dennis zhuang(killme2008@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
*/
/**
* Copyright [2009-2010] [dennis zhuang(killme2008@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 net.rubyeye.xmemcached.command.text;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import net.rubyeye.xmemcached.command.Command;
import net.rubyeye.xmemcached.command.CommandType;
import net.rubyeye.xmemcached.transcoders.CachedData;
/**
* Get command for text protocol
*
* @author dennis
*
*/
public class TextGetOneCommand extends TextGetCommand {
public TextGetOneCommand(String key, byte[] keyBytes, CommandType cmdType, CountDownLatch latch) {
super(key, keyBytes, cmdType, latch);
}
@Override
public void dispatch() {
if (this.mergeCount < 0) {
// single get
if (this.returnValues.get(this.getKey()) == null) {
if (!this.wasFirst) {
decodeError();
} else {
this.countDownLatch();
}
} else {
CachedData data = this.returnValues.get(this.getKey());
setResult(data);
this.countDownLatch();
}
} else {
// merge get
// Collection<Command> mergeCommands = mergeCommands.values();
getIoBuffer().free();
for (Command nextCommand : mergeCommands.values()) {
TextGetCommand textGetCommand = (TextGetCommand) nextCommand;
textGetCommand.countDownLatch();
if (textGetCommand.assocCommands != null) {
for (Command assocCommand : textGetCommand.assocCommands) {
assocCommand.countDownLatch();
}
}
}
}
}
}
| killme2008/xmemcached | src/main/java/net/rubyeye/xmemcached/command/text/TextGetOneCommand.java | Java | apache-2.0 | 2,662 |
package com.gbaldera.yts.fragments;
import android.content.Loader;
import com.gbaldera.yts.loaders.PopularMoviesLoader;
import com.jakewharton.trakt.entities.Movie;
import java.util.List;
public class PopularMoviesFragment extends BaseMovieFragment {
@Override
protected int getLoaderId() {
return BaseMovieFragment.POPULAR_MOVIES_LOADER_ID;
}
@Override
protected Loader<List<Movie>> getLoader() {
return new PopularMoviesLoader(getActivity());
}
}
| gbaldera/Yts | app/src/main/java/com/gbaldera/yts/fragments/PopularMoviesFragment.java | Java | apache-2.0 | 495 |
/*
* Copyright 2003-2019 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ig.javadoc;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.javadoc.PsiDocToken;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.MethodUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
final class MissingDeprecatedAnnotationInspection extends BaseInspection {
@SuppressWarnings("PublicField") public boolean warnOnMissingJavadoc = false;
@Override
@NotNull
protected String buildErrorString(Object... infos) {
final boolean annotationWarning = ((Boolean)infos[0]).booleanValue();
return annotationWarning
? InspectionGadgetsBundle.message("missing.deprecated.annotation.problem.descriptor")
: InspectionGadgetsBundle.message("missing.deprecated.tag.problem.descriptor");
}
@NotNull
@Override
public JComponent createOptionsPanel() {
return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message("missing.deprecated.tag.option"),
this, "warnOnMissingJavadoc");
}
@Override
public boolean runForWholeFile() {
return true;
}
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
final boolean annotationWarning = ((Boolean)infos[0]).booleanValue();
return annotationWarning ? new MissingDeprecatedAnnotationFix() : new MissingDeprecatedTagFix();
}
private static class MissingDeprecatedAnnotationFix extends InspectionGadgetsFix {
@Override
@NotNull
public String getFamilyName() {
return InspectionGadgetsBundle.message("missing.deprecated.annotation.add.quickfix");
}
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
final PsiElement identifier = descriptor.getPsiElement();
final PsiModifierListOwner parent = (PsiModifierListOwner)identifier.getParent();
if (parent == null) {
return;
}
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
final PsiAnnotation annotation = factory.createAnnotationFromText("@java.lang.Deprecated", parent);
final PsiModifierList modifierList = parent.getModifierList();
if (modifierList == null) {
return;
}
modifierList.addAfter(annotation, null);
}
}
private static class MissingDeprecatedTagFix extends InspectionGadgetsFix {
private static final String DEPRECATED_TAG_NAME = "deprecated";
@Nls(capitalization = Nls.Capitalization.Sentence)
@NotNull
@Override
public String getFamilyName() {
return InspectionGadgetsBundle.message("missing.add.deprecated.javadoc.tag.quickfix");
}
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
PsiElement parent = descriptor.getPsiElement().getParent();
if (!(parent instanceof PsiJavaDocumentedElement)) {
return;
}
PsiJavaDocumentedElement documentedElement = (PsiJavaDocumentedElement)parent;
PsiDocComment docComment = documentedElement.getDocComment();
if (docComment != null) {
PsiDocTag existingTag = docComment.findTagByName(DEPRECATED_TAG_NAME);
if (existingTag != null) {
moveCaretAfter(existingTag);
return;
}
PsiDocTag deprecatedTag = JavaPsiFacade.getElementFactory(project).createDocTagFromText("@" + DEPRECATED_TAG_NAME + " TODO: explain");
PsiElement addedTag = docComment.add(deprecatedTag);
moveCaretAfter(addedTag);
}
else {
PsiDocComment newDocComment = JavaPsiFacade.getElementFactory(project).createDocCommentFromText(
StringUtil.join("/**\n", " * ", "@" + DEPRECATED_TAG_NAME + " TODO: explain", "\n */")
);
PsiElement addedComment = documentedElement.addBefore(newDocComment, documentedElement.getFirstChild());
if (addedComment instanceof PsiDocComment) {
PsiDocTag addedTag = ((PsiDocComment)addedComment).findTagByName(DEPRECATED_TAG_NAME);
if (addedTag != null) {
moveCaretAfter(addedTag);
}
}
}
}
private static void moveCaretAfter(PsiElement newCaretPosition) {
PsiElement sibling = newCaretPosition.getNextSibling();
if (sibling instanceof Navigatable) {
((Navigatable)sibling).navigate(true);
}
}
}
@Override
public boolean shouldInspect(PsiFile file) {
return PsiUtil.isLanguageLevel5OrHigher(file);
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new MissingDeprecatedAnnotationVisitor();
}
private class MissingDeprecatedAnnotationVisitor extends BaseInspectionVisitor {
@Override
public void visitModule(@NotNull PsiJavaModule module) {
super.visitModule(module);
if (hasDeprecatedAnnotation(module)) {
if (warnOnMissingJavadoc && !hasDeprecatedComment(module, true)) {
registerModuleError(module, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(module, false)) {
registerModuleError(module, Boolean.TRUE);
}
}
@Override
public void visitClass(@NotNull PsiClass aClass) {
super.visitClass(aClass);
if (hasDeprecatedAnnotation(aClass)) {
if (warnOnMissingJavadoc && !hasDeprecatedComment(aClass, true)) {
registerClassError(aClass, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(aClass, false)) {
registerClassError(aClass, Boolean.TRUE);
}
}
@Override
public void visitMethod(@NotNull PsiMethod method) {
if (method.getNameIdentifier() == null) {
return;
}
if (hasDeprecatedAnnotation(method)) {
if (warnOnMissingJavadoc) {
PsiMethod m = method;
while (m != null) {
if (hasDeprecatedComment(m, true)) {
return;
}
m = MethodUtils.getSuper(m);
}
registerMethodError(method, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(method, false)) {
registerMethodError(method, Boolean.TRUE);
}
}
@Override
public void visitField(@NotNull PsiField field) {
if (hasDeprecatedAnnotation(field)) {
if (warnOnMissingJavadoc && !hasDeprecatedComment(field, true)) {
registerFieldError(field, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(field, false)) {
registerFieldError(field, Boolean.TRUE);
}
}
private boolean hasDeprecatedAnnotation(PsiModifierListOwner element) {
final PsiModifierList modifierList = element.getModifierList();
return modifierList != null && modifierList.hasAnnotation(CommonClassNames.JAVA_LANG_DEPRECATED);
}
private boolean hasDeprecatedComment(PsiJavaDocumentedElement documentedElement, boolean checkContent) {
final PsiDocComment comment = documentedElement.getDocComment();
if (comment == null) {
return false;
}
final PsiDocTag deprecatedTag = comment.findTagByName("deprecated");
if (deprecatedTag == null) {
return false;
}
if (!checkContent) {
return true;
}
for (PsiElement element : deprecatedTag.getDataElements()) {
if (element instanceof PsiDocTagValue ||
element instanceof PsiDocToken && ((PsiDocToken)element).getTokenType() == JavaDocTokenType.DOC_COMMENT_DATA) {
return true;
}
}
return false;
}
}
} | leafclick/intellij-community | plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/javadoc/MissingDeprecatedAnnotationInspection.java | Java | apache-2.0 | 8,667 |
package com.google.api.ads.adwords.jaxws.v201406.video;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import com.google.api.ads.adwords.jaxws.v201406.cm.Money;
/**
*
* Class representing the various summary budgets for a campaign page.
*
*
* <p>Java class for SummaryBudgets complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SummaryBudgets">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="totalVideoBudget" type="{https://adwords.google.com/api/adwords/video/v201406}VideoBudget" minOccurs="0"/>
* <element name="nonVideoBudget" type="{https://adwords.google.com/api/adwords/cm/v201406}Money" minOccurs="0"/>
* <element name="combinedBudget" type="{https://adwords.google.com/api/adwords/cm/v201406}Money" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SummaryBudgets", propOrder = {
"totalVideoBudget",
"nonVideoBudget",
"combinedBudget"
})
public class SummaryBudgets {
protected VideoBudget totalVideoBudget;
protected Money nonVideoBudget;
protected Money combinedBudget;
/**
* Gets the value of the totalVideoBudget property.
*
* @return
* possible object is
* {@link VideoBudget }
*
*/
public VideoBudget getTotalVideoBudget() {
return totalVideoBudget;
}
/**
* Sets the value of the totalVideoBudget property.
*
* @param value
* allowed object is
* {@link VideoBudget }
*
*/
public void setTotalVideoBudget(VideoBudget value) {
this.totalVideoBudget = value;
}
/**
* Gets the value of the nonVideoBudget property.
*
* @return
* possible object is
* {@link Money }
*
*/
public Money getNonVideoBudget() {
return nonVideoBudget;
}
/**
* Sets the value of the nonVideoBudget property.
*
* @param value
* allowed object is
* {@link Money }
*
*/
public void setNonVideoBudget(Money value) {
this.nonVideoBudget = value;
}
/**
* Gets the value of the combinedBudget property.
*
* @return
* possible object is
* {@link Money }
*
*/
public Money getCombinedBudget() {
return combinedBudget;
}
/**
* Sets the value of the combinedBudget property.
*
* @param value
* allowed object is
* {@link Money }
*
*/
public void setCombinedBudget(Money value) {
this.combinedBudget = value;
}
}
| nafae/developer | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/video/SummaryBudgets.java | Java | apache-2.0 | 3,027 |
package com.rodbate.httpserver.nioserver.old;
public interface WriterChannel {
}
| rodbate/httpserver | src/main/java/com/rodbate/httpserver/nioserver/old/WriterChannel.java | Java | apache-2.0 | 86 |
package com.glaf.base.modules.sys.model;
import java.io.Serializable;
import java.util.Date;
public class Dictory implements Serializable {
private static final long serialVersionUID = 2756737871937885934L;
private long id;
private long typeId;
private String code;
private String name;
private int sort;
private String desc;
private int blocked;
private String ext1;
private String ext2;
private String ext3;
private String ext4;
private Date ext5;
private Date ext6;
public int getBlocked() {
return blocked;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
public String getExt1() {
return ext1;
}
public String getExt2() {
return ext2;
}
public String getExt3() {
return ext3;
}
public String getExt4() {
return ext4;
}
public Date getExt5() {
return ext5;
}
public Date getExt6() {
return ext6;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public int getSort() {
return sort;
}
public long getTypeId() {
return typeId;
}
public void setBlocked(int blocked) {
this.blocked = blocked;
}
public void setCode(String code) {
this.code = code;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setExt1(String ext1) {
this.ext1 = ext1;
}
public void setExt2(String ext2) {
this.ext2 = ext2;
}
public void setExt3(String ext3) {
this.ext3 = ext3;
}
public void setExt4(String ext4) {
this.ext4 = ext4;
}
public void setExt5(Date ext5) {
this.ext5 = ext5;
}
public void setExt6(Date ext6) {
this.ext6 = ext6;
}
public void setId(long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSort(int sort) {
this.sort = sort;
}
public void setTypeId(long typeId) {
this.typeId = typeId;
}
}
| jior/glaf-gac | glaf-base/src/main/java/com/glaf/base/modules/sys/model/Dictory.java | Java | apache-2.0 | 1,856 |
package com.comps.util;
import com.google.gson.Gson;
public class GsonManager {
private static Gson instance;
public static Gson getInstance(){
if (instance == null){
instance = new Gson();
}
return instance;
}
}
| diogocs1/comps | mobile/src/com/comps/util/GsonManager.java | Java | apache-2.0 | 231 |
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.api.FormulaType.BooleanType;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.testing.EqualsTester;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverException;
@RunWith(Parameterized.class)
public class FormulaManagerTest extends SolverBasedTest0 {
@Parameters(name = "{0}")
public static Object[] getAllSolvers() {
return Solvers.values();
}
@Parameter(0)
public Solvers solver;
@Override
protected Solvers solverToUse() {
return solver;
}
@Test
public void testEmptySubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
assume().withMessage("Princess fails").that(solver).isNotEqualTo(Solvers.PRINCESS);
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula input = bmgr.xor(f1, f2);
BooleanFormula out = mgr.substitute(input, ImmutableMap.of());
assertThatFormula(out).isEquivalentTo(input);
}
@Test
public void testNoSubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
assume().withMessage("Princess fails").that(solver).isNotEqualTo(Solvers.PRINCESS);
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula input = bmgr.xor(f1, f2);
Map<BooleanFormula, BooleanFormula> substitution =
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e"));
BooleanFormula out = mgr.substitute(input, substitution);
assertThatFormula(out).isEquivalentTo(input);
}
@Test
public void testSubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula input =
bmgr.or(
bmgr.and(bmgr.makeVariable("a"), bmgr.makeVariable("b")),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")));
BooleanFormula out =
mgr.substitute(
input,
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e")));
assertThatFormula(out)
.isEquivalentTo(
bmgr.or(
bmgr.and(bmgr.makeVariable("a1"), bmgr.makeVariable("b1")),
bmgr.makeVariable("e")));
}
@Test
public void testSubstitutionTwice() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula input =
bmgr.or(
bmgr.and(bmgr.makeVariable("a"), bmgr.makeVariable("b")),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")));
ImmutableMap<BooleanFormula, BooleanFormula> substitution =
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e"));
BooleanFormula out = mgr.substitute(input, substitution);
assertThatFormula(out)
.isEquivalentTo(
bmgr.or(
bmgr.and(bmgr.makeVariable("a1"), bmgr.makeVariable("b1")),
bmgr.makeVariable("e")));
BooleanFormula out2 = mgr.substitute(out, substitution);
assertThatFormula(out2).isEquivalentTo(out);
}
@Test
public void formulaEqualsAndHashCode() {
// Solvers without integers (Boolector) get their own test below
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
FunctionDeclaration<IntegerFormula> fb = fmgr.declareUF("f_b", IntegerType, IntegerType);
new EqualsTester()
.addEqualityGroup(bmgr.makeBoolean(true))
.addEqualityGroup(bmgr.makeBoolean(false))
.addEqualityGroup(bmgr.makeVariable("bool_a"))
.addEqualityGroup(imgr.makeVariable("int_a"))
// Way of creating numbers should not make a difference.
.addEqualityGroup(
imgr.makeNumber(0.0),
imgr.makeNumber(0L),
imgr.makeNumber(BigInteger.ZERO),
imgr.makeNumber(BigDecimal.ZERO),
imgr.makeNumber("0"))
.addEqualityGroup(
imgr.makeNumber(1.0),
imgr.makeNumber(1L),
imgr.makeNumber(BigInteger.ONE),
imgr.makeNumber(BigDecimal.ONE),
imgr.makeNumber("1"))
// The same formula when created twice should compare equal.
.addEqualityGroup(bmgr.makeVariable("bool_b"), bmgr.makeVariable("bool_b"))
.addEqualityGroup(
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")),
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")))
.addEqualityGroup(
imgr.equal(imgr.makeNumber(0), imgr.makeVariable("int_a")),
imgr.equal(imgr.makeNumber(0), imgr.makeVariable("int_a")))
// UninterpretedFunctionDeclarations should not compare equal to Formulas,
// but declaring one twice needs to return the same UIF.
.addEqualityGroup(
fmgr.declareUF("f_a", IntegerType, IntegerType),
fmgr.declareUF("f_a", IntegerType, IntegerType))
.addEqualityGroup(fb)
.addEqualityGroup(fmgr.callUF(fb, imgr.makeNumber(0)))
.addEqualityGroup(fmgr.callUF(fb, imgr.makeNumber(1)), fmgr.callUF(fb, imgr.makeNumber(1)))
.testEquals();
}
@Test
public void bitvectorFormulaEqualsAndHashCode() {
// Boolector does not support integers and it is easier to make a new test with bvs
requireBitvectors();
FunctionDeclaration<BitvectorFormula> fb =
fmgr.declareUF(
"f_bv",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8));
new EqualsTester()
.addEqualityGroup(bmgr.makeBoolean(true))
.addEqualityGroup(bmgr.makeBoolean(false))
.addEqualityGroup(bmgr.makeVariable("bool_a"))
.addEqualityGroup(bvmgr.makeVariable(8, "bv_a"))
// Way of creating numbers should not make a difference.
.addEqualityGroup(
bvmgr.makeBitvector(8, 0L),
bvmgr.makeBitvector(8, 0),
bvmgr.makeBitvector(8, BigInteger.ZERO))
.addEqualityGroup(
bvmgr.makeBitvector(8, 1L),
bvmgr.makeBitvector(8, 1),
bvmgr.makeBitvector(8, BigInteger.ONE))
// The same formula when created twice should compare equal.
.addEqualityGroup(bmgr.makeVariable("bool_b"), bmgr.makeVariable("bool_b"))
.addEqualityGroup(
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")),
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")))
.addEqualityGroup(
bvmgr.equal(bvmgr.makeBitvector(8, 0), bvmgr.makeVariable(8, "int_a")),
bvmgr.equal(bvmgr.makeBitvector(8, 0), bvmgr.makeVariable(8, "int_a")))
// UninterpretedFunctionDeclarations should not compare equal to Formulas,
// but declaring one twice needs to return the same UIF.
.addEqualityGroup(
fmgr.declareUF(
"f_a",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8)),
fmgr.declareUF(
"f_a",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8)))
.addEqualityGroup(fb)
.addEqualityGroup(fmgr.callUF(fb, bvmgr.makeBitvector(8, 0)))
.addEqualityGroup(
fmgr.callUF(fb, bvmgr.makeBitvector(8, 1)), // why not equal?!
fmgr.callUF(fb, bvmgr.makeBitvector(8, 1)))
.testEquals();
}
@Test
public void variableNameExtractorTest() {
// Since Boolector does not support integers we use bitvectors
if (imgr != null) {
BooleanFormula constr =
bmgr.or(
imgr.equal(
imgr.subtract(
imgr.add(imgr.makeVariable("x"), imgr.makeVariable("z")),
imgr.makeNumber(10)),
imgr.makeVariable("y")),
imgr.equal(imgr.makeVariable("xx"), imgr.makeVariable("zz")));
assertThat(mgr.extractVariables(constr).keySet()).containsExactly("x", "y", "z", "xx", "zz");
assertThat(mgr.extractVariablesAndUFs(constr)).isEqualTo(mgr.extractVariables(constr));
} else {
BooleanFormula bvConstr =
bmgr.or(
bvmgr.equal(
bvmgr.subtract(
bvmgr.add(bvmgr.makeVariable(8, "x"), bvmgr.makeVariable(8, "z")),
bvmgr.makeBitvector(8, 10)),
bvmgr.makeVariable(8, "y")),
bvmgr.equal(bvmgr.makeVariable(8, "xx"), bvmgr.makeVariable(8, "zz")));
requireVisitor();
assertThat(mgr.extractVariables(bvConstr).keySet())
.containsExactly("x", "y", "z", "xx", "zz");
assertThat(mgr.extractVariablesAndUFs(bvConstr)).isEqualTo(mgr.extractVariables(bvConstr));
}
}
@Test
public void ufNameExtractorTest() {
// Since Boolector does not support integers we use bitvectors for constraints
if (imgr != null) {
BooleanFormula constraint =
imgr.equal(
fmgr.declareAndCallUF("uf1", IntegerType, ImmutableList.of(imgr.makeVariable("x"))),
fmgr.declareAndCallUF("uf2", IntegerType, ImmutableList.of(imgr.makeVariable("y"))));
assertThat(mgr.extractVariablesAndUFs(constraint).keySet())
.containsExactly("uf1", "uf2", "x", "y");
assertThat(mgr.extractVariables(constraint).keySet()).containsExactly("x", "y");
} else {
BooleanFormula bvConstraint =
bvmgr.equal(
fmgr.declareAndCallUF(
"uf1",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "x"))),
fmgr.declareAndCallUF(
"uf2",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "y"))));
requireVisitor();
assertThat(mgr.extractVariablesAndUFs(bvConstraint).keySet())
.containsExactly("uf1", "uf2", "x", "y");
assertThat(mgr.extractVariables(bvConstraint).keySet()).containsExactly("x", "y");
}
}
@Test
public void simplifyIntTest() throws SolverException, InterruptedException {
requireIntegers();
// x=1 && y=x+2 && z=y+3 --> simplified: x=1 && y=3 && z=6
IntegerFormula num1 = imgr.makeNumber(1);
IntegerFormula num2 = imgr.makeNumber(2);
IntegerFormula num3 = imgr.makeNumber(3);
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
BooleanFormula f =
bmgr.and(
imgr.equal(x, num1),
imgr.equal(y, imgr.add(x, num2)),
imgr.equal(z, imgr.add(y, num3)));
assertThatFormula(mgr.simplify(f)).isEquisatisfiableTo(f);
}
@Test
public void simplifyArrayTest() throws SolverException, InterruptedException {
requireIntegers();
requireArrays();
// exists arr : (arr[0]=5 && x=arr[0]) --> simplified: x=5
ArrayFormula<IntegerFormula, IntegerFormula> arr =
amgr.makeArray("arr", new ArrayFormulaType<>(IntegerType, IntegerType));
IntegerFormula index = imgr.makeNumber(0);
IntegerFormula value = imgr.makeNumber(5);
IntegerFormula x = imgr.makeVariable("x");
ArrayFormula<IntegerFormula, IntegerFormula> write = amgr.store(arr, index, value);
IntegerFormula read = amgr.select(write, index);
BooleanFormula f = imgr.equal(x, read);
assertThatFormula(mgr.simplify(f)).isEquisatisfiableTo(f);
}
}
| sosy-lab/java-smt | src/org/sosy_lab/java_smt/test/FormulaManagerTest.java | Java | apache-2.0 | 14,364 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.17 at 02:39:44 오후 KST
//
package com.athena.chameleon.engine.entity.xml.application.jeus.v5_0;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
/**
* <p>Java class for vendorType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="vendorType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="oracle"/>
* <enumeration value="sybase"/>
* <enumeration value="mssql"/>
* <enumeration value="db2"/>
* <enumeration value="tibero"/>
* <enumeration value="informix"/>
* <enumeration value="mysql"/>
* <enumeration value="others"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlEnum
public enum VendorType {
@XmlEnumValue("db2")
DB_2("db2"),
@XmlEnumValue("informix")
INFORMIX("informix"),
@XmlEnumValue("mssql")
MSSQL("mssql"),
@XmlEnumValue("mysql")
MYSQL("mysql"),
@XmlEnumValue("oracle")
ORACLE("oracle"),
@XmlEnumValue("others")
OTHERS("others"),
@XmlEnumValue("sybase")
SYBASE("sybase"),
@XmlEnumValue("tibero")
TIBERO("tibero");
private final String value;
VendorType(String v) {
value = v;
}
public String value() {
return value;
}
public static VendorType fromValue(String v) {
for (VendorType c: VendorType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v.toString());
}
}
| OpenSourceConsulting/athena-chameleon | src/main/java/com/athena/chameleon/engine/entity/xml/application/jeus/v5_0/VendorType.java | Java | apache-2.0 | 1,969 |
package it.unibz.inf.ontop.renderer;
/*
* #%L
* ontop-obdalib-core
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* 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.
* #L%
*/
import it.unibz.inf.ontop.io.PrefixManager;
import it.unibz.inf.ontop.io.SimplePrefixManager;
import it.unibz.inf.ontop.model.Constant;
import it.unibz.inf.ontop.model.DatatypeFactory;
import it.unibz.inf.ontop.model.ExpressionOperation;
import it.unibz.inf.ontop.model.Function;
import it.unibz.inf.ontop.model.Predicate;
import it.unibz.inf.ontop.model.Term;
import it.unibz.inf.ontop.model.URIConstant;
import it.unibz.inf.ontop.model.URITemplatePredicate;
import it.unibz.inf.ontop.model.ValueConstant;
import it.unibz.inf.ontop.model.Variable;
import it.unibz.inf.ontop.model.impl.OBDADataFactoryImpl;
import it.unibz.inf.ontop.model.impl.OBDAVocabulary;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* A utility class to render a Target Query object into its representational
* string.
*/
public class TargetQueryRenderer {
private static final DatatypeFactory dtfac = OBDADataFactoryImpl.getInstance().getDatatypeFactory();
/**
* Transforms the given <code>OBDAQuery</code> into a string. The method requires
* a prefix manager to shorten full IRI name.
*/
public static String encode(List<Function> input, PrefixManager prefixManager) {
TurtleWriter turtleWriter = new TurtleWriter();
List<Function> body = input;
for (Function atom : body) {
String subject, predicate, object = "";
String originalString = atom.getFunctionSymbol().toString();
if (isUnary(atom)) {
Term subjectTerm = atom.getTerm(0);
subject = getDisplayName(subjectTerm, prefixManager);
predicate = "a";
object = getAbbreviatedName(originalString, prefixManager, false);
if (originalString.equals(object)) {
object = "<" + object + ">";
}
}
else if (originalString.equals("triple")) {
Term subjectTerm = atom.getTerm(0);
subject = getDisplayName(subjectTerm, prefixManager);
Term predicateTerm = atom.getTerm(1);
predicate = getDisplayName(predicateTerm, prefixManager);
Term objectTerm = atom.getTerm(2);
object = getDisplayName(objectTerm, prefixManager);
}
else {
Term subjectTerm = atom.getTerm(0);
subject = getDisplayName(subjectTerm, prefixManager);
predicate = getAbbreviatedName(originalString, prefixManager, false);
if (originalString.equals(predicate)) {
predicate = "<" + predicate + ">";
}
Term objectTerm = atom.getTerm(1);
object = getDisplayName(objectTerm, prefixManager);
}
turtleWriter.put(subject, predicate, object);
}
return turtleWriter.print();
}
/**
* Checks if the atom is unary or not.
*/
private static boolean isUnary(Function atom) {
return atom.getArity() == 1 ? true : false;
}
/**
* Prints the short form of the predicate (by omitting the complete URI and
* replacing it by a prefix name).
*
* Note that by default this method will consider a set of predefined
* prefixes, i.e., rdf:, rdfs:, owl:, xsd: and quest: To support this
* prefixes the method will temporally add the prefixes if they dont exist
* already, taken care to remove them if they didn't exist.
*
* The implementation requires at the moment, the implementation requires
* cloning the existing prefix manager, and hence this is highly inefficient
* method. *
*/
private static String getAbbreviatedName(String uri, PrefixManager pm, boolean insideQuotes) {
// Cloning the existing manager
PrefixManager prefManClone = new SimplePrefixManager();
Map<String,String> currentMap = pm.getPrefixMap();
for (String prefix: currentMap.keySet()) {
prefManClone.addPrefix(prefix, pm.getURIDefinition(prefix));
}
return prefManClone.getShortForm(uri, insideQuotes);
}
private static String appendTerms(Term term){
if (term instanceof Constant){
String st = ((Constant) term).getValue();
if (st.contains("{")){
st = st.replace("{", "\\{");
st = st.replace("}", "\\}");
}
return st;
}else{
return "{"+((Variable) term).getName()+"}";
}
}
//Appends nested concats
public static void getNestedConcats(StringBuilder stb, Term term1, Term term2){
if (term1 instanceof Function){
Function f = (Function) term1;
getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1));
}else{
stb.append(appendTerms(term1));
}
if (term2 instanceof Function){
Function f = (Function) term2;
getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1));
}else{
stb.append(appendTerms(term2));
}
}
/**
* Prints the text representation of different terms.
*/
private static String getDisplayName(Term term, PrefixManager prefixManager) {
StringBuilder sb = new StringBuilder();
if (term instanceof Function) {
Function function = (Function) term;
Predicate functionSymbol = function.getFunctionSymbol();
String fname = getAbbreviatedName(functionSymbol.toString(), prefixManager, false);
if (function.isDataTypeFunction()) {
// if the function symbol is a data type predicate
if (dtfac.isLiteral(functionSymbol)) {
// if it is rdfs:Literal
int arity = function.getArity();
if (arity == 1) {
// without the language tag
Term var = function.getTerms().get(0);
sb.append(getDisplayName(var, prefixManager));
sb.append("^^rdfs:Literal");
} else if (arity == 2) {
// with the language tag
Term var = function.getTerms().get(0);
Term lang = function.getTerms().get(1);
sb.append(getDisplayName(var, prefixManager));
sb.append("@");
if (lang instanceof ValueConstant) {
// Don't pass this to getDisplayName() because
// language constant is not written as @"lang-tag"
sb.append(((ValueConstant) lang).getValue());
} else {
sb.append(getDisplayName(lang, prefixManager));
}
}
} else { // for the other data types
Term var = function.getTerms().get(0);
sb.append(getDisplayName(var, prefixManager));
sb.append("^^");
sb.append(fname);
}
} else if (functionSymbol instanceof URITemplatePredicate) {
Term firstTerm = function.getTerms().get(0);
if(firstTerm instanceof Variable)
{
sb.append("<{");
sb.append(((Variable) firstTerm).getName());
sb.append("}>");
}
else {
String template = ((ValueConstant) firstTerm).getValue();
// Utilize the String.format() method so we replaced placeholders '{}' with '%s'
String templateFormat = template.replace("{}", "%s");
List<String> varNames = new ArrayList<String>();
for (Term innerTerm : function.getTerms()) {
if (innerTerm instanceof Variable) {
varNames.add(getDisplayName(innerTerm, prefixManager));
}
}
String originalUri = String.format(templateFormat, varNames.toArray());
if (originalUri.equals(OBDAVocabulary.RDF_TYPE)) {
sb.append("a");
} else {
String shortenUri = getAbbreviatedName(originalUri, prefixManager, false); // shorten the URI if possible
if (!shortenUri.equals(originalUri)) {
sb.append(shortenUri);
} else {
// If the URI can't be shorten then use the full URI within brackets
sb.append("<");
sb.append(originalUri);
sb.append(">");
}
}
}
}
else if (functionSymbol == ExpressionOperation.CONCAT) { //Concat
List<Term> terms = function.getTerms();
sb.append("\"");
getNestedConcats(sb, terms.get(0),terms.get(1));
sb.append("\"");
//sb.append("^^rdfs:Literal");
}
else { // for any ordinary function symbol
sb.append(fname);
sb.append("(");
boolean separator = false;
for (Term innerTerm : function.getTerms()) {
if (separator) {
sb.append(", ");
}
sb.append(getDisplayName(innerTerm, prefixManager));
separator = true;
}
sb.append(")");
}
} else if (term instanceof Variable) {
sb.append("{");
sb.append(((Variable) term).getName());
sb.append("}");
} else if (term instanceof URIConstant) {
String originalUri = term.toString();
String shortenUri = getAbbreviatedName(originalUri, prefixManager, false); // shorten the URI if possible
if (!shortenUri.equals(originalUri)) {
sb.append(shortenUri);
} else {
// If the URI can't be shorten then use the full URI within brackets
sb.append("<");
sb.append(originalUri);
sb.append(">");
}
} else if (term instanceof ValueConstant) {
sb.append("\"");
sb.append(((ValueConstant) term).getValue());
sb.append("\"");
}
return sb.toString();
}
private TargetQueryRenderer() {
// Prevent initialization
}
}
| srapisarda/ontop | obdalib-core/src/main/java/it/unibz/inf/ontop/renderer/TargetQueryRenderer.java | Java | apache-2.0 | 9,391 |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.parsers;
import com.spectralogic.ds3client.commands.parsers.interfaces.AbstractResponseParser;
import com.spectralogic.ds3client.commands.parsers.utils.ResponseParserUtils;
import com.spectralogic.ds3client.commands.spectrads3.ModifyUserSpectraS3Response;
import com.spectralogic.ds3client.models.SpectraUser;
import com.spectralogic.ds3client.networking.WebResponse;
import com.spectralogic.ds3client.serializer.XmlOutput;
import java.io.IOException;
import java.io.InputStream;
public class ModifyUserSpectraS3ResponseParser extends AbstractResponseParser<ModifyUserSpectraS3Response> {
private final int[] expectedStatusCodes = new int[]{200};
@Override
public ModifyUserSpectraS3Response parseXmlResponse(final WebResponse response) throws IOException {
final int statusCode = response.getStatusCode();
if (ResponseParserUtils.validateStatusCode(statusCode, expectedStatusCodes)) {
switch (statusCode) {
case 200:
try (final InputStream inputStream = response.getResponseStream()) {
final SpectraUser result = XmlOutput.fromXml(inputStream, SpectraUser.class);
return new ModifyUserSpectraS3Response(result, this.getChecksum(), this.getChecksumType());
}
default:
assert false: "validateStatusCode should have made it impossible to reach this line";
}
}
throw ResponseParserUtils.createFailedRequest(response, expectedStatusCodes);
}
} | DenverM80/ds3_java_sdk | ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/parsers/ModifyUserSpectraS3ResponseParser.java | Java | apache-2.0 | 2,377 |
package com.github.particlesystem.modifiers;
import com.github.particlesystem.Particle;
public interface ParticleModifier {
/**
* modifies the specific value of a particle given the current miliseconds
*
* @param particle
* @param miliseconds
*/
void apply(Particle particle, long miliseconds);
}
| rohitiskul/ParticleSystem | particlesystem/src/main/java/com/github/particlesystem/modifiers/ParticleModifier.java | Java | apache-2.0 | 335 |
package com.ftfl.icare;
import java.util.List;
import com.ftfl.icare.adapter.CustomAppointmentAdapter;
import com.ftfl.icare.adapter.CustomDoctorAdapter;
import com.ftfl.icare.helper.AppointmentDataSource;
import com.ftfl.icare.helper.DoctorProfileDataSource;
import com.ftfl.icare.model.Appointment;
import com.ftfl.icare.model.DoctorProfile;
import com.ftfl.icare.util.FragmentHome;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentAppointmentList extends Fragment {
TextView mId_tv = null;
AppointmentDataSource mAppointmentDataSource;
Appointment mAppointment;
FragmentManager mFrgManager;
Fragment mFragment;
Context mContext;
ListView mLvProfileList;
List<Appointment> mDoctorProfileList;
String mId;
Bundle mArgs = new Bundle();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_doctor_list, container,
false);
mContext = container.getContext();
mAppointmentDataSource = new AppointmentDataSource(getActivity());
mDoctorProfileList = mAppointmentDataSource.appointmentList();
CustomAppointmentAdapter arrayAdapter = new CustomAppointmentAdapter(
getActivity(), mDoctorProfileList);
mLvProfileList = (ListView) view.findViewById(R.id.lvDoctorList);
mLvProfileList.setAdapter(arrayAdapter);
mLvProfileList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final int pos = position;
new AlertDialog.Builder(mContext)
.setTitle("Delete entry")
.setMessage(
"Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
mAppointmentDataSource = new AppointmentDataSource(
getActivity());
if (mAppointmentDataSource.deleteData(Integer
.parseInt(mDoctorProfileList
.get(pos)
.getId())) == true) {
Toast toast = Toast
.makeText(
getActivity(),
"Successfully Deleted.",
Toast.LENGTH_LONG);
toast.show();
mFragment = new FragmentHome();
mFrgManager = getFragmentManager();
mFrgManager
.beginTransaction()
.replace(
R.id.content_frame,
mFragment)
.commit();
setTitle("Home");
} else {
Toast toast = Toast
.makeText(
getActivity(),
"Error, Couldn't inserted data to database",
Toast.LENGTH_LONG);
toast.show();
}
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
return view;
}
public void setTitle(CharSequence title) {
getActivity().getActionBar().setTitle(title);
}
} | FTFL02-ANDROID/julkarnine | ICare/src/com/ftfl/icare/FragmentAppointmentList.java | Java | apache-2.0 | 3,803 |
package com.ymsino.water.service.manager.manager;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI. JAX-WS RI 2.1.3-hudson-390- Generated source version: 2.0
*
*/
@WebService(name = "ManagerService", targetNamespace = "http://api.service.manager.esb.ymsino.com/")
public interface ManagerService {
/**
* 登录(密码为明文密码,只有状态为开通的管理员才能登录)
*
* @param mangerId
* @param password
* @return returns com.ymsino.water.service.manager.manager.ManagerReturn
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "login", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Login")
@ResponseWrapper(localName = "loginResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.LoginResponse")
public ManagerReturn login(@WebParam(name = "mangerId", targetNamespace = "") String mangerId, @WebParam(name = "password", targetNamespace = "") String password);
/**
* 保存管理员
*
* @param managerSaveParam
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "save", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Save")
@ResponseWrapper(localName = "saveResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.SaveResponse")
public Boolean save(@WebParam(name = "managerSaveParam", targetNamespace = "") ManagerSaveParam managerSaveParam);
/**
* 根据查询参数获取管理员分页列表
*
* @param queryParam
* @param startRow
* @param pageSize
* @return returns java.util.List<com.ymsino.water.service.manager.manager.ManagerReturn>
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getListpager", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetListpager")
@ResponseWrapper(localName = "getListpagerResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetListpagerResponse")
public List<ManagerReturn> getListpager(@WebParam(name = "queryParam", targetNamespace = "") QueryParam queryParam, @WebParam(name = "startRow", targetNamespace = "") Integer startRow, @WebParam(name = "pageSize", targetNamespace = "") Integer pageSize);
/**
* 停用帐号(审核不通过)
*
* @param mangerId
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "closeStatus", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.CloseStatus")
@ResponseWrapper(localName = "closeStatusResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.CloseStatusResponse")
public Boolean closeStatus(@WebParam(name = "mangerId", targetNamespace = "") String mangerId);
/**
* 修改管理员
*
* @param managerModifyParam
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "modify", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Modify")
@ResponseWrapper(localName = "modifyResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.ModifyResponse")
public Boolean modify(@WebParam(name = "managerModifyParam", targetNamespace = "") ManagerModifyParam managerModifyParam);
/**
* 根据查询参数获取管理员记录数
*
* @param queryParam
* @return returns java.lang.Integer
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getCount", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetCount")
@ResponseWrapper(localName = "getCountResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetCountResponse")
public Integer getCount(@WebParam(name = "queryParam", targetNamespace = "") QueryParam queryParam);
/**
* 启用帐号(审核通过)
*
* @param managerId
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "openStatus", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.OpenStatus")
@ResponseWrapper(localName = "openStatusResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.OpenStatusResponse")
public Boolean openStatus(@WebParam(name = "managerId", targetNamespace = "") String managerId);
/**
* 根据管理员id获取管理员实体
*
* @param mangerId
* @return returns com.ymsino.water.service.manager.manager.ManagerReturn
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getByManagerId", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetByManagerId")
@ResponseWrapper(localName = "getByManagerIdResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetByManagerIdResponse")
public ManagerReturn getByManagerId(@WebParam(name = "mangerId", targetNamespace = "") String mangerId);
}
| xcjava/ymWaterWeb | manager_ws_client/com/ymsino/water/service/manager/manager/ManagerService.java | Java | apache-2.0 | 6,070 |
package app.yweather.com.yweather.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* 解析JSON工具类
*/
public class Utility {
//解析服务器返回的JSON数据,并将解析出的数据存储到本地。
public static void handleWeatherResponse(Context context, String response){
try{
JSONArray jsonObjs = new JSONObject(response).getJSONArray("results");
JSONObject locationJsonObj = ((JSONObject)jsonObjs.opt(0)).getJSONObject("location");
String id = locationJsonObj.getString("id");
String name = locationJsonObj.getString("name");
JSONObject nowJsonObj = ((JSONObject)jsonObjs.opt(0)).getJSONObject("now");
String text = nowJsonObj.getString("text");
String temperature = nowJsonObj.getString("temperature");
String wind = nowJsonObj.getString("wind_direction");
String lastUpdateTime = ((JSONObject) jsonObjs.opt(0)).getString("last_update");
lastUpdateTime = lastUpdateTime.substring(lastUpdateTime.indexOf("+") + 1,lastUpdateTime.length());
LogUtil.e("Utility", "name:" + name + ",text:"+ text + "wind:" + wind + ",lastUpdateTime:" + lastUpdateTime);
saveWeatherInfo(context,name,id,temperature,text,lastUpdateTime);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 将服务器返回的天气信息存储到SharedPreferences文件中
* context : Context对象
* cityName : 城市名称
* cityId : 城市id
* temperature: 温度
* text :天气现象文字说明,如多云
* lastUpdateTime : 数据更新时间
* 2016-07-16T13:10:00+08:00
*/
@TargetApi(Build.VERSION_CODES.N) //指定使用的系统版本
public static void saveWeatherInfo(Context context, String cityName, String cityId, String temperature,
String text, String lastUpdateTime){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CANADA);
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean("city_selected",true);
editor.putString("city_name",cityName);
editor.putString("city_id",cityId);
editor.putString("temperature",temperature);
editor.putString("text",text);
editor.putString("last_update_time",lastUpdateTime);
editor.putString("current_date",sdf.format(new Date()));
editor.commit();
}
}
| llxyhuang/YWeather | app/src/main/java/app/yweather/com/yweather/util/Utility.java | Java | apache-2.0 | 2,845 |
/*
* Copyright (C) 2017 grandcentrix GmbH
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.grandcentrix.thirtyinch;
import android.content.res.Configuration;
import android.os.Bundle;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import java.util.concurrent.Executor;
import net.grandcentrix.thirtyinch.internal.DelegatedTiActivity;
import net.grandcentrix.thirtyinch.internal.InterceptableViewBinder;
import net.grandcentrix.thirtyinch.internal.PresenterAccessor;
import net.grandcentrix.thirtyinch.internal.PresenterSavior;
import net.grandcentrix.thirtyinch.internal.TiActivityDelegate;
import net.grandcentrix.thirtyinch.internal.TiLoggingTagProvider;
import net.grandcentrix.thirtyinch.internal.TiPresenterProvider;
import net.grandcentrix.thirtyinch.internal.TiViewProvider;
import net.grandcentrix.thirtyinch.internal.UiThreadExecutor;
import net.grandcentrix.thirtyinch.util.AnnotationUtil;
/**
* An Activity which has a {@link TiPresenter} to build the Model View Presenter architecture on
* Android.
*
* <p>
* The {@link TiPresenter} will be created in {@link #providePresenter()} called in
* {@link #onCreate(Bundle)}. Depending on the {@link TiConfiguration} passed into the
* {@link TiPresenter#TiPresenter(TiConfiguration)} constructor the {@link TiPresenter} survives
* orientation changes (default).
* </p>
* <p>
* The {@link TiPresenter} requires a interface to communicate with the View. Normally the Activity
* implements the View interface (which must extend {@link TiView}) and is returned by default
* from {@link #provideView()}.
* </p>
*
* <p>
* Example:
* <code>
* <pre>
* public class MyActivity extends TiActivity<MyPresenter, MyView> implements MyView {
*
* @Override
* public MyPresenter providePresenter() {
* return new MyPresenter();
* }
* }
*
* public class MyPresenter extends TiPresenter<MyView> {
*
* @Override
* protected void onCreate() {
* super.onCreate();
* }
* }
*
* public interface MyView extends TiView {
*
* // void showItems(List<Item> items);
*
* // Observable<Item> onItemClicked();
* }
* </pre>
* </code>
* </p>
*
* @param <V> the View type, must implement {@link TiView}
* @param <P> the Presenter type, must extend {@link TiPresenter}
*/
public abstract class TiActivity<P extends TiPresenter<V>, V extends TiView>
extends AppCompatActivity
implements TiPresenterProvider<P>, TiViewProvider<V>, DelegatedTiActivity,
TiLoggingTagProvider, InterceptableViewBinder<V>, PresenterAccessor<P, V> {
private final String TAG = this.getClass().getSimpleName()
+ ":" + TiActivity.class.getSimpleName()
+ "@" + Integer.toHexString(this.hashCode());
private final TiActivityDelegate<P, V> mDelegate
= new TiActivityDelegate<>(this, this, this, this, PresenterSavior.getInstance());
private final UiThreadExecutor mUiThreadExecutor = new UiThreadExecutor();
@CallSuper
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDelegate.onCreate_afterSuper(savedInstanceState);
}
@CallSuper
@Override
protected void onStart() {
super.onStart();
mDelegate.onStart_afterSuper();
}
@CallSuper
@Override
protected void onStop() {
mDelegate.onStop_beforeSuper();
super.onStop();
mDelegate.onStop_afterSuper();
}
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull final Bundle outState) {
super.onSaveInstanceState(outState);
mDelegate.onSaveInstanceState_afterSuper(outState);
}
@CallSuper
@Override
protected void onDestroy() {
super.onDestroy();
mDelegate.onDestroy_afterSuper();
}
@NonNull
@Override
public final Removable addBindViewInterceptor(@NonNull final BindViewInterceptor interceptor) {
return mDelegate.addBindViewInterceptor(interceptor);
}
@Override
public final Object getHostingContainer() {
return this;
}
@Nullable
@Override
public final V getInterceptedViewOf(@NonNull final BindViewInterceptor interceptor) {
return mDelegate.getInterceptedViewOf(interceptor);
}
@NonNull
@Override
public final List<BindViewInterceptor> getInterceptors(
@NonNull final Filter<BindViewInterceptor> predicate) {
return mDelegate.getInterceptors(predicate);
}
@Override
public String getLoggingTag() {
return TAG;
}
/**
* is {@code null} before {@link #onCreate(Bundle)}
*/
@Override
public final P getPresenter() {
return mDelegate.getPresenter();
}
@Override
public final Executor getUiThreadExecutor() {
return mUiThreadExecutor;
}
/**
* Invalidates the cache of the latest bound view. Forces the next binding of the view to run
* through all the interceptors (again).
*/
@Override
public final void invalidateView() {
mDelegate.invalidateView();
}
@Override
public final boolean isActivityFinishing() {
return isFinishing();
}
@CallSuper
@Override
public void onConfigurationChanged(@NonNull final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDelegate.onConfigurationChanged_afterSuper(newConfig);
}
@SuppressWarnings("unchecked")
@NonNull
@Override
public V provideView() {
final Class<?> foundViewInterface = AnnotationUtil
.getInterfaceOfClassExtendingGivenInterface(this.getClass(), TiView.class);
if (foundViewInterface == null) {
throw new IllegalArgumentException(
"This Activity doesn't implement a TiView interface. "
+ "This is the default behaviour. Override provideView() to explicitly change this.");
} else {
if (foundViewInterface.getSimpleName().equals("TiView")) {
throw new IllegalArgumentException(
"extending TiView doesn't make sense, it's an empty interface."
+ " This is the default behaviour. Override provideView() to explicitly change this.");
} else {
// assume that the activity itself is the view and implements the TiView interface
return (V) this;
}
}
}
@Override
public String toString() {
String presenter = mDelegate.getPresenter() == null ? "null" :
mDelegate.getPresenter().getClass().getSimpleName()
+ "@" + Integer.toHexString(mDelegate.getPresenter().hashCode());
return getClass().getSimpleName()
+ ":" + TiActivity.class.getSimpleName()
+ "@" + Integer.toHexString(hashCode())
+ "{presenter = " + presenter + "}";
}
}
| grandcentrix/ThirtyInch | thirtyinch/src/main/java/net/grandcentrix/thirtyinch/TiActivity.java | Java | apache-2.0 | 7,692 |
/*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.ibm.jbatch.jsl.util;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
public class JSLValidationEventHandler implements ValidationEventHandler {
private boolean eventOccurred = false;
public boolean handleEvent(ValidationEvent event) {
System.out.println("\nMESSAGE: " + event.getMessage());
System.out.println("\nSEVERITY: " + event.getSeverity());
System.out.println("\nLINKED EXC: " + event.getLinkedException());
System.out.println("\nLOCATOR INFO:\n------------");
System.out.println("\n COLUMN NUMBER: " + event.getLocator().getColumnNumber());
System.out.println("\n LINE NUMBER: " + event.getLocator().getLineNumber());
System.out.println("\n OFFSET: " + event.getLocator().getOffset());
System.out.println("\n CLASS: " + event.getLocator().getClass());
System.out.println("\n NODE: " + event.getLocator().getNode());
System.out.println("\n OBJECT: " + event.getLocator().getObject());
System.out.println("\n URL: " + event.getLocator().getURL());
eventOccurred = true;
// Allow more parsing feedback
return true;
}
public boolean eventOccurred() {
return eventOccurred;
}
}
| papegaaij/jsr-352 | JSR352.JobXML.Model/src/main/java/com/ibm/jbatch/jsl/util/JSLValidationEventHandler.java | Java | apache-2.0 | 2,107 |
package com.iclockwork.percy.wechat4j;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* HelloWorldTest
*
* @author: fengwang
* @date: 2016/3/9 13:40
* @version: 1.0
* @since: JDK 1.7
*/
public class HelloWorldTest {
/**
* helloworld
*/
private HelloWorld helloworld;
@BeforeMethod
public void setUp() throws Exception {
helloworld = new HelloWorld();
}
@AfterMethod
public void tearDown() throws Exception {
}
@Test
public void testHello() throws Exception {
helloworld.hello();
}
}
| iclockwork/percy | wechat4j/src/test/java/com/iclockwork/percy/wechat4j/HelloWorldTest.java | Java | apache-2.0 | 646 |
package com.scicrop.se.commons.utils;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
public class LogHelper {
private LogHelper(){}
private static LogHelper INSTANCE = null;
public static LogHelper getInstance(){
if(INSTANCE == null) INSTANCE = new LogHelper();
return INSTANCE;
}
public void setLogger(String logNamePattern, String logFolder){
String logPath = logFolder + Constants.APP_NAME+"_"+logNamePattern+".log";
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.INFO);
PatternLayout layout = new PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n");
rootLogger.addAppender(new ConsoleAppender(layout));
try {
RollingFileAppender fileAppender = new RollingFileAppender(layout, logPath);
rootLogger.addAppender(fileAppender);
} catch (IOException e) {
System.err.println("Failed to find/access "+logPath+" !");
System.exit(1);
}
}
public void handleVerboseLog(boolean isVerbose, boolean isLog, Log log, char type, String data){
if(isLog){
logData(data, type, log);
}
if(isVerbose){
verbose(data, type);
}
}
public void logData(String data, char type, Log log){
switch (type) {
case 'i':
log.info(data);
break;
case 'w':
log.warn(data);
break;
case 'e':
log.error(data);
break;
default:
log.info(data);
break;
}
}
public void verbose(String data, char type){
switch (type) {
case 'e':
System.err.println(data);
break;
default:
System.out.println(data);
break;
}
}
}
| Scicrop/sentinel-extractor | source-code/sentinel-extractor-commons/src/com/scicrop/se/commons/utils/LogHelper.java | Java | apache-2.0 | 1,743 |
/*
* 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 javax.mail.search;
import javax.mail.Address;
/**
* Term that compares two addresses.
*
* @version $Rev: 920714 $ $Date: 2010-03-09 07:55:49 +0100 (Di, 09. Mär 2010) $
*/
public abstract class AddressTerm extends SearchTerm {
private static final long serialVersionUID = 2005405551929769980L;
/**
* The address.
*/
protected Address address;
/**
* Constructor taking the address for this term.
* @param address the address
*/
protected AddressTerm(Address address) {
this.address = address;
}
/**
* Return the address of this term.
*
* @return the addre4ss
*/
public Address getAddress() {
return address;
}
/**
* Match to the supplied address.
*
* @param address the address to match with
* @return true if the addresses match
*/
protected boolean match(Address address) {
return this.address.equals(address);
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof AddressTerm == false) return false;
return address.equals(((AddressTerm) other).address);
}
public int hashCode() {
return address.hashCode();
}
}
| salyh/jm14specsvn | src/main/java/javax/mail/search/AddressTerm.java | Java | apache-2.0 | 2,071 |
public class Lab4_2
{
public static void main(String[] arg)
{
System.out.print(" * |");
for(int x=1;x<=12;x++) {
if (x<10) System.out.print(' ');
if (x<100) System.out.print(' ');
System.out.print(x+" ");
}
System.out.println();
for(int x=1;x<=21;x++) {
if (x<10) System.out.print('-');
System.out.print("--");
}
System.out.println();
for(int i=1;i<=12;i++)
{
if (i<10) System.out.print(' ');
System.out.print(i+" |");
for(int j=1;j<=12;j++) {
if (i*j<10) System.out.print(' ');
if (j*i<100) System.out.print(' ');
System.out.print(j*i+" ");
}
System.out.println();
}
System.out.println();
System.out.println();
System.out.print(" + |");
for(int x=1;x<=12;x++) {
if (x<10) System.out.print(' ');
if (x<100) System.out.print(' ');
System.out.print(x+" ");
}
System.out.println();
for(int x=1;x<=21;x++) {
if (x<10) System.out.print('-');
System.out.print("--");
}
System.out.println();
for(int i=1;i<=12;i++)
{
if (i<10) System.out.print(' ');
System.out.print(i+" |");
for(int j=1;j<=12;j++) {
if (i+j<10) System.out.print(' ');
if (j+i<100) System.out.print(' ');
System.out.print(j+i+" ");
}
System.out.println();
}
}
}
| Seven-and-Nine/example-code-for-nine | Java/normal code/Java I/Lab4/Lab4_2.java | Java | artistic-2.0 | 1,401 |
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* 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 uk.co.senab.photoview;
import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
public class PhotoView extends ImageView implements IPhotoView {
private final PhotoViewAttacher mAttacher;
private ScaleType mPendingScaleType;
public PhotoView(Context context) {
this(context, null);
}
public PhotoView(Context context, AttributeSet attr) {
this(context, attr, 0);
}
public PhotoView(Context context, AttributeSet attr, int defStyle) {
super(context, attr, defStyle);
super.setScaleType(ScaleType.MATRIX);
mAttacher = new PhotoViewAttacher(this);
if (null != mPendingScaleType) {
setScaleType(mPendingScaleType);
mPendingScaleType = null;
}
}
@Override
public void setPhotoViewRotation(float rotationDegree) {
mAttacher.setPhotoViewRotation(rotationDegree);
}
@Override
public boolean canZoom() {
return mAttacher.canZoom();
}
@Override
public RectF getDisplayRect() {
return mAttacher.getDisplayRect();
}
@Override
public Matrix getDisplayMatrix() {
return mAttacher.getDrawMatrix();
}
@Override
public boolean setDisplayMatrix(Matrix finalRectangle) {
return mAttacher.setDisplayMatrix(finalRectangle);
}
@Override
@Deprecated
public float getMinScale() {
return getMinimumScale();
}
@Override
public float getMinimumScale() {
return mAttacher.getMinimumScale();
}
@Override
@Deprecated
public float getMidScale() {
return getMediumScale();
}
@Override
public float getMediumScale() {
return mAttacher.getMediumScale();
}
@Override
@Deprecated
public float getMaxScale() {
return getMaximumScale();
}
@Override
public float getMaximumScale() {
return mAttacher.getMaximumScale();
}
@Override
public float getScale() {
return mAttacher.getScale();
}
@Override
public ScaleType getScaleType() {
return mAttacher.getScaleType();
}
@Override
public void setAllowParentInterceptOnEdge(boolean allow) {
mAttacher.setAllowParentInterceptOnEdge(allow);
}
@Override
@Deprecated
public void setMinScale(float minScale) {
setMinimumScale(minScale);
}
@Override
public void setMinimumScale(float minimumScale) {
mAttacher.setMinimumScale(minimumScale);
}
@Override
@Deprecated
public void setMidScale(float midScale) {
setMediumScale(midScale);
}
@Override
public void setMediumScale(float mediumScale) {
mAttacher.setMediumScale(mediumScale);
}
@Override
@Deprecated
public void setMaxScale(float maxScale) {
setMaximumScale(maxScale);
}
@Override
public void setMaximumScale(float maximumScale) {
mAttacher.setMaximumScale(maximumScale);
}
@Override
// setImageBitmap calls through to this method
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override
public void setOnPhotoTapListener(OnPhotoTapListener listener) {
mAttacher.setOnPhotoTapListener(listener);
}
@Override
public OnPhotoTapListener getOnPhotoTapListener() {
return mAttacher.getOnPhotoTapListener();
}
@Override
public void setOnViewTapListener(OnViewTapListener listener) {
mAttacher.setOnViewTapListener(listener);
}
@Override
public OnViewTapListener getOnViewTapListener() {
return mAttacher.getOnViewTapListener();
}
@Override
public void setScale(float scale) {
mAttacher.setScale(scale);
}
@Override
public void setScale(float scale, boolean animate) {
mAttacher.setScale(scale, animate);
}
@Override
public void setScale(float scale, float focalX, float focalY, boolean animate) {
mAttacher.setScale(scale, focalX, focalY, animate);
}
@Override
public void setScaleType(ScaleType scaleType) {
if (null != mAttacher) {
mAttacher.setScaleType(scaleType);
} else {
mPendingScaleType = scaleType;
}
}
@Override
public void setZoomable(boolean zoomable) {
mAttacher.setZoomable(zoomable);
}
@Override
public Bitmap getVisibleRectangleBitmap() {
return mAttacher.getVisibleRectangleBitmap();
}
@Override
public void setZoomTransitionDuration(int milliseconds) {
mAttacher.setZoomTransitionDuration(milliseconds);
}
@Override
protected void onDetachedFromWindow() {
mAttacher.cleanup();
super.onDetachedFromWindow();
}
} | cocolove2/LISDemo | library-lis/src/main/java/uk/co/senab/photoview/PhotoView.java | Java | artistic-2.0 | 6,686 |
/**
* Copyright (c) 2013, Jens Hohmuth
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.lessvoid.coregl;
import com.lessvoid.coregl.spi.CoreGL;
/**
* Simple helper methods to render vertex arrays.
*
* @author void
*/
public class CoreRender {
private final CoreGL gl;
CoreRender(final CoreGL gl) {
this.gl = gl;
}
public static CoreRender createCoreRender(final CoreGL gl) {
return new CoreRender(gl);
}
// Lines
/**
* Render lines.
*
* @param count
* number of vertices
*/
public void renderLines(final int count) {
gl.glDrawArrays(gl.GL_LINE_STRIP(), 0, count);
gl.checkGLError("glDrawArrays");
}
/**
* Render adjacent lines.
*
* @param count
* number of vertices
*/
public void renderLinesAdjacent(final int count) {
gl.glDrawArrays(gl.GL_LINE_STRIP_ADJACENCY(), 0, count);
gl.checkGLError("glDrawArrays");
}
// Triangle Strip
/**
* Render the currently active VAO using triangle strips with the given number
* of vertices.
*
* @param count
* number of vertices to render as triangle strips
*/
public void renderTriangleStrip(final int count) {
gl.glDrawArrays(gl.GL_TRIANGLE_STRIP(), 0, count);
gl.checkGLError("glDrawArrays");
}
/**
* Render the currently active VAO using triangle strips, sending the given
* number of indizes.
*
* @param count
* number of indizes to render as triangle strips
*/
public void renderTriangleStripIndexed(final int count) {
gl.glDrawElements(gl.GL_TRIANGLE_STRIP(), count, gl.GL_UNSIGNED_INT(), 0);
gl.checkGLError("glDrawElements(GL_TRIANGLE_STRIP)");
}
/**
* Render the currently active VAO using triangle strips with the given number
* of vertices AND do that primCount times.
*
* @param count
* number of vertices to render as triangle strips per primitve
* @param primCount
* number of primitives to render
*/
public void renderTriangleStripInstances(final int count, final int primCount) {
gl.glDrawArraysInstanced(gl.GL_TRIANGLE_STRIP(), 0, count, primCount);
gl.checkGLError("glDrawArraysInstanced(GL_TRIANGLE_STRIP)");
}
// Triangle Fan
/**
* Render the currently active VAO using triangle fan with the given number of
* vertices.
*
* @param count
* number of vertices to render as triangle fan
*/
public void renderTriangleFan(final int count) {
gl.glDrawArrays(gl.GL_TRIANGLE_FAN(), 0, count);
gl.checkGLError("glDrawArrays");
}
/**
* Render the currently active VAO using triangle fans, sending the given
* number of indizes.
*
* @param count
* number of indizes to render as triangle fans.
*/
public void renderTriangleFanIndexed(final int count) {
gl.glDrawElements(gl.GL_TRIANGLE_FAN(), count, gl.GL_UNSIGNED_INT(), 0);
gl.checkGLError("glDrawElements(GL_TRIANGLE_FAN)");
}
// Individual Triangles
/**
* Render the currently active VAO using triangles with the given number of
* vertices.
*
* @param vertexCount
* number of vertices to render as triangle strips
*/
public void renderTriangles(final int vertexCount) {
gl.glDrawArrays(gl.GL_TRIANGLES(), 0, vertexCount);
gl.checkGLError("glDrawArrays");
}
/**
* Render the currently active VAO using triangles with the given number of
* vertices starting at the given offset.
*
* @param offset
* offset to start sending vertices
* @param vertexCount
* number of vertices to render as triangle strips
*/
public void renderTrianglesOffset(final int offset, final int vertexCount) {
gl.glDrawArrays(gl.GL_TRIANGLES(), offset, vertexCount);
gl.checkGLError("glDrawArrays");
}
/**
* Render the currently active VAO using triangles with the given number of
* vertices.
*
* @param count
* number of vertices to render as triangles
*/
public void renderTrianglesIndexed(final int count) {
gl.glDrawElements(gl.GL_TRIANGLES(), count, gl.GL_UNSIGNED_INT(), 0);
gl.checkGLError("glDrawElements");
}
/**
* Render the currently active VAO using triangles with the given number of
* vertices AND do that primCount times.
*
* @param count
* number of vertices to render as triangles per primitve
* @param primCount
* number of primitives to render
*/
public void renderTrianglesInstances(final int count, final int primCount) {
gl.glDrawArraysInstanced(gl.GL_TRIANGLES(), 0, count, primCount);
gl.checkGLError("glDrawArraysInstanced(GL_TRIANGLES)");
}
// Points
/**
* Render the currently active VAO using points with the given number of
* vertices.
*
* @param count
* number of vertices to render as points
*/
public void renderPoints(final int count) {
gl.glDrawArrays(gl.GL_POINTS(), 0, count);
gl.checkGLError("glDrawArrays(GL_POINTS)");
}
/**
* Render the currently active VAO using points with the given number of
* vertices AND do that primCount times.
*
* @param count
* number of vertices to render as points per primitive
* @param primCount
* number of primitives to render
*/
public void renderPointsInstances(final int count, final int primCount) {
gl.glDrawArraysInstanced(gl.GL_POINTS(), 0, count, primCount);
gl.checkGLError("glDrawArraysInstanced(GL_POINTS)");
}
// Utils
/**
* Set the clear color.
*
* @param r
* red
* @param g
* green
* @param b
* blue
* @param a
* alpha
*/
public void clearColor(final float r, final float g, final float b, final float a) {
gl.glClearColor(r, g, b, a);
}
/**
* Clear the color buffer.
*/
public void clearColorBuffer() {
gl.glClear(gl.GL_COLOR_BUFFER_BIT());
}
}
| bgroenks96/coregl | coregl-utils/src/main/java/com/lessvoid/coregl/CoreRender.java | Java | bsd-2-clause | 7,233 |
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.initialization;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.gradle.api.internal.project.ProjectIdentifier;
import org.gradle.api.internal.project.ProjectRegistry;
import org.gradle.api.InvalidUserDataException;
import java.io.File;
import java.io.Serializable;
public class ProjectDirectoryProjectSpec extends AbstractProjectSpec implements Serializable {
private final File dir;
public ProjectDirectoryProjectSpec(File dir) {
this.dir = dir;
}
public String getDisplayName() {
return String.format("with project directory '%s'", dir);
}
public boolean isCorresponding(File file) {
return dir.equals(file);
}
protected String formatNoMatchesMessage() {
return String.format("No projects in this build have project directory '%s'.", dir);
}
protected String formatMultipleMatchesMessage(Iterable<? extends ProjectIdentifier> matches) {
return String.format("Multiple projects in this build have project directory '%s': %s", dir, matches);
}
protected boolean select(ProjectIdentifier project) {
return project.getProjectDir().equals(dir);
}
@Override
protected void checkPreconditions(ProjectRegistry<?> registry) {
if (!dir.exists()) {
throw new InvalidUserDataException(String.format("Project directory '%s' does not exist.", dir));
}
if (!dir.isDirectory()) {
throw new InvalidUserDataException(String.format("Project directory '%s' is not a directory.", dir));
}
}
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
| tkmnet/RCRS-ADF | gradle/gradle-2.1/src/core/org/gradle/initialization/ProjectDirectoryProjectSpec.java | Java | bsd-2-clause | 2,457 |
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.gde.core.filters.impl;
import com.jme3.gde.core.filters.AbstractFilterNode;
import com.jme3.gde.core.filters.FilterNode;
import com.jme3.post.Filter;
import com.jme3.water.WaterFilter;
import org.openide.loaders.DataObject;
import org.openide.nodes.Node;
import org.openide.nodes.Sheet;
/**
*
* @author Rémy Bouquet
*/
@org.openide.util.lookup.ServiceProvider(service = FilterNode.class)
public class JmeWaterFilter extends AbstractFilterNode {
public JmeWaterFilter() {
}
public JmeWaterFilter(WaterFilter filter, DataObject object, boolean readOnly) {
super(filter);
this.dataObject = object;
this.readOnly = readOnly;
}
@Override
protected Sheet createSheet() {
Sheet sheet = super.createSheet();
Sheet.Set set = Sheet.createPropertiesSet();
set.setDisplayName("Water");
set.setName("Water");
WaterFilter obj = (WaterFilter) filter;
if (obj == null) {
return sheet;
}
createFields(WaterFilter.class, set, obj);
sheet.put(set);
return sheet;
}
@Override
public Class<?> getExplorerObjectClass() {
return WaterFilter.class;
}
@Override
public Node[] createNodes(Object key, DataObject dataObject, boolean readOnly) {
return new Node[]{new JmeWaterFilter((WaterFilter) key, dataObject, readOnly)};
}
}
| chototsu/MikuMikuStudio | sdk/jme3-core/src/com/jme3/gde/core/filters/impl/JmeWaterFilter.java | Java | bsd-2-clause | 3,026 |
package com.glob3mobile.vectorial.processing;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import com.glob3mobile.utils.Progress;
import com.glob3mobile.vectorial.lod.PointFeatureLODStorage;
import com.glob3mobile.vectorial.lod.mapdb.PointFeatureLODMapDBStorage;
import com.glob3mobile.vectorial.storage.PointFeature;
import com.glob3mobile.vectorial.storage.PointFeatureStorage;
import com.glob3mobile.vectorial.storage.mapdb.PointFeatureMapDBStorage;
public class LODPointFeaturesPreprocessor {
private static class LeafNodesImporter
implements
PointFeatureStorage.NodeVisitor {
private final long _nodesCount;
private final PointFeatureLODStorage _lodStorage;
private final boolean _verbose;
private Progress _progress;
private LeafNodesImporter(final long nodesCount,
final PointFeatureLODStorage lodStorage,
final boolean verbose) {
_nodesCount = nodesCount;
_lodStorage = lodStorage;
_verbose = verbose;
}
@Override
public void start() {
_progress = new Progress(_nodesCount) {
@Override
public void informProgress(final long stepsDone,
final double percent,
final long elapsed,
final long estimatedMsToFinish) {
if (_verbose) {
System.out.println(_lodStorage.getName() + ": 1/4 Importing leaf nodes: "
+ progressString(stepsDone, percent, elapsed, estimatedMsToFinish));
}
}
};
}
@Override
public void stop() {
_progress.finish();
_progress = null;
}
@Override
public boolean visit(final PointFeatureStorage.Node node) {
final List<PointFeature> features = new ArrayList<>(node.getFeatures());
_lodStorage.addLeafNode( //
node.getID(), //
node.getNodeSector(), //
node.getMinimumSector(), //
features //
);
_progress.stepDone();
return true;
}
}
public static void process(final File storageDir,
final String storageName,
final File lodDir,
final String lodName,
final int maxFeaturesPerNode,
final Comparator<PointFeature> featuresComparator,
final boolean createClusters,
final boolean verbose) throws IOException {
try (final PointFeatureStorage storage = PointFeatureMapDBStorage.openReadOnly(storageDir, storageName)) {
try (final PointFeatureLODStorage lodStorage = PointFeatureLODMapDBStorage.createEmpty(storage.getSector(), lodDir,
lodName, maxFeaturesPerNode, featuresComparator, createClusters)) {
final PointFeatureStorage.Statistics statistics = storage.getStatistics(verbose);
if (verbose) {
statistics.show();
System.out.println();
}
final int nodesCount = statistics.getNodesCount();
storage.acceptDepthFirstVisitor(new LeafNodesImporter(nodesCount, lodStorage, verbose));
lodStorage.createLOD(verbose);
if (verbose) {
System.out.println(lodStorage.getName() + ": 4/4 Optimizing storage...");
}
lodStorage.optimize();
if (verbose) {
System.out.println();
final PointFeatureLODStorage.Statistics lodStatistics = lodStorage.getStatistics(verbose);
lodStatistics.show();
}
}
}
}
private LODPointFeaturesPreprocessor() {
}
public static void main(final String[] args) throws IOException {
System.out.println("LODPointFeaturesPreprocessor 0.1");
System.out.println("--------------------------------\n");
final File sourceDir = new File("PointFeaturesStorage");
// final String sourceName = "Cities1000";
// final String sourceName = "AR";
// final String sourceName = "ES";
// final String sourceName = "GEONames-PopulatedPlaces";
// final String sourceName = "SpanishBars";
final String sourceName = "Tornados";
final File lodDir = new File("PointFeaturesLOD");
final String lodName = sourceName + "_LOD";
final int maxFeaturesPerNode = 64;
// final int maxFeaturesPerNode = 96;
final boolean createClusters = true;
final Comparator<PointFeature> featuresComparator = createClusters ? null : new GEONamesComparator();
final boolean verbose = true;
LODPointFeaturesPreprocessor.process( //
sourceDir, sourceName, //
lodDir, lodName, //
maxFeaturesPerNode, //
featuresComparator, //
createClusters, //
verbose);
System.out.println("\n- done!");
}
}
| octavianiLocator/g3m | tools/vectorial-streaming/src/com/glob3mobile/vectorial/processing/LODPointFeaturesPreprocessor.java | Java | bsd-2-clause | 5,344 |
/*
* Copyright 2016 Skynav, Inc. All rights reserved.
* Portions Copyright 2009 Extensible Formatting Systems, Inc (XFSI).
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY SKYNAV, INC. AND ITS CONTRIBUTORS “AS IS” AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SKYNAV, INC. 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.
*/
package com.xfsi.xav.validation.images.jpeg;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
/**
* Handles JPEG input stream. Tracks total bytes read and allows putting back of read data.
*/
class JpegInputStream {
private int readByteCount = 0;
private final DataInputStream inputStream;
private LinkedList<Byte> putBack = new LinkedList<Byte>();
JpegInputStream(InputStream is)
{
this.inputStream = new DataInputStream(is);
}
byte readByte() throws EOFException, IOException
{
if (this.putBack.size() == 0)
{
byte b = this.inputStream.readByte();
this.readByteCount++;
return b;
}
return this.putBack.remove();
}
short readShort() throws EOFException, IOException
{
if (this.putBack.size() == 0)
{
short s = this.inputStream.readShort();
this.readByteCount += 2;
return s;
}
short msb = readByte();
short lsb = readByte();
return (short) ((msb << 8) | (lsb & 0xff));
}
int readInt() throws EOFException, IOException
{
if (this.putBack.size() == 0)
{
int i = this.inputStream.readInt();
this.readByteCount += 4;
return i;
}
int mss = readShort();
int lss = readShort();
return (mss << 16) | (lss & 0xffff);
}
void skipBytes(int count) throws EOFException, IOException
{
// DataInputStream skipBytes() in jpegInputStream does not throw EOFException() if EOF reached,
// which we are interested in, so read the bytes to skip them which WILL generate an EOFException().
for (int i = 0; i < count; i++)
readByte();
}
void putBack(byte b)
{
this.putBack.add(b);
}
int getTotalBytesRead()
{
return this.readByteCount;
}
}
| skynav/ttt | ttt-ttv/src/main/java/com/xfsi/xav/validation/images/jpeg/JpegInputStream.java | Java | bsd-2-clause | 3,933 |
// EarthShape.java
// See copyright.txt for license and terms of use.
package earthshape;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import com.jogamp.opengl.GLCapabilities;
import util.FloatUtil;
import util.Vector3d;
import util.Vector3f;
import util.swing.ModalDialog;
import util.swing.MyJFrame;
import util.swing.MySwingWorker;
import util.swing.ProgressDialog;
import static util.swing.SwingUtil.log;
/** This application demonstrates a procedure for inferring the shape
* of a surface (such as the Earth) based on the observed locations of
* stars from various locations at a fixed point in time.
*
* This class, EarthShape, manages UI components external to the 3D
* display, such as the menu and status bars. It also contains all of
* the code to construct the virtual 3D map using various algorithms.
* The 3D display, along with its camera controls, is in EarthMapCanvas. */
public class EarthShape extends MyJFrame {
// --------- Constants ----------
/** AWT boilerplate generated serial ID. */
private static final long serialVersionUID = 3903955302894393226L;
/** Size of the first constructed square, in kilometers. The
* displayed size is then determined by the map scale, which
* is normally 1 unit per 1000 km. */
private static final float INITIAL_SQUARE_SIZE_KM = 1000;
/** Initial value of 'adjustOrientationDegrees', and the value to
* which it is reset when a new square is created. */
private static final float DEFAULT_ADJUST_ORIENTATION_DEGREES = 1.0f;
/** Do not let 'adjustOrientationDegrees' go below this value. Below
* this value is pointless because the precision of the variance is
* not high enough to discriminate among the choices. */
private static final float MINIMUM_ADJUST_ORIENTATION_DEGREES = 1e-7f;
// ---------- Instance variables ----------
// ---- Observation Information ----
/** The observations that will drive surface reconstruction.
* By default, this will be data from the real world, but it
* can be swapped out at the user's option. */
public WorldObservations worldObservations = new RealWorldObservations();
/** Set of stars that are enabled. */
private LinkedHashMap<String, Boolean> enabledStars = new LinkedHashMap<String, Boolean>();
// ---- Interactive surface construction state ----
/** The square we will build upon when the next square is added.
* This may be null. */
private SurfaceSquare activeSquare;
/** When adjusting the orientation of the active square, this
* is how many degrees to rotate at once. */
private float adjustOrientationDegrees = DEFAULT_ADJUST_ORIENTATION_DEGREES;
// ---- Options ----
/** When true, star observations are only compared by their
* direction. When false, we also consider the location of the
* observer, which allows us to handle nearby objects. */
public boolean assumeInfiniteStarDistance = false;
/** When true, star observations are only compared by their
* direction, and furthermore, only the elevation, ignoring
* azimuth. This is potentially interesting because, in
* practice, it is difficult to accurately measure azimuth
* with just a hand-held sextant. */
public boolean onlyCompareElevations = false;
/** When analyzing the solution space, use this many points of
* rotation on each side of 0, for each axis. Note that the
* algorithm is cubic in this parameter. */
private int solutionAnalysisPointsPerSide = 20;
/** If the Sun's elevation is higher than this value, then
* we cannot see any stars. */
private float maximumSunElevation = -5;
/** When true, take the Sun's elevation into account. */
private boolean useSunElevation = true;
/** When true, use the "new" orientation algorithm that
* repeatedly applies the recommended command. Otherwise,
* use the older one based on average deviation. The old
* algorithm is faster, but slightly less accurate, and
* does not mimic the process a user would use to manually
* adjust a square's orientation. */
private boolean newAutomaticOrientationAlgorithm = true;
// ---- Widgets ----
/** Canvas showing the Earth surface built so far. */
private EarthMapCanvas emCanvas;
/** Widget to show various state variables such as camera position. */
private JLabel statusLabel;
/** Selected square info panel on right side. */
private InfoPanel infoPanel;
// Menu items to toggle various options.
private JCheckBoxMenuItem drawCoordinateAxesCBItem;
private JCheckBoxMenuItem drawCrosshairCBItem;
private JCheckBoxMenuItem drawWireframeSquaresCBItem;
private JCheckBoxMenuItem drawCompassesCBItem;
private JCheckBoxMenuItem drawSurfaceNormalsCBItem;
private JCheckBoxMenuItem drawCelestialNorthCBItem;
private JCheckBoxMenuItem drawStarRaysCBItem;
private JCheckBoxMenuItem drawUnitStarRaysCBItem;
private JCheckBoxMenuItem drawBaseSquareStarRaysCBItem;
private JCheckBoxMenuItem drawTravelPathCBItem;
private JCheckBoxMenuItem drawActiveSquareAtOriginCBItem;
private JCheckBoxMenuItem useSunElevationCBItem;
private JCheckBoxMenuItem invertHorizontalCameraMovementCBItem;
private JCheckBoxMenuItem invertVerticalCameraMovementCBItem;
private JCheckBoxMenuItem newAutomaticOrientationAlgorithmCBItem;
private JCheckBoxMenuItem assumeInfiniteStarDistanceCBItem;
private JCheckBoxMenuItem onlyCompareElevationsCBItem;
private JCheckBoxMenuItem drawWorldWireframeCBItem;
private JCheckBoxMenuItem drawWorldStarsCBItem;
private JCheckBoxMenuItem drawSkyboxCBItem;
// ---------- Methods ----------
public EarthShape()
{
super("EarthShape");
this.setName("EarthShape (JFrame)");
this.setLayout(new BorderLayout());
this.setIcon();
for (String starName : this.worldObservations.getAllStars()) {
// Initially all stars are enabled.
this.enabledStars.put(starName, true);
}
this.setSize(1150, 800);
this.setLocationByPlatform(true);
this.setupJOGL();
this.buildMenuBar();
// Status bar on bottom.
this.statusLabel = new JLabel();
this.statusLabel.setName("statusLabel");
this.add(this.statusLabel, BorderLayout.SOUTH);
// Info panel on right.
this.add(this.infoPanel = new InfoPanel(), BorderLayout.EAST);
this.updateUIState();
}
/** Initialize the JOGL library, then create a GL canvas and
* associate it with this window. */
private void setupJOGL()
{
log("creating GLCapabilities");
// This call takes about one second to complete, which is
// pretty slow...
GLCapabilities caps = new GLCapabilities(null /*profile*/);
log("caps: "+caps);
caps.setDoubleBuffered(true);
caps.setHardwareAccelerated(true);
// Build the object that will show the surface.
this.emCanvas = new EarthMapCanvas(this, caps);
// Associate the canvas with 'this' window.
this.add(this.emCanvas, BorderLayout.CENTER);
}
/** Set the window icon to my application's icon. */
private void setIcon()
{
try {
URL url = this.getClass().getResource("globe-icon.png");
Image img = Toolkit.getDefaultToolkit().createImage(url);
this.setIconImage(img);
}
catch (Exception e) {
System.err.println("Failed to set app icon: "+e.getMessage());
}
}
private void showAboutBox()
{
String about =
"EarthShape\n"+
"Copyright 2017 Scott McPeak\n"+
"\n"+
"Published under the 2-clause BSD license.\n"+
"See copyright.txt for details.\n";
JOptionPane.showMessageDialog(this, about, "About", JOptionPane.INFORMATION_MESSAGE);
}
private void showKeyBindings()
{
String bindings =
"Left click in 3D view to enter FPS controls mode.\n"+
"Esc - Leave FPS mode.\n"+
"W/A/S/D - Move camera horizontally when in FPS mode.\n"+
"Space/Z - Move camera up or down in FPS mode.\n"+
"Left click on square in FPS mode to make it active.\n"+
"\n"+
"T - Reconstruct Earth from star data.\n"+
"\n"+
"C - Toggle compass or Earth texture.\n"+
"P - Toggle star rays for active square.\n"+
"G - Move camera to active square's center.\n"+
"H - Build complete Earth using assumed sphere.\n"+
"R - Build Earth using assumed sphere and random walk.\n"+
"\n"+
"U/O - Roll active square left or right.\n"+
"I/K - Pitch active square down or up.\n"+
"J/L - Yaw active square left or right.\n"+
"1 - Reset adjustment amount to 1 degree.\n"+
"-/= - Decrease or increase adjustment amount.\n"+
"; (semicolon) - Make recommended active square adjustment.\n"+
"/ (slash) - Automatically orient active square.\n"+
"\' (apostrophe) - Analyze rotation solution space for active square.\n"+
"\n"+
"N - Start a new surface.\n"+
"M - Add a square adjacent to the active square.\n"+
"Ctrl+N/S/E/W - Add a square to the N/S/E/W and automatically adjust it.\n"+
", (comma) - Move to previous active square.\n"+
". (period) - Move to next active square.\n"+
"Delete - Delete active square.\n"+
"\n"+
"0/PgUp/PgDn - Change animation state (not for general use)\n"+
"";
JOptionPane.showMessageDialog(this, bindings, "Bindings", JOptionPane.INFORMATION_MESSAGE);
}
/** Build the menu bar and attach it to 'this'. */
private void buildMenuBar()
{
// This ensures that the menu items do not appear underneath
// the GL canvas. Strangely, this problem appeared suddenly,
// after I made a seemingly irrelevant change (putting a
// scroll bar on the info panel). But this call solves it,
// so whatever.
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
JMenuBar menuBar = new JMenuBar();
this.setJMenuBar(menuBar);
// Used keys:
// a - Move camera left
// b
// c - Toggle compass
// d - Move camera right
// e
// f
// g - Go to selected square's center
// h - Build spherical Earth
// i - Pitch active square down
// j - Yaw active square left
// k - Pitch active square up
// l - Yaw active square right
// m - Add adjacent square to surface
// n - Build new surface
// o - Roll active square right
// p - Toggle star rays for active square
// q
// r - Build with random walk
// s - Move camera backward
// t - Build full Earth with star data
// u - Roll active square left
// v
// w - Move camera forward
// x
// y
// z - Move camera down
// 0 - Reset animation state to 0
// 1 - Reset adjustment amount to 1
// - - Decrease adjustment amount
// = - Increase adjustment amount
// ; - One recommended rotation adjustment
// ' - Analyze solution space
// , - Select previous square
// . - Select next square
// / - Automatically orient active square
// Space - Move camera up
// Delete - Delete active square
// Enter - enter FPS mode
// Esc - leave FPS mode
// Ins - canned commands
// PgUp - Decrement animation state
// PgDn - Increment animation state
// Ctrl+E - build and orient to the East
// Ctrl+W - build and orient to the West
// Ctrl+N - build and orient to the North
// Ctrl+S - build and orient to the South
menuBar.add(this.buildFileMenu());
menuBar.add(this.buildDrawMenu());
menuBar.add(this.buildBuildMenu());
menuBar.add(this.buildSelectMenu());
menuBar.add(this.buildEditMenu());
menuBar.add(this.buildNavigateMenu());
menuBar.add(this.buildAnimateMenu());
menuBar.add(this.buildOptionsMenu());
menuBar.add(this.buildHelpMenu());
}
private JMenu buildFileMenu()
{
JMenu menu = new JMenu("File");
addMenuItem(menu, "Use real world astronomical observations", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new RealWorldObservations());
}
});
menu.addSeparator();
addMenuItem(menu, "Use model: spherical Earth with nearby stars", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new CloseStarObservations());
}
});
addMenuItem(menu, "Use model: azimuthal equidistant projection flat Earth", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new AzimuthalEquidistantObservations());
}
});
addMenuItem(menu, "Use model: bowl-shaped Earth", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new BowlObservations());
}
});
addMenuItem(menu, "Use model: saddle-shaped Earth", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new SaddleObservations());
}
});
menu.addSeparator();
addMenuItem(menu, "Exit", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.dispose();
}
});
return menu;
}
private JMenu buildDrawMenu()
{
JMenu drawMenu = new JMenu("Draw");
this.drawCoordinateAxesCBItem =
addCBMenuItem(drawMenu, "Draw X/Y/Z coordinate axes", null,
this.emCanvas.drawAxes,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawAxes();
}
});
this.drawCrosshairCBItem =
addCBMenuItem(drawMenu, "Draw crosshair when in FPS camera mode", null,
this.emCanvas.drawCrosshair,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawCrosshair();
}
});
this.drawWireframeSquaresCBItem =
addCBMenuItem(drawMenu, "Draw squares as wireframes with translucent squares", null,
this.emCanvas.drawWireframeSquares,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawWireframeSquares();
}
});
this.drawCompassesCBItem =
addCBMenuItem(drawMenu, "Draw squares with compass texture (vs. world map)",
KeyStroke.getKeyStroke('c'),
this.emCanvas.drawCompasses,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawCompasses();
}
});
this.drawSurfaceNormalsCBItem =
addCBMenuItem(drawMenu, "Draw surface normals", null, this.emCanvas.drawSurfaceNormals,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawSurfaceNormals();
}
});
this.drawCelestialNorthCBItem =
addCBMenuItem(drawMenu, "Draw celestial North", null, this.emCanvas.drawCelestialNorth,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawCelestialNorth();
}
});
this.drawStarRaysCBItem =
addCBMenuItem(drawMenu, "Draw star rays for active square",
KeyStroke.getKeyStroke('p'),
this.activeSquareDrawsStarRays(),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawStarRays();
}
});
this.drawUnitStarRaysCBItem =
addCBMenuItem(drawMenu, "Draw star rays as unit vectors", null,
this.emCanvas.drawUnitStarRays,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawUnitStarRays();
}
});
this.drawBaseSquareStarRaysCBItem =
addCBMenuItem(drawMenu, "Draw star rays for the base square too, on the active square", null,
this.emCanvas.drawBaseSquareStarRays,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawBaseSquareStarRays();
}
});
this.drawTravelPathCBItem =
addCBMenuItem(drawMenu, "Draw the travel path from base square to active square", null,
this.emCanvas.drawTravelPath,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawTravelPath();
}
});
this.drawActiveSquareAtOriginCBItem =
addCBMenuItem(drawMenu, "Draw the active square at the 3D coordinate origin", null,
this.emCanvas.drawActiveSquareAtOrigin,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawActiveSquareAtOrigin();
}
});
this.drawWorldWireframeCBItem =
addCBMenuItem(drawMenu, "Draw world wireframe (if one is in use)", null,
this.emCanvas.drawWorldWireframe,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawWorldWireframe();
}
});
this.drawWorldStarsCBItem =
addCBMenuItem(drawMenu, "Draw world stars (if in use)", null,
this.emCanvas.drawWorldStars,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawWorldStars();
}
});
this.drawSkyboxCBItem =
addCBMenuItem(drawMenu, "Draw skybox", null,
this.emCanvas.drawSkybox,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawSkybox();
}
});
addMenuItem(drawMenu, "Set skybox distance...", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setSkyboxDistance();
}
});
addMenuItem(drawMenu, "Turn off all star rays", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.turnOffAllStarRays();
}
});
return drawMenu;
}
private JMenu buildBuildMenu()
{
JMenu buildMenu = new JMenu("Build");
addMenuItem(buildMenu, "Build Earth using active observational data or model",
KeyStroke.getKeyStroke('t'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildEarthSurfaceFromStarData();
}
});
addMenuItem(buildMenu, "Build complete Earth using assumed sphere",
KeyStroke.getKeyStroke('h'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildSphericalEarthSurfaceWithLatLong();
}
});
addMenuItem(buildMenu, "Build partial Earth using assumed sphere and random walk",
KeyStroke.getKeyStroke('r'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildSphericalEarthWithRandomWalk();
}
});
addMenuItem(buildMenu, "Start a new surface using star data",
KeyStroke.getKeyStroke('n'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.startNewSurface();
}
});
addMenuItem(buildMenu, "Add another square to the surface",
KeyStroke.getKeyStroke('m'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildNextSquare();
}
});
buildMenu.addSeparator();
addMenuItem(buildMenu, "Create new square 9 degrees to the East and orient it automatically",
KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.createAndAutomaticallyOrientActiveSquare(
0 /*deltLatitude*/, +9 /*deltaLongitude*/);
}
});
addMenuItem(buildMenu, "Create new square 9 degrees to the West and orient it automatically",
KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.createAndAutomaticallyOrientActiveSquare(
0 /*deltLatitude*/, -9 /*deltaLongitude*/);
}
});
addMenuItem(buildMenu, "Create new square 9 degrees to the North and orient it automatically",
KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.createAndAutomaticallyOrientActiveSquare(
+9 /*deltLatitude*/, 0 /*deltaLongitude*/);
}
});
addMenuItem(buildMenu, "Create new square 9 degrees to the South and orient it automatically",
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.createAndAutomaticallyOrientActiveSquare(
-9 /*deltLatitude*/, 0 /*deltaLongitude*/);
}
});
buildMenu.addSeparator();
addMenuItem(buildMenu, "Do some canned setup for debugging",
KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.doCannedSetup();
}
});
return buildMenu;
}
private JMenu buildSelectMenu()
{
JMenu selectMenu = new JMenu("Select");
addMenuItem(selectMenu, "Select previous square",
KeyStroke.getKeyStroke(','),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.selectNextSquare(false /*forward*/);
}
});
addMenuItem(selectMenu, "Select next square",
KeyStroke.getKeyStroke('.'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.selectNextSquare(true /*forward*/);
}
});
return selectMenu;
}
private JMenu buildEditMenu()
{
JMenu editMenu = new JMenu("Edit");
for (RotationCommand rc : RotationCommand.values()) {
this.addAdjustOrientationMenuItem(editMenu,
rc.description, rc.key, rc.axis);
}
editMenu.addSeparator();
addMenuItem(editMenu, "Double active square adjustment angle",
KeyStroke.getKeyStroke('='),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeAdjustOrientationDegrees(2.0f);
}
});
addMenuItem(editMenu, "Halve active square adjustment angle",
KeyStroke.getKeyStroke('-'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeAdjustOrientationDegrees(0.5f);
}
});
addMenuItem(editMenu, "Reset active square adjustment angle to 1 degree",
KeyStroke.getKeyStroke('1'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.adjustOrientationDegrees = 1;
EarthShape.this.updateUIState();
}
});
editMenu.addSeparator();
addMenuItem(editMenu, "Analyze solution space",
KeyStroke.getKeyStroke('\''),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.analyzeSolutionSpace();
}
});
addMenuItem(editMenu, "Set solution analysis resolution...",
null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setSolutionAnalysisResolution();
}
});
editMenu.addSeparator();
addMenuItem(editMenu, "Do one recommended rotation adjustment",
KeyStroke.getKeyStroke(';'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.applyRecommendedRotationCommand();
}
});
addMenuItem(editMenu, "Automatically orient active square",
KeyStroke.getKeyStroke('/'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.automaticallyOrientActiveSquare();
}
});
addMenuItem(editMenu, "Delete active square",
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.deleteActiveSquare();
}
});
return editMenu;
}
private JMenu buildNavigateMenu()
{
JMenu menu = new JMenu("Navigate");
addMenuItem(menu, "Control camera like a first-person shooter",
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.emCanvas.enterFPSMode();
}
});
addMenuItem(menu, "Leave first-person shooter mode",
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.emCanvas.exitFPSMode();
}
});
addMenuItem(menu, "Go to active square's center",
KeyStroke.getKeyStroke('g'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.goToActiveSquareCenter();
}
});
addMenuItem(menu, "Go to origin", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.moveCamera(new Vector3f(0,0,0));
}
});
menu.addSeparator();
addMenuItem(menu, "Curvature calculator...", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.showCurvatureDialog();
}
});
return menu;
}
private JMenu buildAnimateMenu()
{
JMenu menu = new JMenu("Animate");
addMenuItem(menu, "Reset to animation state 0",
KeyStroke.getKeyStroke('0'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setAnimationState(0);
}
});
addMenuItem(menu, "Increment animation state",
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setAnimationState(+1);
}
});
addMenuItem(menu, "Decrement animation state",
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setAnimationState(-1);
}
});
return menu;
}
private JMenu buildOptionsMenu()
{
JMenu menu = new JMenu("Options");
addMenuItem(menu, "Choose enabled stars...", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.chooseEnabledStars();
}
});
addMenuItem(menu, "Set maximum Sun elevation...",
null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setMaximumSunElevation();
}
});
this.useSunElevationCBItem =
addCBMenuItem(menu, "Take Sun elevation into account", null,
this.useSunElevation,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.useSunElevation =
!EarthShape.this.useSunElevation;
EarthShape.this.updateUIState();
}
});
menu.addSeparator();
this.invertHorizontalCameraMovementCBItem =
addCBMenuItem(menu, "Invert horizontal camera movement", null,
this.emCanvas.invertHorizontalCameraMovement,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.emCanvas.invertHorizontalCameraMovement =
!EarthShape.this.emCanvas.invertHorizontalCameraMovement;
EarthShape.this.updateUIState();
}
});
this.invertVerticalCameraMovementCBItem =
addCBMenuItem(menu, "Invert vertical camera movement", null,
this.emCanvas.invertVerticalCameraMovement,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.emCanvas.invertVerticalCameraMovement =
!EarthShape.this.emCanvas.invertVerticalCameraMovement;
EarthShape.this.updateUIState();
}
});
menu.addSeparator();
this.newAutomaticOrientationAlgorithmCBItem =
addCBMenuItem(menu, "Use new automatic orientation algorithm", null,
this.newAutomaticOrientationAlgorithm,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.newAutomaticOrientationAlgorithm =
!EarthShape.this.newAutomaticOrientationAlgorithm;
EarthShape.this.updateUIState();
}
});
this.assumeInfiniteStarDistanceCBItem =
addCBMenuItem(menu, "Assume stars are infinitely far away", null,
this.assumeInfiniteStarDistance,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.assumeInfiniteStarDistance =
!EarthShape.this.assumeInfiniteStarDistance;
EarthShape.this.updateAndRedraw();
}
});
this.onlyCompareElevationsCBItem =
addCBMenuItem(menu, "Only compare star elevations", null,
this.onlyCompareElevations,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.onlyCompareElevations =
!EarthShape.this.onlyCompareElevations;
EarthShape.this.updateAndRedraw();
}
});
return menu;
}
private JMenu buildHelpMenu()
{
JMenu helpMenu = new JMenu("Help");
addMenuItem(helpMenu, "Show all key bindings...", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.showKeyBindings();
}
});
addMenuItem(helpMenu, "About...", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.showAboutBox();
}
});
return helpMenu;
}
/** Add a menu item to adjust the orientation of the active square. */
private void addAdjustOrientationMenuItem(
JMenu menu, String description, char key, Vector3f axis)
{
addMenuItem(menu, description,
KeyStroke.getKeyStroke(key),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.adjustActiveSquareOrientation(axis);
}
});
}
/** Make a new menu item and add it to 'menu' with the given
* label and listener. */
private static void addMenuItem(JMenu menu, String itemLabel, KeyStroke accelerator,
ActionListener listener)
{
JMenuItem item = new JMenuItem(itemLabel);
item.addActionListener(listener);
if (accelerator != null) {
item.setAccelerator(accelerator);
}
menu.add(item);
}
private static JCheckBoxMenuItem addCBMenuItem(JMenu menu, String itemLabel, KeyStroke accelerator,
boolean initState, ActionListener listener)
{
JCheckBoxMenuItem cbItem =
new JCheckBoxMenuItem(itemLabel, initState);
cbItem.addActionListener(listener);
if (accelerator != null) {
cbItem.setAccelerator(accelerator);
}
menu.add(cbItem);
return cbItem;
}
/** Choose the set of stars to use. This only affects new
* squares. */
private void chooseEnabledStars()
{
StarListDialog d = new StarListDialog(this, this.enabledStars);
if (d.exec()) {
this.enabledStars = d.stars;
this.updateAndRedraw();
}
}
/** Clear out the virtual map and any dependent state. */
private void clearSurfaceSquares()
{
this.emCanvas.clearSurfaceSquares();
this.activeSquare = null;
}
/** Build a portion of the Earth's surface. Adds squares to
* 'surfaceSquares'. This works by iterating over latitude
* and longitude pairs and assuming a spherical Earth. It
* assumes the Earth is a sphere. */
public void buildSphericalEarthSurfaceWithLatLong()
{
log("building spherical Earth");
this.clearSurfaceSquares();
// Size of squares to build, in km.
float sizeKm = 1000;
// Start with an arbitrary square centered at the origin
// the 3D space, and at SF, CA in the real world.
float startLatitude = 38; // 38N
float startLongitude = -122; // 122W
SurfaceSquare startSquare = new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0), // up
sizeKm,
startLatitude,
startLongitude,
null /*base*/, null /*midpoint*/,
new Vector3f(0,0,0));
this.emCanvas.addSurfaceSquare(startSquare);
// Outer loop 1: Walk North as far as we can.
SurfaceSquare outer = startSquare;
for (float latitude = startLatitude;
latitude < 90;
latitude += 9)
{
// Go North another step.
outer = this.addSphericallyAdjacentSquare(outer, latitude, startLongitude);
// Inner loop: Walk East until we get back to
// the same longitude.
float longitude = startLongitude;
float prevLongitude = longitude;
SurfaceSquare inner = outer;
while (true) {
inner = this.addSphericallyAdjacentSquare(inner, latitude, longitude);
if (prevLongitude < outer.longitude &&
outer.longitude <= longitude) {
break;
}
prevLongitude = longitude;
longitude = FloatUtil.modulus2f(longitude+9, -180, 180);
}
}
// Outer loop 2: Walk South as far as we can.
outer = startSquare;
for (float latitude = startLatitude - 9;
latitude > -90;
latitude -= 9)
{
// Go North another step.
outer = this.addSphericallyAdjacentSquare(outer, latitude, startLongitude);
// Inner loop: Walk East until we get back to
// the same longitude.
float longitude = startLongitude;
float prevLongitude = longitude;
SurfaceSquare inner = outer;
while (true) {
inner = this.addSphericallyAdjacentSquare(inner, latitude, longitude);
if (prevLongitude < outer.longitude &&
outer.longitude <= longitude) {
break;
}
prevLongitude = longitude;
longitude = FloatUtil.modulus2f(longitude+9, -180, 180);
}
}
this.emCanvas.redrawCanvas();
log("finished building Earth; nsquares="+this.emCanvas.numSurfaceSquares());
}
/** Build the surface by walking randomly from a starting location,
* assuming a Earth is a sphere. */
public void buildSphericalEarthWithRandomWalk()
{
log("building spherical Earth by random walk");
this.clearSurfaceSquares();
// Size of squares to build, in km.
float sizeKm = 1000;
// Start with an arbitrary square centered at the origin
// the 3D space, and at SF, CA in the real world.
float startLatitude = 38; // 38N
float startLongitude = -122; // 122W
SurfaceSquare startSquare = new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0), // up
sizeKm,
startLatitude,
startLongitude,
null /*base*/, null /*midpoint*/,
new Vector3f(0,0,0));
this.emCanvas.addSurfaceSquare(startSquare);
SurfaceSquare square = startSquare;
for (int i=0; i < 1000; i++) {
// Select a random change in latitude and longitude
// of about 10 degrees.
float deltaLatitude = (float)(Math.random() * 12 - 6);
float deltaLongitude = (float)(Math.random() * 12 - 6);
// Walk in that direction, keeping latitude and longitude
// within their usual ranges. Also stay away from the poles
// since the rounding errors cause problems there.
square = this.addSphericallyAdjacentSquare(square,
FloatUtil.clampf(square.latitude + deltaLatitude, -80, 80),
FloatUtil.modulus2f(square.longitude + deltaLongitude, -180, 180));
}
this.emCanvas.redrawCanvas();
log("finished building Earth; nsquares="+this.emCanvas.numSurfaceSquares());
}
/** Given square 'old', add an adjacent square at the given
* latitude and longitude. The relative orientation of the
* new square will determined using the latitude and longitude,
* assuming a spherical shape for the Earth.
*
* This is used by the routines that build the surface using
* the sphere assumption, not those that use star observation
* data. */
private SurfaceSquare addSphericallyAdjacentSquare(
SurfaceSquare old,
float newLatitude,
float newLongitude)
{
// Calculate local East for 'old'.
Vector3f oldEast = old.north.cross(old.up).normalize();
// Calculate celestial North for 'old', which is given by
// the latitude plus geographic North.
Vector3f celestialNorth =
old.north.rotateDeg(old.latitude, oldEast);
// Get lat/long deltas.
float deltaLatitude = newLatitude - old.latitude;
float deltaLongitude = FloatUtil.modulus2f(
newLongitude - old.longitude, -180, 180);
// If we didn't move, just return the old square.
if (deltaLongitude == 0 && deltaLatitude == 0) {
return old;
}
// What we want now is to first rotate Northward
// around local East to account for change in latitude, then
// Eastward around celestial North for change in longitude.
Vector3f firstRotation = oldEast.times(-deltaLatitude);
Vector3f secondRotation = celestialNorth.times(deltaLongitude);
// But then we want to express the composition of those as a
// single rotation vector in order to call the general routine.
Vector3f combined = Vector3f.composeRotations(firstRotation, secondRotation);
// Now call into the general procedure for adding a square
// given the proper relative orientation rotation.
return addRotatedAdjacentSquare(old, newLatitude, newLongitude, combined);
}
/** Build a surface using star data rather than any presumed
* size and shape. */
public void buildEarthSurfaceFromStarData()
{
Cursor oldCursor = this.getCursor();
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
ProgressDialog<Void, Void> pd =
new ProgressDialog<Void, Void>(this,
"Building Surface with model: "+this.worldObservations.getDescription(),
new BuildSurfaceTask(EarthShape.this));
pd.exec();
}
finally {
this.setCursor(oldCursor);
}
this.emCanvas.redrawCanvas();
}
/** Task to manage construction of surface.
*
* I have to use a class rather than a simple closure so I have
* something to pass to the build routines so they can set the
* status and progress as the algorithm runs. */
private static class BuildSurfaceTask extends MySwingWorker<Void, Void>
{
private EarthShape earthShape;
public BuildSurfaceTask(EarthShape earthShape_)
{
this.earthShape = earthShape_;
}
protected Void doTask() throws Exception
{
this.earthShape.buildEarthSurfaceFromStarDataInner(this);
return null;
}
}
/** Core of 'buildEarthSurfaceFromStarData', so I can more easily
* wrap computation around it. */
public void buildEarthSurfaceFromStarDataInner(BuildSurfaceTask task)
{
log("building Earth using star data: "+this.worldObservations.getDescription());
this.clearSurfaceSquares();
// Size of squares to build, in km.
float sizeKm = 1000;
// Start at approximately my location in SF, CA. This is one of
// the locations for which I have manual data, and when we build
// the first latitude strip, that will pick up the other manual
// data points.
float latitude = 38;
float longitude = -122;
SurfaceSquare square = null;
log("buildEarth: building first square at lat="+latitude+" long="+longitude);
// First square will be placed at the 3D origin with
// its North pointed along the -Z axis.
square = new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0), // up
sizeKm,
latitude,
longitude,
null /*base*/, null /*midpoint*/,
new Vector3f(0,0,0));
this.emCanvas.addSurfaceSquare(square);
this.addMatchingData(square);
// Go East and West.
task.setStatus("Initial latitude strip at "+square.latitude);
this.buildLatitudeStrip(square, +9);
this.buildLatitudeStrip(square, -9);
// Explore in all directions until all points on
// the surface have been explored (to within 9 degrees).
this.buildLongitudeStrip(square, +9, task);
this.buildLongitudeStrip(square, -9, task);
// Reset the adjustment angle.
this.adjustOrientationDegrees = EarthShape.DEFAULT_ADJUST_ORIENTATION_DEGREES;
log("buildEarth: finished using star data; nSquares="+this.emCanvas.numSurfaceSquares());
}
/** Build squares by going North or South from a starting square
* until we add 20 or we can't add any more. At each spot, also
* build latitude strips in both directions. */
private void buildLongitudeStrip(SurfaceSquare startSquare, float deltaLatitude,
BuildSurfaceTask task)
{
float curLatitude = startSquare.latitude;
float curLongitude = startSquare.longitude;
SurfaceSquare curSquare = startSquare;
if (task.isCancelled()) {
// Bail now, rather than repeat the cancellation log message.
return;
}
while (!task.isCancelled()) {
float newLatitude = curLatitude + deltaLatitude;
if (!( -90 < newLatitude && newLatitude < 90 )) {
// Do not go past the poles.
break;
}
float newLongitude = curLongitude;
log("buildEarth: building lat="+newLatitude+" long="+newLongitude);
// Report progress.
task.setStatus("Latitude strip at "+newLatitude);
{
// +1 since we did one strip before the first call to
// buildLongitudeStrip.
float totalStrips = 180 / (float)Math.abs(deltaLatitude) + 1;
float completedStrips;
if (deltaLatitude > 0) {
completedStrips = (newLatitude - startSquare.latitude) / deltaLatitude + 1;
}
else {
completedStrips = (90 - newLatitude) / -deltaLatitude + 1;
}
float fraction = completedStrips / totalStrips;
log("progress fraction: "+fraction);
task.setProgressFraction(fraction);
}
curSquare = this.createAndAutomaticallyOrientSquare(curSquare,
newLatitude, newLongitude);
if (curSquare == null) {
log("buildEarth: could not place next square!");
break;
}
curLatitude = newLatitude;
curLongitude = newLongitude;
// Also build strips in each direction.
this.buildLatitudeStrip(curSquare, +9);
this.buildLatitudeStrip(curSquare, -9);
}
if (task.isCancelled()) {
log("surface construction canceled");
}
}
/** Build squares by going East or West from a starting square
* until we add 20 or we can't add any more. */
private void buildLatitudeStrip(SurfaceSquare startSquare, float deltaLongitude)
{
float curLatitude = startSquare.latitude;
float curLongitude = startSquare.longitude;
SurfaceSquare curSquare = startSquare;
for (int i=0; i < 20; i++) {
float newLatitude = curLatitude;
float newLongitude = FloatUtil.modulus2f(curLongitude + deltaLongitude, -180, 180);
log("buildEarth: building lat="+newLatitude+" long="+newLongitude);
curSquare = this.createAndAutomaticallyOrientSquare(curSquare,
newLatitude, newLongitude);
if (curSquare == null) {
log("buildEarth: could not place next square!");
break;
}
curLatitude = newLatitude;
curLongitude = newLongitude;
}
}
/** Create a square adjacent to 'old', positioned at the given latitude
* and longitude, with orientation changed by 'rotation'. If there is
* no change, return null. Even if not, do not add the square yet,
* just return it. */
private SurfaceSquare createRotatedAdjacentSquare(
SurfaceSquare old,
float newLatitude,
float newLongitude,
Vector3f rotation)
{
// Normalize latitude and longitude.
newLatitude = FloatUtil.clampf(newLatitude, -90, 90);
newLongitude = FloatUtil.modulus2f(newLongitude, -180, 180);
// If we didn't move, return null.
if (old.latitude == newLatitude && old.longitude == newLongitude) {
return null;
}
// Compute the new orientation vectors by rotating
// the old ones by the given amount.
Vector3f newNorth = old.north.rotateAADeg(rotation);
Vector3f newUp = old.up.rotateAADeg(rotation);
// Get observed travel details going to the new location.
TravelObservation tobs = this.worldObservations.getTravelObservation(
old.latitude, old.longitude, newLatitude, newLongitude);
// For both old and new, calculate a unit vector for the
// travel direction. Both headings are negated due to the
// right hand rule for rotation. The new to old heading is
// then flipped 180 since I want both to indicate the local
// direction from old to new.
Vector3f oldTravel = old.north.rotateDeg(-tobs.startToEndHeading, old.up);
Vector3f newTravel = newNorth.rotateDeg(-tobs.endToStartHeading + 180, newUp);
// Calculate the new square's center by going half the distance
// according to the old orientation and then half the distance
// according to the new orientation, in world coordinates.
float halfDistWorld = tobs.distanceKm / 2.0f * EarthMapCanvas.SPACE_UNITS_PER_KM;
Vector3f midPoint = old.center.plus(oldTravel.times(halfDistWorld));
Vector3f newCenter = midPoint.plus(newTravel.times(halfDistWorld));
// Make the new square and add it to the list.
SurfaceSquare ret = new SurfaceSquare(
newCenter, newNorth, newUp,
old.sizeKm,
newLatitude,
newLongitude,
old /*base*/,
midPoint,
rotation);
return ret;
}
/** Add a square adjacent to 'old', positioned at the given latitude
* and longitude, with orientation changed by 'rotation'. If we
* did not move, this returns the old square. */
private SurfaceSquare addRotatedAdjacentSquare(
SurfaceSquare old,
float newLatitude,
float newLongitude,
Vector3f rotation)
{
SurfaceSquare ret = this.createRotatedAdjacentSquare(
old, newLatitude, newLongitude, rotation);
if (ret == null) {
return old; // Did not move.
}
else {
this.emCanvas.addSurfaceSquare(ret);
}
return ret;
}
/** Get star observations for the given location, at the particular
* point in time that I am using for everything. */
private List<StarObservation> getStarObservationsFor(
float latitude, float longitude)
{
return this.worldObservations.getStarObservations(
StarObservation.unixTimeOfManualData, latitude, longitude);
}
/** Add to 'square.starObs' all entries of 'starObs' that have
* the same latitude and longitude, and also are at least
* 20 degrees above the horizon. */
private void addMatchingData(SurfaceSquare square)
{
for (StarObservation so :
this.getStarObservationsFor(square.latitude, square.longitude)) {
if (this.qualifyingStarObservation(so)) {
square.addObservation(so);
}
}
}
/** Compare star data for 'startSquare' and for the given new
* latitude and longitude. Return a rotation vector that will
* transform the orientation of 'startSquare' to match the
* best surface for a new square at the new location. The
* vector's length is the amount of rotation in degrees.
*
* Returns null if there are not enough stars in common. */
private Vector3f calcRequiredRotation(
SurfaceSquare startSquare,
float newLatitude,
float newLongitude)
{
// Set of stars visible at the start and end squares and
// above 20 degrees above the horizon.
HashMap<String, Vector3f> startStars =
getVisibleStars(startSquare.latitude, startSquare.longitude);
HashMap<String, Vector3f> endStars =
getVisibleStars(newLatitude, newLongitude);
// Current best rotation and average difference.
Vector3f currentRotation = new Vector3f(0,0,0);
// Iteratively refine the current rotation by computing the
// average correction rotation and applying it until that
// correction drops below a certain threshold.
for (int iterationCount = 0; iterationCount < 1000; iterationCount++) {
// Accumulate the vector sum of all the rotation difference
// vectors as well as the max length.
Vector3f diffSum = new Vector3f(0,0,0);
float maxDiffLength = 0;
int diffCount = 0;
for (HashMap.Entry<String, Vector3f> e : startStars.entrySet()) {
String starName = e.getKey();
Vector3f startVector = e.getValue();
Vector3f endVector = endStars.get(starName);
if (endVector == null) {
continue;
}
// Both vectors must first be rotated the way the start
// surface was rotated since its creation so that when
// we compute the final required rotation, it can be
// applied to the start surface in its existing orientation,
// not the nominal orientation that the star vectors have
// before I do this.
startVector = startVector.rotateAADeg(startSquare.rotationFromNominal);
endVector = endVector.rotateAADeg(startSquare.rotationFromNominal);
// Calculate a difference rotation vector from the
// rotated end vector to the start vector. Rotating
// the end star in one direction is like rotating
// the start terrain in the opposite direction.
Vector3f rot = endVector.rotateAADeg(currentRotation)
.rotationToBecome(startVector);
// Accumulate it.
diffSum = diffSum.plus(rot);
maxDiffLength = (float)Math.max(maxDiffLength, rot.length());
diffCount++;
}
if (diffCount < 2) {
log("reqRot: not enough stars");
return null;
}
// Calculate the average correction rotation.
Vector3f avgDiff = diffSum.times(1.0f / diffCount);
// If the correction angle is small enough, stop. For any set
// of observations, we should be able to drive the average
// difference arbitrarily close to zero (this is like finding
// the centroid, except in spherical rather than flat space).
// The real question is whether the *maximum* difference is
// large enough to indicate that the data is inconsistent.
if (avgDiff.length() < 0.001) {
log("reqRot finished: iters="+iterationCount+
" avgDiffLen="+avgDiff.length()+
" maxDiffLength="+maxDiffLength+
" diffCount="+diffCount);
if (maxDiffLength > 0.2) {
// For the data I am working with, I estimate it is
// accurate to within 0.2 degrees. Consequently,
// there should not be a max difference that large.
log("reqRot: WARNING: maxDiffLength greater than 0.2");
}
return currentRotation;
}
// Otherwise, apply it to the current rotation and
// iterate again.
currentRotation = currentRotation.plus(avgDiff);
}
log("reqRot: hit iteration limit!");
return currentRotation;
}
/** True if the given observation is available for use, meaning
* it is high enough in the sky, is enabled, and not obscured
* by light from the Sun. */
private boolean qualifyingStarObservation(StarObservation so)
{
if (this.sunIsTooHigh(so.latitude, so.longitude)) {
return false;
}
return so.elevation >= 20.0f &&
this.enabledStars.containsKey(so.name) &&
this.enabledStars.get(so.name) == true;
}
/** Return true if, at StarObservation.unixTimeOfManualData, the
* Sun is too high in the sky to see stars. This depends on
* the configurable parameter 'maximumSunElevation'. */
private boolean sunIsTooHigh(float latitude, float longitude)
{
if (!this.useSunElevation) {
return false;
}
StarObservation sun = this.worldObservations.getSunObservation(
StarObservation.unixTimeOfManualData, latitude, longitude);
if (sun == null) {
return false;
}
return sun.elevation > this.maximumSunElevation;
}
/** For every visible star vislble at the specified coordinate
* that has an elevation of at least 20 degrees,
* add it to a map from star name to azEl vector. */
private HashMap<String, Vector3f> getVisibleStars(
float latitude,
float longitude)
{
HashMap<String, Vector3f> ret = new HashMap<String, Vector3f>();
for (StarObservation so :
this.getStarObservationsFor(latitude, longitude)) {
if (this.qualifyingStarObservation(so)) {
ret.put(so.name,
Vector3f.azimuthElevationToVector(so.azimuth, so.elevation));
}
}
return ret;
}
/** Get the unit ray, in world coordinates, from the center of 'square' to
* the star recorded in 'so', which was observed at this square. */
public static Vector3f rayToStar(SurfaceSquare square, StarObservation so)
{
// Ray to star in nominal, -Z facing, coordinates.
Vector3f nominalRay =
Vector3f.azimuthElevationToVector(so.azimuth, so.elevation);
// Ray to star in world coordinates, taking into account
// how the surface is rotated.
Vector3f worldRay = nominalRay.rotateAADeg(square.rotationFromNominal);
return worldRay;
}
/** Hold results of call to 'fitOfObservations'. */
private static class ObservationStats {
/** The total variance in star observation locations from the
* indicated square to the observations of its base square as the
* average square of the deviation angles.
*
* The reason for using a sum of squares approach is to penalize large
* deviations and to ensure there is a unique "least deviated" point
* (which need not exist when using a simple sum). The reason for using
* the average is to make it easier to judge "good" or "bad" fits,
* regardless of the number of star observations in common.
*
* I use the term "variance" here because it is similar to the idea in
* statistics, except here we are measuring differences between pairs of
* observations, rather than between individual observations and the mean
* of the set. I'll then reserve "deviation", if I use it, to refer to
* the square root of the variance, by analogy with "standard deviation".
* */
public double variance;
/** Maximum separation between observations, in degrees. */
public double maxSeparation;
/** Number of pairs of stars used in comparison. */
public int numSamples;
}
/** Calculate variance and maximum separation for 'square'. Returns
* null if there is no base or there are no observations in common. */
private ObservationStats fitOfObservations(SurfaceSquare square)
{
if (square.baseSquare == null) {
return null;
}
double sumOfSquares = 0;
int numSamples = 0;
double maxSeparation = 0;
for (Map.Entry<String, StarObservation> entry : square.starObs.entrySet()) {
StarObservation so = entry.getValue();
// Ray to star in world coordinates.
Vector3f starRay = EarthShape.rayToStar(square, so);
// Calculate the deviation of this observation from that of
// the base square.
StarObservation baseObservation = square.baseSquare.findObservation(so.name);
if (baseObservation != null) {
// Get ray from base square to the base observation star
// in world coordinates.
Vector3f baseStarRay = EarthShape.rayToStar(square.baseSquare, baseObservation);
// Visual separation angle between these rays.
double sep;
if (this.assumeInfiniteStarDistance) {
sep = this.getStarRayDifference(
square.up, starRay, baseStarRay);
}
else {
sep = EarthShape.getModifiedClosestApproach(
square.center, starRay,
square.baseSquare.center, baseStarRay).separationAngleDegrees;
}
if (sep > maxSeparation) {
maxSeparation = sep;
}
// Accumulate its square.
sumOfSquares += sep * sep;
numSamples++;
}
}
if (numSamples == 0) {
return null;
}
else {
ObservationStats ret = new ObservationStats();
ret.variance = sumOfSquares / numSamples;
ret.maxSeparation = maxSeparation;
ret.numSamples = numSamples;
return ret;
}
}
/** Get closest approach, except with a modification to
* smooth out the search space. */
public static Vector3d.ClosestApproach getModifiedClosestApproach(
Vector3f p1f, Vector3f u1f,
Vector3f p2f, Vector3f u2f)
{
Vector3d p1 = new Vector3d(p1f);
Vector3d u1 = new Vector3d(u1f);
Vector3d p2 = new Vector3d(p2f);
Vector3d u2 = new Vector3d(u2f);
Vector3d.ClosestApproach ca = Vector3d.getClosestApproach(p1, u1, p2, u2);
if (ca.line1Closest != null) {
// Now, there is a problem if the closest approach is behind
// either observer. Not only does that not make logical sense,
// but naively using the calculation will cause the search
// space to be very lumpy, which creates local minima that my
// hill-climbing algorithm gets trapped in. So, we require
// that the points on each observation line be at least one
// unit away, which currently means 1000 km. That smooths out
// the search space so the hill climber will find its way to
// the optimal solution more reliably.
// How far along u1 is the closest approach?
double m1 = ca.line1Closest.minus(p1).dot(u1);
if (m1 < 1.0) {
// That is unreasonably close. Push the approach point
// out to one unit away along u1.
ca.line1Closest = p1.plus(u1);
// Find the closest point on (p2,u2) to that point.
ca.line2Closest = ca.line1Closest.closestPointOnLine(p2, u2);
// Recalculate the separation angle to that point.
ca.separationAngleDegrees = u1.separationAngleDegrees(ca.line2Closest.minus(p1));
}
// How far along u2?
double m2 = ca.line2Closest.minus(p2).dot(u2);
if (m2 < 1.0) {
// Too close; push it.
ca.line2Closest = p2.plus(u2);
// What is closest on (p1,u1) to that?
ca.line1Closest = ca.line2Closest.closestPointOnLine(p1, u1);
// Re-check if that is too close to p1.
if (ca.line1Closest.minus(p1).dot(u1) < 1.0) {
// Push it without changing line2Closest.
ca.line1Closest = p1.plus(u1);
}
// Recalculate the separation angle to that point.
ca.separationAngleDegrees = u1.separationAngleDegrees(ca.line2Closest.minus(p1));
}
}
return ca;
}
/** Get the difference between the two star rays, for a location
* with given unit 'up' vector, in degrees. This depends on the
* option setting 'onlyCompareElevations'. */
public double getStarRayDifference(
Vector3f up,
Vector3f ray1,
Vector3f ray2)
{
if (this.onlyCompareElevations) {
return EarthShape.getElevationDifference(up, ray1, ray2);
}
else {
return ray1.separationAngleDegrees(ray2);
}
}
/** Given two star observation rays at a location with the given
* 'up' unit vector, return the difference in elevation between
* them, ignoring azimuth, in degrees. */
private static double getElevationDifference(
Vector3f up,
Vector3f ray1,
Vector3f ray2)
{
double e1 = getElevation(up, ray1);
double e2 = getElevation(up, ray2);
return Math.abs(e1-e2);
}
/** Return the elevation of 'ray' at a location with unit 'up'
* vector, in degrees. */
private static double getElevation(Vector3f up, Vector3f ray)
{
// Decompose into vertical and horizontal components.
Vector3f v = ray.projectOntoUnitVector(up);
Vector3f h = ray.minus(v);
// Get lengths, with vertical possibly negative if below
// horizon.
double vLen = ray.dot(up);
double hLen = h.length();
// Calculate corresponding angle.
return FloatUtil.atan2Deg(vLen, hLen);
}
/** Begin constructing a new surface using star data. This just
* places down the initial square to represent a user-specified
* latitude and longitude. The square is placed into 3D space
* at a fixed location. */
public void startNewSurface()
{
LatLongDialog d = new LatLongDialog(this, 38, -122);
if (d.exec()) {
this.startNewSurfaceAt(d.finalLatitude, d.finalLongitude);
}
}
/** Same as 'startNewSurface' but at a specified location. */
public void startNewSurfaceAt(float latitude, float longitude)
{
log("starting new surface at lat="+latitude+", lng="+longitude);
this.clearSurfaceSquares();
this.setActiveSquare(new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0), // up
INITIAL_SQUARE_SIZE_KM,
latitude,
longitude,
null /*base*/, null /*midpoint*/,
new Vector3f(0,0,0)));
this.addMatchingData(this.activeSquare);
this.emCanvas.addSurfaceSquare(this.activeSquare);
this.emCanvas.redrawCanvas();
}
/** Get the active square, or null if none. */
public SurfaceSquare getActiveSquare()
{
return this.activeSquare;
}
/** Change which square is active, but do not trigger a redraw. */
public void setActiveSquareNoRedraw(SurfaceSquare sq)
{
if (this.activeSquare != null) {
this.activeSquare.showAsActive = false;
}
this.activeSquare = sq;
if (this.activeSquare != null) {
this.activeSquare.showAsActive = true;
}
}
/** Change which square is active. */
public void setActiveSquare(SurfaceSquare sq)
{
this.setActiveSquareNoRedraw(sq);
this.updateAndRedraw();
}
/** Add another square to the surface by building one adjacent
* to the active square. */
private void buildNextSquare()
{
if (this.activeSquare == null) {
this.errorBox("No square is active.");
return;
}
LatLongDialog d = new LatLongDialog(this,
this.activeSquare.latitude, this.activeSquare.longitude + 9);
if (d.exec()) {
this.buildNextSquareAt(d.finalLatitude, d.finalLongitude);
}
}
/** Same as 'buildNextSquare' except at a specified location. */
private void buildNextSquareAt(float latitude, float longitude)
{
// The new square should draw star rays if the old did.
boolean drawStarRays = this.activeSquare.drawStarRays;
// Add it initially with no rotation. My plan is to add
// the rotation interactively afterward.
this.setActiveSquare(
this.addRotatedAdjacentSquare(this.activeSquare,
latitude, longitude, new Vector3f(0,0,0)));
this.activeSquare.drawStarRays = drawStarRays;
// Reset the rotation angle after adding a square.
this.adjustOrientationDegrees = DEFAULT_ADJUST_ORIENTATION_DEGREES;
this.addMatchingData(this.activeSquare);
this.emCanvas.redrawCanvas();
}
/** If there is an active square, assume we just built it, and now
* we want to adjust its orientation. 'axis' indicates the axis
* about which to rotate, relative to the square's current orientation,
* where -Z is North, +Y is up, and +X is east, and the angle is given
* by 'this.adjustOrientationDegrees'. */
private void adjustActiveSquareOrientation(Vector3f axis)
{
SurfaceSquare derived = this.activeSquare;
if (derived == null) {
this.errorBox("No active square.");
return;
}
SurfaceSquare base = derived.baseSquare;
if (base == null) {
this.errorBox("The active square has no base square.");
return;
}
// Replace the active square.
this.setActiveSquare(
this.adjustDerivedSquareOrientation(axis, derived, this.adjustOrientationDegrees));
this.emCanvas.redrawCanvas();
}
/** Adjust the orientation of 'derived' by 'adjustDegrees' around
* 'axis', where 'axis' is relative to the square's current
* orientation. */
private SurfaceSquare adjustDerivedSquareOrientation(Vector3f axis,
SurfaceSquare derived, float adjustDegrees)
{
SurfaceSquare base = derived.baseSquare;
// Rotate by 'adjustOrientationDegrees'.
Vector3f angleAxis = axis.times(adjustDegrees);
// Rotate the axis to align it with the square.
angleAxis = angleAxis.rotateAADeg(derived.rotationFromNominal);
// Now add that to the square's existing rotation relative
// to its base square.
angleAxis = Vector3f.composeRotations(derived.rotationFromBase, angleAxis);
// Now, replace it.
return this.replaceWithNewRotation(base, derived, angleAxis);
}
/** Replace the square 'derived', with a new square that
* is computed from 'base' by applying 'newRotation'.
* Return the new square. */
public SurfaceSquare replaceWithNewRotation(
SurfaceSquare base, SurfaceSquare derived, Vector3f newRotation)
{
// Replace the derived square with a new one created by
// rotating from the same base by this new amount.
this.emCanvas.removeSurfaceSquare(derived);
SurfaceSquare ret =
this.addRotatedAdjacentSquare(base,
derived.latitude, derived.longitude, newRotation);
// Copy some other data from the derived square that we
// are in the process of discarding.
ret.drawStarRays = derived.drawStarRays;
ret.starObs = derived.starObs;
return ret;
}
/** Calculate what the variation of observations would be for
* 'derived' if its orientation were adjusted by
* 'angleAxis.degrees()' around 'angleAxis'. Returns null if
* the calculation cannot be done because of missing information. */
private ObservationStats fitOfAdjustedSquare(
SurfaceSquare derived, Vector3f angleAxis)
{
// This part mirrors 'adjustActiveSquareOrientation'.
SurfaceSquare base = derived.baseSquare;
if (base == null) {
return null;
}
angleAxis = angleAxis.rotateAADeg(derived.rotationFromNominal);
angleAxis = Vector3f.composeRotations(derived.rotationFromBase, angleAxis);
// Now, create a new square with this new rotation.
SurfaceSquare newSquare =
this.createRotatedAdjacentSquare(base,
derived.latitude, derived.longitude, angleAxis);
if (newSquare == null) {
// If we do not move, use the original square's data.
return this.fitOfObservations(derived);
}
// Copy the observation data since that is needed to calculate
// the deviation.
newSquare.starObs = derived.starObs;
// Now calculate the new variance.
return this.fitOfObservations(newSquare);
}
/** Like 'fitOfAdjustedSquare' except only retrieves the
* variance. This returns 40000 if the data is unavailable. */
private double varianceOfAdjustedSquare(
SurfaceSquare derived, Vector3f angleAxis)
{
ObservationStats os = this.fitOfAdjustedSquare(derived, angleAxis);
if (os == null) {
// The variance should never be greater than 180 squared,
// since that would be the worst possible fit for a star.
return 40000;
}
else {
return os.variance;
}
}
/** Change 'adjustOrientationDegrees' by the given multiplier. */
private void changeAdjustOrientationDegrees(float multiplier)
{
this.adjustOrientationDegrees *= multiplier;
if (this.adjustOrientationDegrees < MINIMUM_ADJUST_ORIENTATION_DEGREES) {
this.adjustOrientationDegrees = MINIMUM_ADJUST_ORIENTATION_DEGREES;
}
this.updateUIState();
}
/** Compute and apply a single step rotation command to improve
* the variance of the active square. */
private void applyRecommendedRotationCommand()
{
SurfaceSquare s = this.activeSquare;
if (s == null) {
this.errorBox("No active square.");
return;
}
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null) {
this.errorBox("Not enough observational data available.");
return;
}
if (ostats.variance == 0) {
this.errorBox("Orientation is already optimal.");
return;
}
// Get the recommended rotation.
VarianceAfterRotations var = this.getVarianceAfterRotations(s,
this.adjustOrientationDegrees);
if (var.bestRC == null) {
if (this.adjustOrientationDegrees <= MINIMUM_ADJUST_ORIENTATION_DEGREES) {
this.errorBox("Cannot further improve orientation.");
return;
}
else {
this.changeAdjustOrientationDegrees(0.5f);
}
}
else {
this.adjustActiveSquareOrientation(var.bestRC.axis);
}
this.updateAndRedraw();
}
/** Apply the recommended rotation to 's' until convergence. Return
* the improved square, or null if that is not possible due to
* insufficient constraints. */
private SurfaceSquare repeatedlyApplyRecommendedRotationCommand(SurfaceSquare s)
{
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null || ostats.numSamples < 2) {
return null; // Underconstrained.
}
if (ostats.variance == 0) {
return s; // Already optimal.
}
// Rotation amount. This will be gradually reduced.
float adjustDegrees = 1.0f;
// Iteration cap for safety.
int iters = 0;
// Iterate until the adjust amount is too small.
while (adjustDegrees > MINIMUM_ADJUST_ORIENTATION_DEGREES) {
// Get the recommended rotation.
VarianceAfterRotations var = this.getVarianceAfterRotations(s, adjustDegrees);
if (var == null) {
return null;
}
if (var.underconstrained) {
log("repeatedlyApply: solution is underconstrained, adjustDegrees="+ adjustDegrees);
return s;
}
if (var.bestRC == null) {
adjustDegrees = adjustDegrees * 0.5f;
// Set the UI adjust degrees to what we came up with here so I
// can easily see where it ended up.
this.adjustOrientationDegrees = adjustDegrees;
}
else {
s = this.adjustDerivedSquareOrientation(var.bestRC.axis, s, adjustDegrees);
}
if (++iters > 1000) {
log("repeatedlyApply: exceeded iteration cap!");
break;
}
}
// Get the final variance.
String finalVariance = "null";
ostats = this.fitOfObservations(s);
if (ostats != null) {
finalVariance = ""+ostats.variance;
}
log("repeatedlyApply done: iters="+iters+" adj="+ adjustDegrees+
" var="+finalVariance);
return s;
}
/** Delete the active square. */
private void deleteActiveSquare()
{
if (this.activeSquare == null) {
this.errorBox("No active square.");
return;
}
this.emCanvas.removeSurfaceSquare(this.activeSquare);
this.setActiveSquare(null);
}
/** Calculate and apply the optimal orientation for the active square;
* make its replacement active if we do replace it.. */
private void automaticallyOrientActiveSquare()
{
SurfaceSquare derived = this.activeSquare;
if (derived == null) {
this.errorBox("No active square.");
return;
}
SurfaceSquare base = derived.baseSquare;
if (base == null) {
this.errorBox("The active square has no base square.");
return;
}
SurfaceSquare newDerived = automaticallyOrientSquare(derived);
if (newDerived == null) {
this.errorBox("Insufficient observations to determine proper orientation.");
}
else {
this.setActiveSquare(newDerived);
}
this.updateAndRedraw();
}
/** Given a square 'derived' that is known to have a base square,
* adjust and/or replace it with one with a better orientation,
* and return the improved square. Returns null if improvement
* is not possible due to insufficient observational data. */
private SurfaceSquare automaticallyOrientSquare(SurfaceSquare derived)
{
if (this.newAutomaticOrientationAlgorithm) {
return this.repeatedlyApplyRecommendedRotationCommand(derived);
}
else {
// Calculate the best rotation.
Vector3f rot = calcRequiredRotation(derived.baseSquare,
derived.latitude, derived.longitude);
if (rot == null) {
return null;
}
// Now, replace the active square.
return this.replaceWithNewRotation(derived.baseSquare, derived, rot);
}
}
/** Make the next square in 'emCanvas.surfaceSquares' active. */
private void selectNextSquare(boolean forward)
{
this.setActiveSquare(this.emCanvas.getNextSquare(this.activeSquare, forward));
}
/** Build a square offset from the active square, set its orientation,
* and make it active. If we cannot make a new square, report that as
* an error and leave the active square alone. */
private void createAndAutomaticallyOrientActiveSquare(
float deltaLatitude, float deltaLongitude)
{
SurfaceSquare base = this.activeSquare;
if (base == null) {
this.errorBox("There is no active square.");
return;
}
SurfaceSquare newSquare = this.createAndAutomaticallyOrientSquare(
base, base.latitude + deltaLatitude, base.longitude + deltaLongitude);
if (newSquare == null) {
ModalDialog.errorBox(this,
"Cannot place new square since observational data does not uniquely determine its orientation.");
}
else {
newSquare.drawStarRays = base.drawStarRays;
this.setActiveSquare(newSquare);
}
}
/** Build a square adjacent to the base square, set its orientation,
* and return it. Returns null and adds nothing if such a square
* cannot be uniquely oriented. */
private SurfaceSquare createAndAutomaticallyOrientSquare(SurfaceSquare base,
float newLatitude, float newLongitude)
{
// Make a new adjacent square, initially with the same orientation
// as the base square.
SurfaceSquare newSquare =
this.addRotatedAdjacentSquare(base,
newLatitude,
newLongitude,
new Vector3f(0,0,0));
if (base == newSquare) {
return base; // Did not move, no new square created.
}
this.addMatchingData(newSquare);
// Now try to set its orientation to match observations.
SurfaceSquare adjustedSquare = this.automaticallyOrientSquare(newSquare);
if (adjustedSquare == null) {
// No unique solution; remove the new square too.
this.emCanvas.removeSurfaceSquare(newSquare);
}
return adjustedSquare;
}
/** Show the user what the local rotation space looks like by.
* considering the effect of rotating various amounts on each axis. */
private void analyzeSolutionSpace()
{
if (this.activeSquare == null) {
this.errorBox("No active square.");
return;
}
SurfaceSquare s = this.activeSquare;
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null) {
this.errorBox("No observation fitness stats for the active square.");
return;
}
// Prepare a task object in which to run the analysis.
AnalysisTask task = new AnalysisTask(this, s);
// Show a progress dialog while this run.
ProgressDialog<PlotData3D, Void> progressDialog =
new ProgressDialog<PlotData3D, Void>(this,
"Analyzing rotations of active square...", task);
// Run the dialog and the task.
if (progressDialog.exec()) {
// Retrieve the computed data.
PlotData3D rollPitchYawPlotData;
try {
rollPitchYawPlotData = task.get();
}
catch (Exception e) {
String msg = "Internal error: solution space analysis failed: "+e.getMessage();
log(msg);
e.printStackTrace();
this.errorBox(msg);
return;
}
// Plot results.
RotationCubeDialog d = new RotationCubeDialog(this,
(float)ostats.variance,
rollPitchYawPlotData);
d.exec();
}
else {
log("Analysis canceled.");
}
}
/** Task to analyze the solution space near a square, which can take a
* while if 'solutionAnalysisPointsPerSide' is high. */
private static class AnalysisTask extends MySwingWorker<PlotData3D, Void> {
/** Enclosing EarthShape instance. */
private EarthShape earthShape;
/** Square whose solution will be analyzed. */
private SurfaceSquare square;
public AnalysisTask(
EarthShape earthShape_,
SurfaceSquare square_)
{
this.earthShape = earthShape_;
this.square = square_;
}
@Override
protected PlotData3D doTask() throws Exception
{
return this.earthShape.getThreeRotationAxisPlotData(this.square, this);
}
}
/** Get data for various rotation angles of all three axes.
*
* This runs in a worker thread. However, I haven't bothered
* to synchronize access since the user shouldn't be able to
* do anything while this is happening (although they can...),
* and most of the shared data is immutable. */
private PlotData3D getThreeRotationAxisPlotData(SurfaceSquare s, AnalysisTask task)
{
// Number of data points on each side of 0.
int pointsPerSide = this.solutionAnalysisPointsPerSide;
// Total number of data points per axis, including 0.
int pointsPerAxis = pointsPerSide * 2 + 1;
// Complete search space cube.
float[] wData = new float[pointsPerAxis * pointsPerAxis * pointsPerAxis];
Vector3f xAxis = new Vector3f(0, 0, -1); // Roll
Vector3f yAxis = new Vector3f(1, 0, 0); // Pitch
Vector3f zAxis = new Vector3f(0, -1, 0); // Yaw
float xFirst = -pointsPerSide * this.adjustOrientationDegrees;
float xLast = pointsPerSide * this.adjustOrientationDegrees;
float yFirst = -pointsPerSide * this.adjustOrientationDegrees;
float yLast = pointsPerSide * this.adjustOrientationDegrees;
float zFirst = -pointsPerSide * this.adjustOrientationDegrees;
float zLast = pointsPerSide * this.adjustOrientationDegrees;
for (int zIndex=0; zIndex < pointsPerAxis; zIndex++) {
if (task.isCancelled()) {
log("analysis canceled");
return null; // Bail out.
}
task.setProgressFraction(zIndex / (float)pointsPerAxis);
task.setStatus("Analyzing plane "+(zIndex+1)+" of "+pointsPerAxis);
for (int yIndex=0; yIndex < pointsPerAxis; yIndex++) {
for (int xIndex=0; xIndex < pointsPerAxis; xIndex++) {
// Compose rotations about each axis: X then Y then Z.
//
// Note: Rotations don't commute, so the axes are not
// being treated perfectly symmetrically here, but this
// is still good for showing overall shape, and when
// we zoom in to small angles, the non-commutativity
// becomes insignificant.
Vector3f rotX = xAxis.times(this.adjustOrientationDegrees * (xIndex - pointsPerSide));
Vector3f rotY = yAxis.times(this.adjustOrientationDegrees * (yIndex - pointsPerSide));
Vector3f rotZ = zAxis.times(this.adjustOrientationDegrees * (zIndex - pointsPerSide));
Vector3f rot = Vector3f.composeRotations(
Vector3f.composeRotations(rotX, rotY), rotZ);
// Get variance after that adjustment.
wData[xIndex + pointsPerAxis * yIndex + pointsPerAxis * pointsPerAxis * zIndex] =
(float)this.varianceOfAdjustedSquare(s, rot);
}
}
}
return new PlotData3D(
xFirst, xLast,
yFirst, yLast,
zFirst, zLast,
pointsPerAxis /*xValuesPerRow*/,
pointsPerAxis /*yValuesPerColumn*/,
wData);
}
/** Show a dialog to let the user change
* 'solutionAnalysisPointsPerSide'. */
private void setSolutionAnalysisResolution()
{
String choice = JOptionPane.showInputDialog(this,
"Specify number of data points on each side of 0 to sample "+
"when performing a solution analysis",
(Integer)this.solutionAnalysisPointsPerSide);
if (choice != null) {
try {
int c = Integer.valueOf(choice);
if (c < 1) {
this.errorBox("The minimum number of points is 1.");
}
else if (c > 100) {
// At 100, it will take about a minute to complete.
this.errorBox("The maximum number of points is 100.");
}
else {
this.solutionAnalysisPointsPerSide = c;
}
}
catch (NumberFormatException e) {
this.errorBox("Invalid integer syntax: "+e.getMessage());
}
}
}
/** Prompt the user for a floating-point value. Returns null if the
* user cancels or enters an invalid value. In the latter case, an
* error box has already been shown. */
private Float floatInputDialog(String label, float curValue)
{
String choice = JOptionPane.showInputDialog(this, label, (Float)curValue);
if (choice != null) {
try {
return Float.valueOf(choice);
}
catch (NumberFormatException e) {
this.errorBox("Invalid float syntax: "+e.getMessage());
return null;
}
}
else {
return null;
}
}
/** Let the user specify a new maximum Sun elevation. */
private void setMaximumSunElevation()
{
Float newValue = this.floatInputDialog(
"Specify maximum elevation of the Sun in degrees "+
"above the horizon (otherwise, stars are not visible)",
this.maximumSunElevation);
if (newValue != null) {
this.maximumSunElevation = newValue;
}
}
/** Let the user specify the distance to the skybox. */
private void setSkyboxDistance()
{
Float newValue = this.floatInputDialog(
"Specify distance in 3D space units (each of which usually "+
"represents 1000km of surface) to the skybox.\n"+
"A value of 0 means the skybox is infinitely far away.",
this.emCanvas.skyboxDistance);
if (newValue != null) {
if (newValue < 0) {
this.errorBox("The skybox distance must be non-negative.");
}
else {
this.emCanvas.skyboxDistance = newValue;
this.updateAndRedraw();
}
}
}
/** Make this window visible. */
public void makeVisible()
{
this.setVisible(true);
// It seems I can only set the focus once the window is
// visible. There is an example in the focus tutorial of
// calling pack() first, but that resizes the window and
// I don't want that.
this.emCanvas.setFocusOnCanvas();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
(new EarthShape()).makeVisible();
}
});
}
public void toggleDrawAxes()
{
this.emCanvas.drawAxes = !this.emCanvas.drawAxes;
this.updateAndRedraw();
}
public void toggleDrawCrosshair()
{
this.emCanvas.drawCrosshair = !this.emCanvas.drawCrosshair;
this.updateAndRedraw();
}
/** Toggle the 'drawWireframeSquares' flag. */
public void toggleDrawWireframeSquares()
{
this.emCanvas.drawWireframeSquares = !this.emCanvas.drawWireframeSquares;
this.updateAndRedraw();
}
/** Toggle the 'drawCompasses' flag, then update state and redraw. */
public void toggleDrawCompasses()
{
log("toggleDrawCompasses");
// The compass flag is ignored when wireframe is true, so if
// we are toggling compass, also clear wireframe.
this.emCanvas.drawWireframeSquares = false;
this.emCanvas.drawCompasses = !this.emCanvas.drawCompasses;
this.updateAndRedraw();
}
/** Toggle the 'drawSurfaceNormals' flag. */
public void toggleDrawSurfaceNormals()
{
this.emCanvas.drawSurfaceNormals = !this.emCanvas.drawSurfaceNormals;
this.updateAndRedraw();
}
/** Toggle the 'drawCelestialNorth' flag. */
public void toggleDrawCelestialNorth()
{
this.emCanvas.drawCelestialNorth = !this.emCanvas.drawCelestialNorth;
this.updateAndRedraw();
}
/** Toggle the 'drawStarRays' flag. */
public void toggleDrawStarRays()
{
if (this.activeSquare == null) {
this.errorBox("No square is active");
}
else {
this.activeSquare.drawStarRays = !this.activeSquare.drawStarRays;
}
this.emCanvas.redrawCanvas();
}
private void toggleDrawUnitStarRays()
{
this.emCanvas.drawUnitStarRays = !this.emCanvas.drawUnitStarRays;
this.updateAndRedraw();
}
private void toggleDrawBaseSquareStarRays()
{
this.emCanvas.drawBaseSquareStarRays = !this.emCanvas.drawBaseSquareStarRays;
this.updateAndRedraw();
}
private void toggleDrawTravelPath()
{
this.emCanvas.drawTravelPath = !this.emCanvas.drawTravelPath;
this.updateAndRedraw();
}
private void toggleDrawActiveSquareAtOrigin()
{
this.emCanvas.drawActiveSquareAtOrigin = !this.emCanvas.drawActiveSquareAtOrigin;
this.updateAndRedraw();
}
private void toggleDrawWorldWireframe()
{
this.emCanvas.drawWorldWireframe = !this.emCanvas.drawWorldWireframe;
this.updateAndRedraw();
}
private void toggleDrawWorldStars()
{
this.emCanvas.drawWorldStars = !this.emCanvas.drawWorldStars;
this.updateAndRedraw();
}
private void toggleDrawSkybox()
{
this.emCanvas.drawSkybox = !this.emCanvas.drawSkybox;
this.updateAndRedraw();
}
private void turnOffAllStarRays()
{
this.emCanvas.turnOffAllStarRays();
this.emCanvas.redrawCanvas();
}
/** Move the camera to the center of the active square. */
private void goToActiveSquareCenter()
{
if (this.activeSquare == null) {
this.errorBox("No active square.");
}
else {
this.moveCamera(this.activeSquare.center);
}
}
/** Place the camera at the specified location. */
private void moveCamera(Vector3f loc)
{
this.emCanvas.cameraPosition = loc;
this.updateAndRedraw();
}
/** Update all stateful UI elements. */
public void updateUIState()
{
this.setStatusLabel();
this.setMenuState();
this.setInfoPanel();
}
/** Set the status label text to reflect other state variables.
* This also updates the state of stateful menu items. */
private void setStatusLabel()
{
StringBuilder sb = new StringBuilder();
sb.append(this.emCanvas.getStatusString());
sb.append(", model="+this.worldObservations.getDescription());
this.statusLabel.setText(sb.toString());
}
/** Set the state of stateful menu items. */
private void setMenuState()
{
this.drawCoordinateAxesCBItem.setSelected(this.emCanvas.drawAxes);
this.drawCrosshairCBItem.setSelected(this.emCanvas.drawCrosshair);
this.drawWireframeSquaresCBItem.setSelected(this.emCanvas.drawWireframeSquares);
this.drawCompassesCBItem.setSelected(this.emCanvas.drawCompasses);
this.drawSurfaceNormalsCBItem.setSelected(this.emCanvas.drawSurfaceNormals);
this.drawCelestialNorthCBItem.setSelected(this.emCanvas.drawCelestialNorth);
this.drawStarRaysCBItem.setSelected(this.activeSquareDrawsStarRays());
this.drawUnitStarRaysCBItem.setSelected(this.emCanvas.drawUnitStarRays);
this.drawBaseSquareStarRaysCBItem.setSelected(this.emCanvas.drawBaseSquareStarRays);
this.drawTravelPathCBItem.setSelected(this.emCanvas.drawTravelPath);
this.drawActiveSquareAtOriginCBItem.setSelected(this.emCanvas.drawActiveSquareAtOrigin);
this.drawWorldWireframeCBItem.setSelected(this.emCanvas.drawWorldWireframe);
this.drawWorldStarsCBItem.setSelected(this.emCanvas.drawWorldStars);
this.drawSkyboxCBItem.setSelected(this.emCanvas.drawSkybox);
this.useSunElevationCBItem.setSelected(this.useSunElevation);
this.invertHorizontalCameraMovementCBItem.setSelected(
this.emCanvas.invertHorizontalCameraMovement);
this.invertVerticalCameraMovementCBItem.setSelected(
this.emCanvas.invertVerticalCameraMovement);
this.newAutomaticOrientationAlgorithmCBItem.setSelected(
this.newAutomaticOrientationAlgorithm);
this.assumeInfiniteStarDistanceCBItem.setSelected(
this.assumeInfiniteStarDistance);
this.onlyCompareElevationsCBItem.setSelected(
this.onlyCompareElevations);
}
/** Update the contents of the info panel. */
private void setInfoPanel()
{
StringBuilder sb = new StringBuilder();
if (this.emCanvas.activeSquareAnimationState != 0) {
sb.append("Animation state: "+this.emCanvas.activeSquareAnimationState+"\n");
}
if (this.activeSquare == null) {
sb.append("No active square.\n");
}
else {
sb.append("Active square:\n");
SurfaceSquare s = this.activeSquare;
sb.append(" lat/lng: ("+s.latitude+","+s.longitude+")\n");
sb.append(" pos: "+s.center+"\n");
sb.append(" rot: "+s.rotationFromNominal+"\n");
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null) {
sb.append(" No obs stats\n");
}
else {
sb.append(" maxSep: "+ostats.maxSeparation+"\n");
sb.append(" sqrtVar: "+(float)Math.sqrt(ostats.variance)+"\n");
sb.append(" var: "+ostats.variance+"\n");
// What do we recommend to improve the variance? If it is
// already zero, nothing. Otherwise, start by thinking we
// should decrease the rotation angle.
char recommendation = (ostats.variance == 0? ' ' : '-');
// What is the best rotation command, and what does it achieve?
VarianceAfterRotations var = this.getVarianceAfterRotations(s,
this.adjustOrientationDegrees);
// Print the effects of all the available rotations.
sb.append("\n");
for (RotationCommand rc : RotationCommand.values()) {
sb.append(" adj("+rc.key+"): ");
Double newVariance = var.rcToVariance.get(rc);
if (newVariance == null) {
sb.append("(none)\n");
}
else {
sb.append(""+newVariance+"\n");
}
}
// Make a final recommendation.
if (var.bestRC != null) {
recommendation = var.bestRC.key;
}
sb.append(" recommend: "+recommendation+"\n");
}
}
sb.append("\n");
sb.append("adjDeg: "+this.adjustOrientationDegrees+"\n");
// Compute average curvature from base.
if (this.activeSquare != null && this.activeSquare.baseSquare != null) {
sb.append("\n");
sb.append("Base at: ("+this.activeSquare.baseSquare.latitude+
","+this.activeSquare.baseSquare.longitude+")\n");
CurvatureCalculator cc = this.computeAverageCurvature(this.activeSquare);
double normalCurvatureDegPer1000km =
FloatUtil.radiansToDegrees(cc.normalCurvature*1000);
sb.append("Normal curvature: "+(float)normalCurvatureDegPer1000km+" deg per 1000 km\n");
if (cc.normalCurvature != 0) {
sb.append("Radius: "+(float)(1/cc.normalCurvature)+" km\n");
}
else {
sb.append("Radius: Infinite\n");
}
sb.append("Geodesic curvature: "+(float)(cc.geodesicCurvature*1000.0)+" deg per 1000 km\n");
sb.append("Geodesic torsion: "+(float)(cc.geodesicTorsion*1000.0)+" deg per 1000 km\n");
}
// Also show star observation data.
if (this.activeSquare != null) {
sb.append("\n");
sb.append("Visible stars (az, el):\n");
// Iterate over stars in name order.
TreeSet<String> stars = new TreeSet<String>(this.activeSquare.starObs.keySet());
for (String starName : stars) {
StarObservation so = this.activeSquare.starObs.get(starName);
sb.append(" "+so.name+": "+so.azimuth+", "+so.elevation+"\n");
}
}
this.infoPanel.setText(sb.toString());
}
/** Compute the average curvature on a path from the base square
* of 's' to 's'. */
private CurvatureCalculator computeAverageCurvature(SurfaceSquare s)
{
// Travel distance and heading.
TravelObservation tobs = this.worldObservations.getTravelObservation(
s.baseSquare.latitude, s.baseSquare.longitude,
s.latitude, s.longitude);
// Unit travel vector in base square coordinate system.
Vector3f startTravel = Vector3f.headingToVector((float)tobs.startToEndHeading);
startTravel = startTravel.rotateAADeg(s.baseSquare.rotationFromNominal);
// And at derived square.
Vector3f endTravel = Vector3f.headingToVector((float)tobs.endToStartHeading + 180);
endTravel = endTravel.rotateAADeg(s.rotationFromNominal);
// Calculate curvature and twist.
CurvatureCalculator c = new CurvatureCalculator();
c.distanceKm = tobs.distanceKm;
c.computeFromNormals(s.baseSquare.up, s.up, startTravel, endTravel);
return c;
}
/** Result of call to 'getVarianceAfterRotations'. */
private static class VarianceAfterRotations {
/** Variance produced by each rotation. The value can be null,
* meaning the rotation produces a situation where we can't
* measure the variance (e.g., because not enough stars are
* above the horizon). */
public HashMap<RotationCommand, Double> rcToVariance = new HashMap<RotationCommand, Double>();
/** Which rotation command produces the greatest improvement
* in variance, if any. */
public RotationCommand bestRC = null;
/** If true, the solution space is underconstrained, meaning
* the best orientation is not unique. */
public boolean underconstrained = false;
}
/** Perform a trial rotation in each direction and record the
* resulting variance, plus a decision about which is best, if any.
* This returns null if we do not have enough data to measure
* the fitness of the square's orientation. */
private VarianceAfterRotations getVarianceAfterRotations(SurfaceSquare s,
float adjustDegrees)
{
// Get variance if no rotation is performed. We only recommend
// a rotation if it improves on this.
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null) {
return null;
}
VarianceAfterRotations ret = new VarianceAfterRotations();
// Variance achieved by the best rotation command, if there is one.
double bestNewVariance = 0;
// Get the effects of all the available rotations.
for (RotationCommand rc : RotationCommand.values()) {
ObservationStats newStats = this.fitOfAdjustedSquare(s,
rc.axis.times(adjustDegrees));
if (newStats == null || newStats.numSamples < 2) {
ret.rcToVariance.put(rc, null);
}
else {
double newVariance = newStats.variance;
ret.rcToVariance.put(rc, newVariance);
if (ostats.variance == 0 && newVariance == 0) {
// The current orientation is ideal, but here
// is a rotation that keeps it ideal. That
// must mean that the solution space is under-
// constrained.
//
// Note: This is an unnecessarily strong condition for
// being underconstrained. It requires that we
// find a zero in the objective function, and
// furthermore that the solution space be parallel
// to one of the three local rotation axes. I have
// some ideas for more robust detection of underconstraint,
// but haven't tried to implement them yet. For now I
// will rely on manual inspection of the rotation cube
// analysis dialog.
ret.underconstrained = true;
}
if (newVariance < ostats.variance &&
(ret.bestRC == null || newVariance < bestNewVariance))
{
ret.bestRC = rc;
bestNewVariance = newVariance;
}
}
}
return ret;
}
/** True if there is an active square and it is drawing star rays. */
private boolean activeSquareDrawsStarRays()
{
return this.activeSquare != null &&
this.activeSquare.drawStarRays;
}
/** Replace the current observations with a new source and clear
* the virtual map. */
private void changeObservations(WorldObservations obs)
{
this.clearSurfaceSquares();
this.worldObservations = obs;
// Enable all stars in the new model.
this.enabledStars.clear();
for (String starName : this.worldObservations.getAllStars()) {
this.enabledStars.put(starName, true);
}
this.updateAndRedraw();
}
/** Refresh all the UI elements and the map canvas. */
private void updateAndRedraw()
{
this.updateUIState();
this.emCanvas.redrawCanvas();
}
/** Return true if the named star is enabled. */
public boolean isStarEnabled(String starName)
{
return this.enabledStars.containsKey(starName) &&
this.enabledStars.get(starName).equals(true);
}
/** Do some initial steps so I do not have to do them manually each
* time I start the program when I'm working on a certain feature.
* The exact setup here will vary over time as I work on different
* things; it is only meant for use while testing or debugging. */
private void doCannedSetup()
{
// Disable all stars except for Betelgeuse and Dubhe.
this.enabledStars.clear();
for (String starName : this.worldObservations.getAllStars()) {
boolean en = (starName.equals("Betelgeuse") || starName.equals("Dubhe"));
this.enabledStars.put(starName, en);
}
// Build first square in SF as usual.
this.startNewSurfaceAt(38, -122);
// Build next near Washington, DC.
this.buildNextSquareAt(38, -77);
// The plan is to align with just two stars, so we need this.
this.assumeInfiniteStarDistance = true;
// Position the camera to see DC square.
if (this.emCanvas.drawActiveSquareAtOrigin) {
// This is a canned command in the middle of a session.
// Do not reposition the camera.
}
else {
this.emCanvas.drawActiveSquareAtOrigin = true;
// this.emCanvas.cameraPosition = new Vector3f(-0.19f, 0.56f, 1.20f);
// this.emCanvas.cameraAzimuthDegrees = 0.0f;
// this.emCanvas.cameraPitchDegrees = -11.0f;
this.emCanvas.cameraPosition = new Vector3f(-0.89f, 0.52f, -1.06f);
this.emCanvas.cameraAzimuthDegrees = 214.0f;
this.emCanvas.cameraPitchDegrees = 1.0f;
}
// Use wireframes for squares, no world wireframe, but add surface normals.
this.emCanvas.drawWireframeSquares = true;
this.emCanvas.drawWorldWireframe = false;
this.emCanvas.drawSurfaceNormals = true;
this.emCanvas.drawTravelPath = false;
// Show its star rays, and those at SF, as unit vectors.
this.activeSquare.drawStarRays = true;
this.emCanvas.drawBaseSquareStarRays = true;
this.emCanvas.drawUnitStarRays = true;
// Reset the animation.
this.emCanvas.activeSquareAnimationState = 0;
this.updateAndRedraw();
}
/** Set the animation state either to 0, or to an amount
* offset by 's'. */
private void setAnimationState(int s)
{
if (s == 0) {
this.emCanvas.activeSquareAnimationState = 0;
}
else {
this.emCanvas.activeSquareAnimationState += s;
}
this.updateAndRedraw();
}
// ------------------------------- Animation --------------------------------
/** When animation begins, this is the rotation of the active
* square relative to its base. */
private Vector3f animatedRotationStartRotation;
/** Angle through which to rotate the active square. */
private double animatedRotationAngle;
/** Axis about which to rotate the active square. */
private Vector3f animatedRotationAxis;
/** Seconds the animation should take to complete. */
private float animatedRotationSeconds;
/** How many seconds have elapsed since we started animating.
* This is clamped to 'animatedRotationSeconds', and when
* it is equal, the animation is complete. */
private float animatedRotationElapsed;
/** Start a new rotation animation of the active square by
* 'angle' degrees about 'axis' for 'seconds'. */
public void beginAnimatedRotation(double angle, Vector3f axis, float seconds)
{
if (this.activeSquare != null &&
this.activeSquare.baseSquare != null)
{
log("starting rotation animation");
this.animatedRotationStartRotation = this.activeSquare.rotationFromBase;
this.animatedRotationAngle = angle;
this.animatedRotationAxis = axis;
this.animatedRotationSeconds = seconds;
this.animatedRotationElapsed = 0;
}
}
/** If animating, advance to the next frame, based on 'deltaSeconds'
* having elapsed since the last animated frame.
*
* This should *not* trigger a redraw, since that will cause this
* function to be called again during the same frame. */
public void nextAnimatedRotationFrame(float deltaSeconds)
{
if (this.animatedRotationElapsed < this.animatedRotationSeconds &&
this.activeSquare != null &&
this.activeSquare.baseSquare != null)
{
this.animatedRotationElapsed = FloatUtil.clampf(
this.animatedRotationElapsed + deltaSeconds, 0, this.animatedRotationSeconds);
// How much do we want the square to be rotated,
// relative to its orientation at the start of
// the animation?
double rotFraction = this.animatedRotationElapsed / this.animatedRotationSeconds;
Vector3f partialRot = this.animatedRotationAxis.timesd(
this.animatedRotationAngle * rotFraction);
// Compose with the original orientation.
Vector3f newRotationFromBase =
Vector3f.composeRotations(this.animatedRotationStartRotation, partialRot);
SurfaceSquare s = replaceWithNewRotation(
this.activeSquare.baseSquare, this.activeSquare, newRotationFromBase);
this.setActiveSquareNoRedraw(s);
if (this.animatedRotationElapsed >= this.animatedRotationSeconds) {
log("rotation animation finished; normal: "+s.up);
}
}
}
/** Do any "physics" world updates. This is invoked prior to
* rendering a frame in the GL canvas. */
public void updatePhysics(float elapsedSeconds)
{
this.nextAnimatedRotationFrame(elapsedSeconds);
}
/** Get list of stars for which both squares have observations. */
private List<String> getCommonStars(SurfaceSquare s1, SurfaceSquare s2)
{
ArrayList<String> ret = new ArrayList<String>();
for (Map.Entry<String, StarObservation> entry : s1.starObs.entrySet()) {
if (s2.findObservation(entry.getKey()) != null) {
ret.add(entry.getKey());
}
}
return ret;
}
private void showCurvatureDialog()
{
// Default initial values.
CurvatureCalculator c = CurvatureCalculator.getDubheSirius();
// Try to populate 'c' with values from the current square.
if (this.activeSquare != null && this.activeSquare.baseSquare != null) {
SurfaceSquare start = this.activeSquare.baseSquare;
SurfaceSquare end = this.activeSquare;
List<String> common = getCommonStars(start, end);
if (common.size() >= 2) {
// When Dubhe and Betelgeuse are the only ones, I want
// Dubhe first so the calculation agrees with the ad-hoc
// animation, and doing them in this order accomplishes
// that.
String A = common.get(1);
String B = common.get(0);
log("initializing curvature dialog with "+A+" and "+B);
c.start_A_az = start.findObservation(A).azimuth;
c.start_A_el = start.findObservation(A).elevation;
c.start_B_az = start.findObservation(B).azimuth;
c.start_B_el = start.findObservation(B).elevation;
c.end_A_az = end.findObservation(A).azimuth;
c.end_A_el = end.findObservation(A).elevation;
c.end_B_az = end.findObservation(B).azimuth;
c.end_B_el = end.findObservation(B).elevation;
c.setTravelByLatLong(start.latitude, start.longitude, end.latitude, end.longitude);
}
}
// Run the dialog.
(new CurvatureCalculatorDialog(EarthShape.this, c)).exec();
}
}
// EOF
| smcpeak/earthshape | src/earthshape/EarthShape.java | Java | bsd-2-clause | 118,405 |
/*
* Ferox, a graphics and game library in Java
*
* Copyright (c) 2012, Michael Ludwig
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ferox.math.bounds;
import com.ferox.math.*;
/**
* <p/>
* Frustum represents the mathematical construction of a frustum. It is described as a 6 sided convex hull,
* where at least two planes are parallel to each other. It supports generating frustums that represent
* perspective projections (a truncated pyramid), or orthographic projections (a rectangular prism).
* <p/>
* Each frustum has a direction vector and an up vector. These vectors define an orthonormal basis for the
* frustum. The two parallel planes of the frustum are specified as distances along the direction vector (near
* and far). The additional planes are computed based on the locations of the four corners of the near plane
* intersection.
* <p/>
* The mapping from world space to frustum space is not as straight-forward as is implied by the above state.
* Frustum provides the functionality to get the {@link #getProjectionMatrix() project matrix} and {@link
* #getViewMatrix() modelview matrix} suitable for use in an OpenGL system. The camera within an OpenGL system
* looks down its local negative z-axis. Thus the provided direction in this Frustum represents the negative
* z-axis within camera space.
*
* @author Michael Ludwig
*/
public class Frustum {
/**
* Result of a frustum test against a {@link AxisAlignedBox}.
*/
public static enum FrustumIntersection {
/**
* Returned when a candidate object is fully enclosed by the Frustum.
*/
INSIDE,
/**
* Returned when a candidate object is completely outside of the Frustum.
*/
OUTSIDE,
/**
* Returned when a candidate object intersects the Frustum but is not completely contained.
*/
INTERSECT
}
public static final int NUM_PLANES = 6;
public static final int NEAR_PLANE = 0;
public static final int FAR_PLANE = 1;
public static final int TOP_PLANE = 2;
public static final int BOTTOM_PLANE = 3;
public static final int LEFT_PLANE = 4;
public static final int RIGHT_PLANE = 5;
private boolean useOrtho;
// local values
private double frustumLeft;
private double frustumRight;
private double frustumTop;
private double frustumBottom;
private double frustumNear;
private double frustumFar;
// frustum orientation
private final Vector3 up;
private final Vector3 direction;
private final Vector3 location;
private final Matrix4 projection;
private final Matrix4 view;
// planes representing frustum, adjusted for
// position, direction and up
private final Vector4[] worldPlanes;
// temporary vector used during intersection queries, saved to avoid allocation
private final Vector3 temp;
/**
* Instantiate a new Frustum that's positioned at the origin, looking down the negative z-axis. The given
* values are equivalent to those described in setPerspective() and are used for the initial frustum
* parameters.
*
* @param fov
* @param aspect
* @param znear
* @param zfar
*/
public Frustum(double fov, double aspect, double znear, double zfar) {
this();
setPerspective(fov, aspect, znear, zfar);
}
/**
* Instantiate a new Frustum that's positioned at the origin, looking down the negative z-axis. The six
* values are equivalent to those specified in setFrustum() and are taken as the initial frustum
* parameters.
*
* @param ortho True if the frustum values are for an orthographic projection, otherwise it's a
* perspective projection
* @param fl
* @param fr
* @param fb
* @param ft
* @param fn
* @param ff
*/
public Frustum(boolean ortho, double fl, double fr, double fb, double ft, double fn, double ff) {
this();
setFrustum(ortho, fl, fr, fb, ft, fn, ff);
}
// initialize everything
private Frustum() {
worldPlanes = new Vector4[6];
location = new Vector3();
up = new Vector3(0, 1, 0);
direction = new Vector3(0, 0, -1);
view = new Matrix4();
projection = new Matrix4();
temp = new Vector3();
}
/**
* Get the left edge of the near frustum plane.
*
* @return The left edge of the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumLeft() {
return frustumLeft;
}
/**
* Get the right edge of the near frustum plane.
*
* @return The right edge of the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumRight() {
return frustumRight;
}
/**
* Get the top edge of the near frustum plane.
*
* @return The top edge of the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumTop() {
return frustumTop;
}
/**
* Get the bottom edge of the near frustum plane.
*
* @return The bottom edge of the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumBottom() {
return frustumBottom;
}
/**
* Get the distance to the near frustum plane from the origin, in camera coords.
*
* @return The distance to the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumNear() {
return frustumNear;
}
/**
* Get the distance to the far frustum plane from the origin, in camera coords.
*
* @return The distance to the far frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumFar() {
return frustumFar;
}
/**
* <p/>
* Sets the dimensions of the viewing frustum in camera coords. left, right, bottom, and top specify edges
* of the rectangular near plane. This plane is positioned perpendicular to the viewing direction, a
* distance near along the direction vector from the view's location.
* <p/>
* If this Frustum is using orthogonal projection, the frustum is a rectangular prism extending from this
* near plane, out to an identically sized plane, that is distance far away. If not, the far plane is the
* far extent of a pyramid with it's point at the location, truncated at the near plane.
*
* @param ortho True if the Frustum should use an orthographic projection
* @param left The left edge of the near frustum plane
* @param right The right edge of the near frustum plane
* @param bottom The bottom edge of the near frustum plane
* @param top The top edge of the near frustum plane
* @param near The distance to the near frustum plane
* @param far The distance to the far frustum plane
*
* @throws IllegalArgumentException if left > right, bottom > top, near > far, or near <= 0 when the view
* isn't orthographic
*/
public void setFrustum(boolean ortho, double left, double right, double bottom, double top, double near,
double far) {
if (left > right || bottom > top || near > far) {
throw new IllegalArgumentException("Frustum values would create an invalid frustum: " + left +
" " +
right + " x " + bottom + " " + top + " x " + near + " " + far);
}
if (near <= 0 && !ortho) {
throw new IllegalArgumentException("Illegal value for near frustum when using perspective projection: " +
near);
}
frustumLeft = left;
frustumRight = right;
frustumBottom = bottom;
frustumTop = top;
frustumNear = near;
frustumFar = far;
useOrtho = ortho;
update();
}
/**
* Set the frustum to be perspective projection with the given field of view (in degrees). Widths and
* heights are calculated using the assumed aspect ration and near and far values. Because perspective
* transforms only make sense for non-orthographic projections, it also sets this view to be
* non-orthographic.
*
* @param fov The field of view
* @param aspect The aspect ratio of the view region (width / height)
* @param near The distance from the view's location to the near camera plane
* @param far The distance from the view's location to the far camera plane
*
* @throws IllegalArgumentException if fov is outside of (0, 180], or aspect is <= 0, or near > far, or if
* near <= 0
*/
public void setPerspective(double fov, double aspect, double near, double far) {
if (fov <= 0f || fov > 180f) {
throw new IllegalArgumentException("Field of view must be in (0, 180], not: " + fov);
}
if (aspect <= 0) {
throw new IllegalArgumentException("Aspect ration must be >= 0, not: " + aspect);
}
double h = Math.tan(Math.toRadians(fov * .5f)) * near;
double w = h * aspect;
setFrustum(false, -w, w, -h, h, near, far);
}
/**
* Set the frustum to be an orthographic projection that uses the given boundary edges for the near
* frustum plane. The near value is set to -1, and the far value is set to 1.
*
* @param left
* @param right
* @param bottom
* @param top
*
* @throws IllegalArgumentException if left > right or bottom > top
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public void setOrtho(double left, double right, double bottom, double top) {
setFrustum(true, left, right, bottom, top, -1f, 1f);
}
/**
* Whether or not this view uses a perspective or orthogonal projection.
*
* @return True if the projection matrix is orthographic
*/
public boolean isOrthogonalProjection() {
return useOrtho;
}
/**
* <p/>
* Get the location vector of this view, in world space. The returned vector is read-only. Modifications
* to the frustum's view parameters must be done through {@link #setOrientation(Vector3, Vector3,
* Vector3)}.
*
* @return The location of the view
*/
public
@Const
Vector3 getLocation() {
return location;
}
/**
* <p/>
* Get the up vector of this view, in world space. Together up and direction form a right-handed
* coordinate system. The returned vector is read-only. Modifications to the frustum's view parameters
* must be done through {@link #setOrientation(Vector3, Vector3, Vector3)}.
*
* @return The up vector of this view
*/
public
@Const
Vector3 getUp() {
return up;
}
/**
* <p/>
* Get the direction vector of this frustum, in world space. Together up and direction form a right-handed
* coordinate system. The returned vector is read-only. Modifications to the frustum's view parameters
* must be done through {@link #setOrientation(Vector3, Vector3, Vector3)}.
*
* @return The current direction that this frustum is pointing
*/
public
@Const
Vector3 getDirection() {
return direction;
}
/**
* Compute and return the field of view along the vertical axis that this Frustum uses. This is
* meaningless for an orthographic projection, and returns -1 in that case. Otherwise, an angle in degrees
* is returned in the range 0 to 180. This works correctly even when the bottom and top edges of the
* Frustum are not centered about its location.
*
* @return The field of view of this Frustum
*/
public double getFieldOfView() {
if (useOrtho) {
return -1f;
}
double fovTop = Math.atan(frustumTop / frustumNear);
double fovBottom = Math.atan(frustumBottom / frustumNear);
return Math.toDegrees(fovTop - fovBottom);
}
/**
* <p/>
* Return the 4x4 projection matrix that represents the mathematical projection from the frustum to
* homogenous device coordinates (essentially the unit cube).
* <p/>
* <p/>
* The returned matrix is read-only and will be updated automatically as the projection of the Frustum
* changes.
*
* @return The projection matrix
*/
public
@Const
Matrix4 getProjectionMatrix() {
return projection;
}
/**
* <p/>
* Return the 'view' transform of this Frustum. The view transform represents the coordinate space
* transformation from world space to camera/frustum space. The local basis of the Frustum is formed by
* the left, up and direction vectors of the Frustum. The left vector is <code>up X direction</code>, and
* up and direction are user defined vectors.
* <p/>
* The returned matrix is read-only and will be updated automatically as {@link #setOrientation(Vector3,
* Vector3, Vector3)} is invoked.
*
* @return The view matrix
*/
public
@Const
Matrix4 getViewMatrix() {
return view;
}
/**
* <p/>
* Copy the given vectors into this Frustum for its location, direction and up vectors. The orientation is
* then normalized and orthogonalized, but the provided vectors are unmodified.
* <p/>
* Any later changes to the vectors' x, y, and z values will not be reflected in the frustum planes or
* view transform, unless this method is called again.
*
* @param location The new location vector
* @param direction The new direction vector
* @param up The new up vector
*
* @throws NullPointerException if location, direction or up is null
*/
public void setOrientation(@Const Vector3 location, @Const Vector3 direction, @Const Vector3 up) {
if (location == null || direction == null || up == null) {
throw new NullPointerException("Orientation vectors cannot be null: " + location + " " +
direction +
" " + up);
}
this.location.set(location);
this.direction.set(direction);
this.up.set(up);
update();
}
/**
* Set the orientation of this Frustum based on the affine <var>transform</var>. The 4th column's first 3
* values encode the transformation. The 3rd column holds the direction vector, and the 2nd column defines
* the up vector.
*
* @param transform The new transform of the frustum
*
* @throws NullPointerException if transform is null
*/
public void setOrientation(@Const Matrix4 transform) {
if (transform == null) {
throw new NullPointerException("Transform cannot be null");
}
this.location.set(transform.m03, transform.m13, transform.m23);
this.direction.set(transform.m02, transform.m12, transform.m22);
this.up.set(transform.m01, transform.m11, transform.m21);
update();
}
/**
* Set the orientation of this Frustum based on the given location vector and 3x3 rotation matrix.
* Together the vector and rotation represent an affine transform that is treated the same as in {@link
* #setOrientation(Matrix4)}.
*
* @param location The location of the frustum
* @param rotation The rotation of the frustum
*
* @throws NullPointerException if location or rotation are null
*/
public void setOrientation(@Const Vector3 location, @Const Matrix3 rotation) {
if (location == null) {
throw new NullPointerException("Location cannot be null");
}
if (rotation == null) {
throw new NullPointerException("Rotation matrix cannot be null");
}
this.location.set(location);
this.direction.set(rotation.m02, rotation.m12, rotation.m22);
this.up.set(rotation.m01, rotation.m11, rotation.m21);
update();
}
/**
* <p/>
* Return a plane representing the given plane of the view frustum, in world coordinates. This plane
* should not be modified. The returned plane's normal is configured so that it points into the center of
* the Frustum. The returned {@link Vector4} is encoded as a plane as defined in {@link Plane}; it is also
* normalized.
* <p/>
* <p/>
* The returned plane vector is read-only. It will be updated automatically when the projection or view
* parameters change.
*
* @param i The requested plane index
*
* @return The ReadOnlyVector4f instance for the requested plane, in world coordinates
*
* @throws IndexOutOfBoundsException if plane isn't in [0, 5]
*/
public
@Const
Vector4 getFrustumPlane(int i) {
return worldPlanes[i];
}
/**
* <p/>
* Compute and return the intersection of the AxisAlignedBox and this Frustum, <var>f</var>. It is assumed
* that the Frustum and AxisAlignedBox exist in the same coordinate frame. {@link
* FrustumIntersection#INSIDE} is returned when the AxisAlignedBox is fully contained by the Frustum.
* {@link FrustumIntersection#INTERSECT} is returned when this box is partially contained by the Frustum,
* and {@link FrustumIntersection#OUTSIDE} is returned when the box has no intersection with the Frustum.
* <p/>
* If <var>OUTSIDE</var> is returned, it is guaranteed that the objects enclosed by the bounds do not
* intersect the Frustum. If <var>INSIDE</var> is returned, any object {@link
* AxisAlignedBox#contains(AxisAlignedBox) contained} by the box will also be completely inside the
* Frustum. When <var>INTERSECT</var> is returned, there is a chance that the true representation of the
* objects enclosed by the box will be outside of the Frustum, but it is unlikely. This can occur when a
* corner of the box intersects with the planes of <var>f</var>, but the shape does not exist in that
* corner.
* <p/>
* The argument <var>planeState</var> can be used to hint to this function which planes of the Frustum
* require checking and which do not. When a hierarchy of bounds is used, the planeState can be used to
* remove unnecessary plane comparisons. If <var>planeState</var> is null it is assumed that all planes
* need to be checked. If <var>planeState</var> is not null, this method will mark any plane that the box
* is completely inside of as not requiring a comparison. It is the responsibility of the caller to save
* and restore the plane state as needed based on the structure of the bound hierarchy.
*
* @param bounds The bounds to test for intersection with this frustm
* @param planeState An optional PlaneState hint specifying which planes to check
*
* @return A FrustumIntersection indicating how the frustum and bounds intersect
*
* @throws NullPointerException if bounds is null
*/
public FrustumIntersection intersects(@Const AxisAlignedBox bounds, PlaneState planeState) {
if (bounds == null) {
throw new NullPointerException("Bounds cannot be null");
}
// early escape for potentially deeply nested nodes in a tree
if (planeState != null && !planeState.getTestsRequired()) {
return FrustumIntersection.INSIDE;
}
FrustumIntersection result = FrustumIntersection.INSIDE;
double distMax;
double distMin;
int plane = 0;
Vector4 p;
for (int i = Frustum.NUM_PLANES - 1; i >= 0; i--) {
if (planeState == null || planeState.isTestRequired(i)) {
p = getFrustumPlane(plane);
// set temp to the normal of the plane then compute the extent
// in-place; this is safe but we'll have to reset temp to the
// normal later if needed
temp.set(p.x, p.y, p.z).farExtent(bounds, temp);
distMax = Plane.getSignedDistance(p, temp, true);
if (distMax < 0) {
// the point closest to the plane is behind the plane, so
// we know the bounds must be outside of the frustum
return FrustumIntersection.OUTSIDE;
} else {
// the point closest to the plane is in front of the plane,
// but we need to check the farthest away point
// make sure to reset temp to the normal before computing
// the near extent in-place
temp.set(p.x, p.y, p.z).nearExtent(bounds, temp);
distMin = Plane.getSignedDistance(p, temp, true);
if (distMin < 0) {
// the farthest point is behind the plane, so at best
// this box will be intersecting the frustum
result = FrustumIntersection.INTERSECT;
} else {
// the box is completely contained by the plane, so
// the return result can be INSIDE or INTERSECT (if set by another plane)
if (planeState != null) {
planeState.setTestRequired(plane, false);
}
}
}
}
}
return result;
}
/*
* Update the plane instances returned by getFrustumPlane() to reflect any
* changes to the frustum's local parameters or orientation. Also update the
* view transform and projection matrix.
*/
private void update() {
// compute the right-handed basis vectors of the frustum
Vector3 n = new Vector3().scale(direction.normalize(), -1); // normalizes direction as well
Vector3 u = new Vector3().cross(up, n).normalize();
Vector3 v = up.cross(n, u).normalize(); // recompute up to properly orthogonal to direction
// view matrix
view.set(u.x, u.y, u.z, -location.dot(u), v.x, v.y, v.z, -location.dot(v), n.x, n.y, n.z,
-location.dot(n), 0f, 0f, 0f, 1f);
// projection matrix
if (useOrtho) {
projection.set(2 / (frustumRight - frustumLeft), 0, 0,
-(frustumRight + frustumLeft) / (frustumRight - frustumLeft), 0,
2 / (frustumTop - frustumBottom), 0,
-(frustumTop + frustumBottom) / (frustumTop - frustumBottom), 0, 0,
2 / (frustumNear - frustumFar),
-(frustumFar + frustumNear) / (frustumFar - frustumNear), 0, 0, 0, 1);
} else {
projection.set(2 * frustumNear / (frustumRight - frustumLeft), 0,
(frustumRight + frustumLeft) / (frustumRight - frustumLeft), 0, 0,
2 * frustumNear / (frustumTop - frustumBottom),
(frustumTop + frustumBottom) / (frustumTop - frustumBottom), 0, 0, 0,
-(frustumFar + frustumNear) / (frustumFar - frustumNear),
-2 * frustumFar * frustumNear / (frustumFar - frustumNear), 0, 0, -1, 0);
}
// generate world-space frustum planes, we pass in n and u since we
// created them to compute the view matrix and they're just garbage
// at this point, might as well let plane generation reuse them.
if (useOrtho) {
computeOrthoWorldPlanes(n, u);
} else {
computePerspectiveWorldPlanes(n, u);
}
}
private void computeOrthoWorldPlanes(Vector3 n, Vector3 p) {
// FAR
p.scale(direction, frustumFar).add(location);
n.scale(direction, -1);
setWorldPlane(FAR_PLANE, n, p);
// NEAR
p.scale(direction, frustumNear).add(location);
n.set(direction);
setWorldPlane(NEAR_PLANE, n, p);
// compute right vector for LEFT and RIGHT usage
n.cross(direction, up);
// LEFT
p.scale(n, frustumLeft).add(location);
setWorldPlane(LEFT_PLANE, n, p);
// RIGHT
p.scale(n, frustumRight).add(location);
n.scale(-1);
setWorldPlane(RIGHT_PLANE, n, p);
// BOTTOM
p.scale(up, frustumBottom).add(location);
setWorldPlane(BOTTOM_PLANE, up, p);
// TOP
n.scale(up, -1);
p.scale(up, frustumTop).add(location);
setWorldPlane(TOP_PLANE, n, p);
}
private void computePerspectiveWorldPlanes(Vector3 n, Vector3 p) {
// FAR
p.scale(direction, frustumFar).add(location);
p.scale(direction, -1);
setWorldPlane(FAR_PLANE, n, p);
// NEAR
p.scale(direction, frustumNear).add(location);
n.set(direction);
setWorldPlane(NEAR_PLANE, n, p);
// compute left vector for LEFT and RIGHT usage
p.cross(up, direction);
// LEFT
double invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumLeft * frustumLeft);
n.scale(direction, Math.abs(frustumLeft) / frustumNear).sub(p).scale(frustumNear * invHyp);
setWorldPlane(LEFT_PLANE, n, location);
// RIGHT
invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumRight * frustumRight);
n.scale(direction, Math.abs(frustumRight) / frustumNear).add(p).scale(frustumNear * invHyp);
setWorldPlane(RIGHT_PLANE, n, location);
// BOTTOM
invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumBottom * frustumBottom);
n.scale(direction, Math.abs(frustumBottom) / frustumNear).add(up).scale(frustumNear * invHyp);
setWorldPlane(BOTTOM_PLANE, n, location);
// TOP
invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumTop * frustumTop);
n.scale(direction, Math.abs(frustumTop) / frustumNear).sub(up).scale(frustumNear * invHyp);
setWorldPlane(TOP_PLANE, n, location);
}
// set the given world plane so it's a plane with the given normal
// that passes through pos, and then normalize it
private void setWorldPlane(int plane, @Const Vector3 normal, @Const Vector3 pos) {
setWorldPlane(plane, normal.x, normal.y, normal.z, -normal.dot(pos));
}
// set the given world plane, with the 4 values, and then normalize it
private void setWorldPlane(int plane, double a, double b, double c, double d) {
Vector4 cp = worldPlanes[plane];
if (cp == null) {
cp = new Vector4(a, b, c, d);
worldPlanes[plane] = cp;
} else {
cp.set(a, b, c, d);
}
Plane.normalize(cp);
}
}
| geronimo-iia/ferox | ferox-math/src/main/java/com/ferox/math/bounds/Frustum.java | Java | bsd-2-clause | 28,685 |
package cocoonClient.Panels;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.DefaultTableModel;
import JSONTransmitProtocol.newReader.JSONReader;
import cocoonClient.Connector.AbstractConnector;
import cocoonClient.Data.UserInfo;
public class StatusPanel extends CocoonDisplayPanel implements AbstractConnector{
private JTable table;
public StatusPanel(){
super(UserInfo.getMainFrame());
setRightPanel(new TestRightPanel());
this.setSize(600, 500);
this.setLayout(new FlowLayout());
init();
UserInfo.getPanels().put("Status", this);
}
private void init() {
try{
//Table//以Model物件宣告建立表格的JTable元件
table = new JTable(){
public void valueChanged(ListSelectionEvent e){
super.valueChanged(e); //呼叫基礎類別的valueChanged()方法, 否則選取動作無法正常執行
if( table.getSelectedRow() == -1) return;//取得表格目前的選取列,若沒有選取列則終止執行方法
}
};
table.setModel(new DefaultTableModel(){
@Override
public boolean isCellEditable(int row, int column){
return false;
}
});
table.setShowGrid(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSelectionBackground(Color.ORANGE);//設定選取背景顏色
table.setCellSelectionEnabled(true); //設定允許儲存格選取
//取得處理表格資料的Model物件,建立關聯
DefaultTableModel dtm = (DefaultTableModel)table.getModel(); //宣告處理表格資料的TableModel物件
String columnTitle[] = new String[]{"Date", "Username", "Problem", "Status"};
int columnWidth[] = new int[]{150, 120, 190, 120};
for(int i = 0; i < columnTitle.length; i++){
dtm.addColumn(columnTitle[i]);
}
for(int i = 0; i < columnWidth.length; i++){
//欄寬設定
table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]);
}
//註冊回應JTable元件的MouseEvent事件的監聽器物件
/* table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
int selRow = table.rowAtPoint(e.getPoint());//取得滑鼠點選位置所在之資料的列索引
String Size = (String) table.getValueAt(selRow, 2); //取得被點選資料列的第3欄的值
if (Integer.parseInt(Size)> 0 ){
}
}
});*/
}catch ( Exception e){
e.printStackTrace();
}
JScrollPane pane = new JScrollPane(table);
pane.setPreferredSize(new Dimension(600, 450));
add(pane);
}
private void addStatus(String response){
JSONReader reader = new JSONReader(response);
DefaultTableModel dtm = (DefaultTableModel)table.getModel();
String result = "";
try{
result = reader.getSubmission().getResult().split("\n")[0];
}
catch(Exception e){}
dtm.addRow(new String[] {
reader.getSubmission().getTime(),
reader.getSubmission().getUsername(),
UserInfo.getProblemSet().getProblemName(reader.getSubmission().getPID()),
result
});
}
@Override
public void recieveResponse(String response) {
addStatus(response);
}
}
| hydai/Cocoon | Cocoon/src/cocoonClient/Panels/StatusPanel.java | Java | bsd-2-clause | 3,759 |
package de.lman;
import de.lman.engine.Colors;
import de.lman.engine.Game;
import de.lman.engine.InputState;
import de.lman.engine.Keys;
import de.lman.engine.Mouse;
import de.lman.engine.math.Mat2f;
import de.lman.engine.math.Scalar;
import de.lman.engine.math.Transform;
import de.lman.engine.math.Vec2f;
import de.lman.engine.physics.Body;
import de.lman.engine.physics.ContactStatePair;
import de.lman.engine.physics.GeometryUtils;
import de.lman.engine.physics.Physics;
import de.lman.engine.physics.contacts.Contact;
import de.lman.engine.physics.contacts.ContactListener;
import de.lman.engine.physics.shapes.BoxShape;
import de.lman.engine.physics.shapes.EdgeShape;
import de.lman.engine.physics.shapes.PhysicsMaterial;
import de.lman.engine.physics.shapes.PlaneShape;
import de.lman.engine.physics.shapes.PolygonShape;
import de.lman.engine.physics.shapes.Shape;
/*
Probleme lösen:
- Linien-Zeichnen korrigieren
Aufgaben:
- Tastatureingaben robuster machen (ist gedrückt, war gedrückt)
- Bitmap laden, konvertieren und zeichnen
- Bitmap transformiert zeichnen (Rotation)
- Bitmap fonts generieren
- Bitmap fonts zeichnen
- Bitmap Bilinär filtern
- Debug Informationen
- Fps / Framedauer anzeigen
- Zeitmessungen
- Speichern für mehrere Frames
- Visualisierung (Bar, Line)
- UI
- Panel
- Button
- Label
- Checkbox
- Radiobutton
- Sensor-Flag für Shape
- ECS
- Integrierter-Level-Editor
- Skalierung
- Propertionales vergrößern von Seiten
- Verschiebung von Eckpunkten
- Löschen
- Kopieren / Einfügen
- Gitter-Snap
- Mehrere Shapetypen + Auswahlmöglichkeit:
- Kreis
- Linien-Segment
- Polygone
- Boxen
- Ebenen
- Laden / Speichern
- Körper & Formen serialisieren und deserialisieren (JSON)
- Rotationsdynamik:
- Kreuzprodukt
- updateAABB in Body robuster machen
- getSupportPoints vereinfachen / robuster machen
- Massenzentrum (COM)
- Traegheitsmoment (Inertia, AngularVelocity)
- Kontaktausschnitt
- Asset-Management
- Preloading
- Erstellung von Kontakt-Szenarien vereinfachen -> offset()
*/
public class Leverman extends Game implements ContactListener {
public Leverman() {
super("Leverman");
}
public static void main(String[] args) {
Leverman game = new Leverman();
game.run();
}
private Physics physics;
private boolean showContacts = true;
private boolean showAABBs = false;
private boolean physicsSingleStep = false;
public final static PhysicsMaterial MAT_STATIC = new PhysicsMaterial(0f, 0.1f);
public final static PhysicsMaterial MAT_DYNAMIC = new PhysicsMaterial(1f, 0.1f);
private Body playerBody;
private boolean playerOnGround = false;
private boolean playerJumping = false;
private int playerGroundHash = 0;
private final Vec2f groundNormal = new Vec2f(0, 1);
@Override
public void physicsBeginContact(int hash, ContactStatePair pair) {
Contact contact = pair.pair.contacts[pair.contactIndex];
Vec2f normal = contact.normal;
Body player = null;
if (pair.pair.a.id == playerBody.id) {
player = pair.pair.a;
normal = new Vec2f(contact.normal).invert();
} else if (pair.pair.b.id == playerBody.id) {
player = pair.pair.b;
}
float d = normal.dot(groundNormal);
if (d > 0) {
if (player != null && (!playerOnGround)) {
playerOnGround = true;
playerGroundHash = hash;
}
}
}
@Override
public void physicsEndContact(int hash, ContactStatePair pair) {
Contact contact = pair.pair.contacts[pair.contactIndex];
Vec2f normal = contact.normal;
Body player = null;
if (pair.pair.a.id == playerBody.id) {
player = pair.pair.a;
normal = new Vec2f(contact.normal).invert();
} else if (pair.pair.b.id == playerBody.id) {
player = pair.pair.b;
}
float d = normal.dot(groundNormal);
if (d > 0) {
if (player != null && playerOnGround && (playerGroundHash == hash)) {
playerOnGround = false;
playerGroundHash = 0;
}
}
}
private void addPlatform(float x, float y, float rx, float ry) {
Body body;
physics.addBody(body = new Body().addShape(new BoxShape(new Vec2f(rx, ry)).setMaterial(MAT_STATIC)));
body.pos.set(x, y);
}
private void addBox(float x, float y, float rx, float ry) {
Body body;
physics.addBody(body = new Body().addShape(new BoxShape(new Vec2f(rx, ry)).setMaterial(MAT_DYNAMIC)));
body.pos.set(x, y);
}
protected void initGame() {
physics = new Physics(this);
physics.enableSingleStepMode(physicsSingleStep);
Body body;
physics.addBody(body = new Body().addShape(new PlaneShape(viewport.y).rotation(Scalar.PI * 0f).setMaterial(MAT_STATIC)));
body.pos.set(-halfWidth + 0.5f, 0);
physics.addBody(body = new Body().addShape(new PlaneShape(viewport.y).rotation(Scalar.PI * 1f).setMaterial(MAT_STATIC)));
body.pos.set(halfWidth - 0.5f, 0);
physics.addBody(body = new Body().addShape(new PlaneShape(viewport.x).rotation(Scalar.PI * 0.5f).setMaterial(MAT_STATIC)));
body.pos.set(0, -halfHeight + 0.5f);
physics.addBody(body = new Body().addShape(new PlaneShape(viewport.x).rotation(Scalar.PI * 1.5f).setMaterial(MAT_STATIC)));
body.pos.set(0, halfHeight - 0.5f);
addPlatform(0 - 2.9f, 0 - 2.0f, 0.6f, 0.1f);
addPlatform(0, 0 - 1.3f, 0.7f, 0.1f);
addPlatform(0 + 2.9f, 0 - 0.8f, 0.6f, 0.1f);
//addBox(0, -0.5f, 0.2f, 0.2f);
addPlatform(0 + 2.0f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f);
addPlatform(0 + 2.4f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f);
addPlatform(0 + 2.8f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f);
addPlatform(0 + 3.2f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f);
playerBody = new Body();
BoxShape playerBox = (BoxShape) new BoxShape(new Vec2f(0.2f, 0.4f)).setMaterial(MAT_DYNAMIC);
playerBody.addShape(playerBox);
playerBody.pos.set(0, -halfHeight + playerBox.radius.y + 0.5f);
physics.addBody(playerBody);
Vec2f[] polyVerts = new Vec2f[]{
new Vec2f(0, 0.5f),
new Vec2f(-0.5f, -0.5f),
new Vec2f(0.5f, -0.5f),
};
physics.addBody(body = new Body().addShape(new PolygonShape(polyVerts).setMaterial(MAT_STATIC)));
body.pos.set(0, 0);
}
private boolean dragging = false;
private Vec2f dragStart = new Vec2f();
private Body dragBody = null;
private void updateGameInput(float dt, InputState inputState) {
boolean leftMousePressed = inputState.isMouseDown(Mouse.LEFT);
if (!dragging) {
if (leftMousePressed) {
dragBody = null;
for (int i = 0; i < physics.numBodies; i++) {
Body body = physics.bodies[i];
if (body.invMass > 0) {
if (GeometryUtils.isPointInAABB(inputState.mousePos.x, inputState.mousePos.y, body.aabb)) {
dragging = true;
dragStart.set(inputState.mousePos);
dragBody = body;
break;
}
}
}
}
} else {
if (leftMousePressed) {
float dx = inputState.mousePos.x - dragStart.x;
float dy = inputState.mousePos.y - dragStart.y;
dragBody.vel.x += dx * 0.1f;
dragBody.vel.y += dy * 0.1f;
dragStart.set(inputState.mousePos);
} else {
dragging = false;
}
}
// Kontakte ein/ausschalten
if (inputState.isKeyDown(Keys.F2)) {
showContacts = !showContacts;
inputState.setKeyDown(Keys.F2, false);
}
// AABBs ein/ausschalten
if (inputState.isKeyDown(Keys.F3)) {
showAABBs = !showAABBs;
inputState.setKeyDown(Keys.F3, false);
}
// Einzelschritt-Physik-Modus ein/ausschalten
if (inputState.isKeyDown(Keys.F5)) {
physicsSingleStep = !physicsSingleStep;
physics.enableSingleStepMode(physicsSingleStep);
inputState.setKeyDown(Keys.F5, false);
}
if (inputState.isKeyDown(Keys.F6)) {
if (physicsSingleStep) {
physics.nextStep();
}
inputState.setKeyDown(Keys.F6, false);
}
// Player bewegen
if (inputState.isKeyDown(Keys.W)) {
if (!playerJumping && playerOnGround) {
playerBody.acc.y += 4f / dt;
playerJumping = true;
}
} else {
if (playerJumping && playerOnGround) {
playerJumping = false;
}
}
if (inputState.isKeyDown(Keys.A)) {
playerBody.acc.x -= 0.1f / dt;
} else if (inputState.isKeyDown(Keys.D)) {
playerBody.acc.x += 0.1f / dt;
}
}
private final Editor editor = new Editor();
private boolean editorWasShownAABB = false;
protected void updateInput(float dt, InputState input) {
// Editormodus ein/ausschalten
if (input.isKeyDown(Keys.F4)) {
editor.active = !editor.active;
if (editor.active) {
editorWasShownAABB = showAABBs;
showAABBs = true;
editor.init(physics);
} else {
showAABBs = editorWasShownAABB;
}
input.setKeyDown(Keys.F4, false);
}
if (editor.active) {
editor.updateInput(dt, physics, input);
} else {
updateGameInput(dt, input);
}
}
@Override
protected String getAdditionalTitle() {
return String.format(" [Frames: %d, Bodies: %d, Contacts: %d]", numFrames, physics.numBodies, physics.numContacts);
}
protected void updateGame(float dt) {
if (!editor.active) {
physics.step(dt);
}
}
private void renderEditor(float dt) {
// TODO: Move to editor class
clear(0x000000);
for (int i = 0; i < viewport.x / Editor.GRID_SIZE; i++) {
drawLine(-halfWidth + i * Editor.GRID_SIZE, -halfHeight, -halfWidth + i * Editor.GRID_SIZE, halfHeight, Colors.DarkSlateGray);
}
for (int i = 0; i < viewport.y / Editor.GRID_SIZE; i++) {
drawLine(-halfWidth, -halfHeight + i * Editor.GRID_SIZE, halfWidth, -halfHeight + i * Editor.GRID_SIZE, Colors.DarkSlateGray);
}
drawBodies(physics.numBodies, physics.bodies);
if (editor.selectedBody != null) {
Editor.DragSide[] dragSides = editor.getDragSides(editor.selectedBody);
Shape shape = editor.selectedBody.shapes[0];
if (dragSides.length > 0 && shape instanceof EdgeShape) {
EdgeShape edgeShape = (EdgeShape) shape;
Transform t = new Transform(shape.localPos, shape.localRotation).offset(editor.selectedBody.pos);
Vec2f[] localVertices = edgeShape.getLocalVertices();
for (int i = 0; i < dragSides.length; i++) {
Vec2f dragPoint = dragSides[i].center;
drawPoint(dragPoint, Editor.DRAGPOINT_RADIUS, Colors.White);
if (editor.resizeSideIndex == i) {
Vec2f v0 = new Vec2f(localVertices[dragSides[i].index0]).transform(t);
Vec2f v1 = new Vec2f(localVertices[dragSides[i].index1]).transform(t);
drawPoint(v0, Editor.DRAGPOINT_RADIUS, Colors.GoldenRod);
drawPoint(v1, Editor.DRAGPOINT_RADIUS, Colors.GoldenRod);
}
}
}
Mat2f mat = new Mat2f(shape.localRotation).transpose();
drawNormal(editor.selectedBody.pos, mat.col1, DEFAULT_ARROW_RADIUS, DEFAULT_ARROW_LENGTH, Colors.Red);
}
drawPoint(inputState.mousePos.x, inputState.mousePos.y, DEFAULT_POINT_RADIUS, 0x0000FF);
}
private void renderInternalGame(float dt) {
clear(0x000000);
drawBodies(physics.numBodies, physics.bodies);
if (showAABBs) {
drawAABBs(physics.numBodies, physics.bodies);
}
if (showContacts) {
drawContacts(dt, physics.numPairs, physics.pairs, false, true);
}
}
protected void renderGame(float dt) {
if (editor.active) {
renderEditor(dt);
} else {
renderInternalGame(dt);
}
}
}
| f1nalspace/leverman-devlog | lman/src/de/lman/Leverman.java | Java | bsd-2-clause | 11,052 |
package org.jvnet.jaxb2_commons.plugin.mergeable;
import java.util.Arrays;
import java.util.Collection;
import javax.xml.namespace.QName;
import org.jvnet.jaxb2_commons.lang.JAXBMergeStrategy;
import org.jvnet.jaxb2_commons.lang.MergeFrom2;
import org.jvnet.jaxb2_commons.lang.MergeStrategy2;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;
import org.jvnet.jaxb2_commons.plugin.AbstractParameterizablePlugin;
import org.jvnet.jaxb2_commons.plugin.Customizations;
import org.jvnet.jaxb2_commons.plugin.CustomizedIgnoring;
import org.jvnet.jaxb2_commons.plugin.Ignoring;
import org.jvnet.jaxb2_commons.plugin.util.FieldOutlineUtils;
import org.jvnet.jaxb2_commons.plugin.util.StrategyClassUtils;
import org.jvnet.jaxb2_commons.util.ClassUtils;
import org.jvnet.jaxb2_commons.util.FieldAccessorFactory;
import org.jvnet.jaxb2_commons.util.PropertyFieldAccessorFactory;
import org.jvnet.jaxb2_commons.xjc.outline.FieldAccessorEx;
import org.xml.sax.ErrorHandler;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JConditional;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JOp;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;
import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.FieldOutline;
import com.sun.tools.xjc.outline.Outline;
public class MergeablePlugin extends AbstractParameterizablePlugin {
@Override
public String getOptionName() {
return "Xmergeable";
}
@Override
public String getUsage() {
return "TBD";
}
private FieldAccessorFactory fieldAccessorFactory = PropertyFieldAccessorFactory.INSTANCE;
public FieldAccessorFactory getFieldAccessorFactory() {
return fieldAccessorFactory;
}
public void setFieldAccessorFactory(
FieldAccessorFactory fieldAccessorFactory) {
this.fieldAccessorFactory = fieldAccessorFactory;
}
private String mergeStrategyClass = JAXBMergeStrategy.class.getName();
public void setMergeStrategyClass(final String mergeStrategyClass) {
this.mergeStrategyClass = mergeStrategyClass;
}
public String getMergeStrategyClass() {
return mergeStrategyClass;
}
public JExpression createMergeStrategy(JCodeModel codeModel) {
return StrategyClassUtils.createStrategyInstanceExpression(codeModel,
MergeStrategy2.class, getMergeStrategyClass());
}
private Ignoring ignoring = new CustomizedIgnoring(
org.jvnet.jaxb2_commons.plugin.mergeable.Customizations.IGNORED_ELEMENT_NAME,
Customizations.IGNORED_ELEMENT_NAME,
Customizations.GENERATED_ELEMENT_NAME);
public Ignoring getIgnoring() {
return ignoring;
}
public void setIgnoring(Ignoring ignoring) {
this.ignoring = ignoring;
}
@Override
public Collection<QName> getCustomizationElementNames() {
return Arrays
.asList(org.jvnet.jaxb2_commons.plugin.mergeable.Customizations.IGNORED_ELEMENT_NAME,
Customizations.IGNORED_ELEMENT_NAME,
Customizations.GENERATED_ELEMENT_NAME);
}
@Override
public boolean run(Outline outline, Options opt, ErrorHandler errorHandler) {
for (final ClassOutline classOutline : outline.getClasses())
if (!getIgnoring().isIgnored(classOutline)) {
processClassOutline(classOutline);
}
return true;
}
protected void processClassOutline(ClassOutline classOutline) {
final JDefinedClass theClass = classOutline.implClass;
ClassUtils
._implements(theClass, theClass.owner().ref(MergeFrom2.class));
@SuppressWarnings("unused")
final JMethod mergeFrom$mergeFrom0 = generateMergeFrom$mergeFrom0(
classOutline, theClass);
@SuppressWarnings("unused")
final JMethod mergeFrom$mergeFrom = generateMergeFrom$mergeFrom(
classOutline, theClass);
if (!classOutline.target.isAbstract()) {
@SuppressWarnings("unused")
final JMethod createCopy = generateMergeFrom$createNewInstance(
classOutline, theClass);
}
}
protected JMethod generateMergeFrom$mergeFrom0(
final ClassOutline classOutline, final JDefinedClass theClass) {
JCodeModel codeModel = theClass.owner();
final JMethod mergeFrom$mergeFrom = theClass.method(JMod.PUBLIC,
codeModel.VOID, "mergeFrom");
mergeFrom$mergeFrom.annotate(Override.class);
{
final JVar left = mergeFrom$mergeFrom.param(Object.class, "left");
final JVar right = mergeFrom$mergeFrom.param(Object.class, "right");
final JBlock body = mergeFrom$mergeFrom.body();
final JVar mergeStrategy = body.decl(JMod.FINAL,
codeModel.ref(MergeStrategy2.class), "strategy",
createMergeStrategy(codeModel));
body.invoke("mergeFrom").arg(JExpr._null()).arg(JExpr._null())
.arg(left).arg(right).arg(mergeStrategy);
}
return mergeFrom$mergeFrom;
}
protected JMethod generateMergeFrom$mergeFrom(ClassOutline classOutline,
final JDefinedClass theClass) {
final JCodeModel codeModel = theClass.owner();
final JMethod mergeFrom = theClass.method(JMod.PUBLIC, codeModel.VOID,
"mergeFrom");
mergeFrom.annotate(Override.class);
{
final JVar leftLocator = mergeFrom.param(ObjectLocator.class,
"leftLocator");
final JVar rightLocator = mergeFrom.param(ObjectLocator.class,
"rightLocator");
final JVar left = mergeFrom.param(Object.class, "left");
final JVar right = mergeFrom.param(Object.class, "right");
final JVar mergeStrategy = mergeFrom.param(MergeStrategy2.class,
"strategy");
final JBlock methodBody = mergeFrom.body();
Boolean superClassImplementsMergeFrom = StrategyClassUtils
.superClassImplements(classOutline, getIgnoring(),
MergeFrom2.class);
if (superClassImplementsMergeFrom == null) {
} else if (superClassImplementsMergeFrom.booleanValue()) {
methodBody.invoke(JExpr._super(), "mergeFrom").arg(leftLocator)
.arg(rightLocator).arg(left).arg(right)
.arg(mergeStrategy);
} else {
}
final FieldOutline[] declaredFields = FieldOutlineUtils.filter(
classOutline.getDeclaredFields(), getIgnoring());
if (declaredFields.length > 0) {
final JBlock body = methodBody._if(right._instanceof(theClass))
._then();
JVar target = body.decl(JMod.FINAL, theClass, "target",
JExpr._this());
JVar leftObject = body.decl(JMod.FINAL, theClass, "leftObject",
JExpr.cast(theClass, left));
JVar rightObject = body.decl(JMod.FINAL, theClass,
"rightObject", JExpr.cast(theClass, right));
for (final FieldOutline fieldOutline : declaredFields) {
final FieldAccessorEx leftFieldAccessor = getFieldAccessorFactory()
.createFieldAccessor(fieldOutline, leftObject);
final FieldAccessorEx rightFieldAccessor = getFieldAccessorFactory()
.createFieldAccessor(fieldOutline, rightObject);
if (leftFieldAccessor.isConstant()
|| rightFieldAccessor.isConstant()) {
continue;
}
final JBlock block = body.block();
final JExpression leftFieldHasSetValue = (leftFieldAccessor
.isAlwaysSet() || leftFieldAccessor.hasSetValue() == null) ? JExpr.TRUE
: leftFieldAccessor.hasSetValue();
final JExpression rightFieldHasSetValue = (rightFieldAccessor
.isAlwaysSet() || rightFieldAccessor.hasSetValue() == null) ? JExpr.TRUE
: rightFieldAccessor.hasSetValue();
final JVar shouldBeSet = block.decl(
codeModel.ref(Boolean.class),
fieldOutline.getPropertyInfo().getName(false)
+ "ShouldBeMergedAndSet",
mergeStrategy.invoke("shouldBeMergedAndSet")
.arg(leftLocator).arg(rightLocator)
.arg(leftFieldHasSetValue)
.arg(rightFieldHasSetValue));
final JConditional ifShouldBeSetConditional = block._if(JOp
.eq(shouldBeSet, codeModel.ref(Boolean.class)
.staticRef("TRUE")));
final JBlock ifShouldBeSetBlock = ifShouldBeSetConditional
._then();
final JConditional ifShouldNotBeSetConditional = ifShouldBeSetConditional
._elseif(JOp.eq(
shouldBeSet,
codeModel.ref(Boolean.class).staticRef(
"FALSE")));
final JBlock ifShouldBeUnsetBlock = ifShouldNotBeSetConditional
._then();
// final JBlock ifShouldBeIgnoredBlock =
// ifShouldNotBeSetConditional
// ._else();
final JVar leftField = ifShouldBeSetBlock.decl(
leftFieldAccessor.getType(),
"lhs"
+ fieldOutline.getPropertyInfo().getName(
true));
leftFieldAccessor.toRawValue(ifShouldBeSetBlock, leftField);
final JVar rightField = ifShouldBeSetBlock.decl(
rightFieldAccessor.getType(),
"rhs"
+ fieldOutline.getPropertyInfo().getName(
true));
rightFieldAccessor.toRawValue(ifShouldBeSetBlock,
rightField);
final JExpression leftFieldLocator = codeModel
.ref(LocatorUtils.class).staticInvoke("property")
.arg(leftLocator)
.arg(fieldOutline.getPropertyInfo().getName(false))
.arg(leftField);
final JExpression rightFieldLocator = codeModel
.ref(LocatorUtils.class).staticInvoke("property")
.arg(rightLocator)
.arg(fieldOutline.getPropertyInfo().getName(false))
.arg(rightField);
final FieldAccessorEx targetFieldAccessor = getFieldAccessorFactory()
.createFieldAccessor(fieldOutline, target);
final JExpression mergedValue = JExpr.cast(
targetFieldAccessor.getType(),
mergeStrategy.invoke("merge").arg(leftFieldLocator)
.arg(rightFieldLocator).arg(leftField)
.arg(rightField).arg(leftFieldHasSetValue)
.arg(rightFieldHasSetValue));
final JVar merged = ifShouldBeSetBlock.decl(
rightFieldAccessor.getType(),
"merged"
+ fieldOutline.getPropertyInfo().getName(
true), mergedValue);
targetFieldAccessor.fromRawValue(
ifShouldBeSetBlock,
"unique"
+ fieldOutline.getPropertyInfo().getName(
true), merged);
targetFieldAccessor.unsetValues(ifShouldBeUnsetBlock);
}
}
}
return mergeFrom;
}
protected JMethod generateMergeFrom$createNewInstance(
final ClassOutline classOutline, final JDefinedClass theClass) {
final JMethod existingMethod = theClass.getMethod("createNewInstance",
new JType[0]);
if (existingMethod == null) {
final JMethod newMethod = theClass.method(JMod.PUBLIC, theClass
.owner().ref(Object.class), "createNewInstance");
newMethod.annotate(Override.class);
{
final JBlock body = newMethod.body();
body._return(JExpr._new(theClass));
}
return newMethod;
} else {
return existingMethod;
}
}
}
| highsource/jaxb2-basics | basic/src/main/java/org/jvnet/jaxb2_commons/plugin/mergeable/MergeablePlugin.java | Java | bsd-2-clause | 10,727 |
package operations;
import data.Collector;
import graph.implementation.Edge;
import utility.GraphFunctions;
/**
* Set the curve point to an ideal position.
* If source and destination are equal, it would be a line.
* If not, it is a noose on top of the vertex.
*/
public class O_RelaxEdge implements EdgeOperation {
private Edge edge;
public O_RelaxEdge(Edge edge) {
super();
this.edge = edge;
}
@Override
public void run() {
Collector.getSlides().addUndo();
GraphFunctions.relaxEdge(edge);
}
@Override
public void setEdge(Edge edge) {
this.edge = edge;
}
}
| Drafigon/WildGraphs | src/operations/O_RelaxEdge.java | Java | bsd-2-clause | 590 |
package adf.launcher.connect;
import adf.agent.office.OfficeAmbulance;
import adf.control.ControlAmbulance;
import adf.launcher.AbstractLoader;
import adf.launcher.ConfigKey;
import rescuecore2.components.ComponentConnectionException;
import rescuecore2.components.ComponentLauncher;
import rescuecore2.config.Config;
import rescuecore2.connection.ConnectionException;
public class ConnectorAmbulanceCentre implements Connector
{
@Override
public void connect(ComponentLauncher launcher, Config config, AbstractLoader loader)
{
int count = config.getIntValue(ConfigKey.KEY_AMBULANCE_CENTRE_COUNT, 0);
int connected = 0;
if (count == 0)
{
return;
}
/*
String classStr = config.getValue(ConfigKey.KEY_AMBULANCE_CENTRE_NAME);
if (classStr == null)
{
System.out.println("[ERROR] Cannot Load AmbulanceCentre Control !!");
return;
}
System.out.println("[START] Connect AmbulanceCentre (teamName:" + classStr + ")");
System.out.println("[INFO ] Load AmbulanceCentre (teamName:" + classStr + ")");
*/
try
{
if (loader.getControlAmbulance() == null)
{
System.out.println("[ERROR ] Cannot Load AmbulanceCentre Control !!");
return;
}
for (int i = 0; i != count; ++i)
{
ControlAmbulance controlAmbulance = loader.getControlAmbulance();
boolean isPrecompute = config.getBooleanValue(ConfigKey.KEY_PRECOMPUTE, false);
launcher.connect(new OfficeAmbulance(controlAmbulance, isPrecompute));
//System.out.println(name);
connected++;
}
}
catch (ComponentConnectionException | InterruptedException | ConnectionException e)
{
//e.printStackTrace();
System.out.println("[ERROR ] Cannot Load AmbulanceCentre Control !!");
}
System.out.println("[FINISH] Connect AmbulanceCentre (success:" + connected + ")");
}
}
| tkmnet/RCRS-ADF | modules/core/src/main/java/adf/launcher/connect/ConnectorAmbulanceCentre.java | Java | bsd-2-clause | 1,801 |
package com.mithos.bfg.loop;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
/**
* This class is an adapter for {@link OnEvent}. All methods do
* nothing and return true, so you need only implement the methods
* that you need to.
* @author James McMahon
*
*/
public class OnEventAdapter implements OnEvent {
@Override
public boolean keyPressed(KeyEvent e) {
return true;
}
@Override
public boolean keyReleased(KeyEvent e) {
return true;
}
@Override
public boolean mousePressed(MouseEvent e) {
return true;
}
@Override
public boolean mouseMoved(MouseEvent e) {
return true;
}
@Override
public boolean mouseReleased(MouseEvent e) {
return true;
}
@Override
public boolean mouseWheel(MouseWheelEvent e) {
return true;
}
}
| James1345/bfg | src/com/mithos/bfg/loop/OnEventAdapter.java | Java | bsd-2-clause | 821 |
/*
* Copyright (c) 2012, JInterval Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.java.jinterval.ir;
import com.cflex.util.lpSolve.LpConstant;
import com.cflex.util.lpSolve.LpModel;
import com.cflex.util.lpSolve.LpSolver;
import java.util.ArrayList;
//import org.apache.commons.math3.exception.MathIllegalArgumentException;
//TODO: Add exceptions and throws
public class IRPredictor {
private double[][] X;
private double[] Y;
private double[] E;
private boolean dataAreGiven;
// Number of observations
private int ObsNumber;
// Number of variables
private int VarNumber;
// Storage for predictions
private double PredictionMin;
private double PredictionMax;
private double[] PredictionMins;
private double[] PredictionMaxs;
// Last error
int ExitCode;
public IRPredictor(){
ObsNumber = 0;
VarNumber = 0;
dataAreGiven = false;
}
public IRPredictor(double[][] X, double[] Y, double[] E){
setData(X,Y,E);
}
public final void setData(double[][] X, double[] Y, double[] E)
// throws IllegalDimensionException
{
// if(X.length != Y.length || X.length != E.length)
// throw IllegalDimensionException;
this.X=X;
this.Y=Y;
this.E=E;
ObsNumber = X.length;
VarNumber = X[0].length;
dataAreGiven = true;
}
public int getExitCode() {
return ExitCode;
}
private boolean solveLpp(double[] Objective)
// throws IllegalDimensionException
{
if (Objective.length != VarNumber){
// throw IllegalDimensionException;
ExitCode = -1;
return false;
}
try {
// Init LP Solver
LpModel Lpp = new LpModel(0, VarNumber);
// Define LPP
double[] zObjective = new double[VarNumber+1];
System.arraycopy(Objective, 0, zObjective, 1, VarNumber);
Lpp.setObjFn(zObjective);
double[] zX=new double[VarNumber+1];
for (int i=0; i<ObsNumber; i++) {
System.arraycopy(X[i], 0, zX, 1, VarNumber);
Lpp.addConstraint(zX, LpConstant.LE, Y[i]+E[i]);
Lpp.addConstraint(zX, LpConstant.GE, Y[i]-E[i]);
// Solver.add_constraint(Lpp, zX, constant.LE, Y[i]+E[i]);
// Solver.add_constraint(Lpp, zX, constant.GE, Y[i]-E[i]);
}
//Solver.set_minim(Lpp);
//Lpp.setMinimum();
LpSolver Solver = new LpSolver(Lpp);
ExitCode = Solver.solve();
// ExitCode = Solver.solve(Lpp);
switch ( ExitCode ) {
case LpConstant.OPTIMAL:
PredictionMin = Lpp.getBestSolution(0);
break;
case LpConstant.INFEASIBLE:
//throw InfeasibleException
case LpConstant.UNBOUNDED:
//throw UnboundedException
}
// Solver.set_maxim(Lpp);
Lpp.setMaximum();
ExitCode = Solver.solve();
switch ( ExitCode ) {
case LpConstant.OPTIMAL:
PredictionMax = Lpp.getBestSolution(0);
break;
case LpConstant.INFEASIBLE:
//throw InfeasibleException
case LpConstant.UNBOUNDED:
//throw UnboundedException
}
} catch (Exception e){
//e.printStackTrace();
}
return ExitCode == LpConstant.OPTIMAL;
}
public boolean isDataConsistent(){
return solveLpp(X[0]);
}
public void compressData(){
}
public boolean predictAt(double[] x){
return solveLpp(x);
}
public boolean predictAtEveryDataPoint(){
PredictionMins = new double[ObsNumber];
PredictionMaxs = new double[ObsNumber];
boolean Solved = true;
for (int i=0; i<ObsNumber; i++){
Solved = Solved && predictAt(X[i]);
if(!Solved) {
break;
}
PredictionMins[i] = getMin();
PredictionMaxs[i] = getMax();
}
return Solved;
}
public double getMin(){
return PredictionMin;
}
public double getMax(){
return PredictionMax;
}
public double getMin(int i) {
return PredictionMins[i];
}
public double getMax(int i) {
return PredictionMaxs[i];
}
public double[] getMins() {
return PredictionMins;
}
public double[] getMaxs() {
return PredictionMaxs;
}
public double[] getResiduals(){
//Residuals=(y-(vmax+vmin)/2)/beta
double v;
double[] residuals = new double[ObsNumber];
for(int i=0; i<ObsNumber; i++) {
v = (PredictionMins[i]+PredictionMaxs[i])/2;
residuals[i] = (Y[i]-v)/E[i];
}
return residuals;
}
public double[] getLeverages(){
//Leverage=((vmax-vmin)/2)/beta
double v;
double[] leverages = new double[ObsNumber];
for(int i=0; i<ObsNumber; i++) {
v = (PredictionMaxs[i]-PredictionMins[i])/2;
leverages[i] = v/E[i];
}
return leverages;
}
public int[] getBoundary(){
final double EPSILON = 1.0e-6;
ArrayList<Integer> boundary = new ArrayList<Integer>();
double yp, ym, vp, vm;
for (int i=0; i<ObsNumber; i++){
yp = Y[i]+E[i];
vp = PredictionMaxs[i];
ym = Y[i]-E[i];
vm = PredictionMins[i];
if ( Math.abs(yp - vp) < EPSILON || Math.abs(ym - vm) < EPSILON ) {
boundary.add(1);
}
else {
boundary.add(0);
}
}
int[] a_boundary = new int[boundary.size()];
for (int i=0; i<a_boundary.length; i++){
a_boundary[i] = boundary.get(i).intValue();
}
return a_boundary;
}
public int[] getBoundaryNumbers(){
int Count = 0;
int[] boundary = getBoundary();
for (int i=0; i<boundary.length; i++){
if(boundary[i] == 1) {
Count++;
}
}
int j = 0;
int[] numbers = new int[Count];
for (int i=0; i<boundary.length; i++){
if(boundary[i] == 1) {
numbers[j++] = i;
}
}
return numbers;
}
//TODO: Implement getOutliers()
// public int[] getOutliers(){
//
// }
//TODO: Implement getOutliersNumbers()
// public int[] getOutliersNumbers(){
//
// }
public double[] getOutliersWeights(){
double[] outliers = new double[ObsNumber];
for(int i=0; i<ObsNumber; i++) {
outliers[i]=0;
}
try {
LpModel Lpp = new LpModel(0, ObsNumber+VarNumber);
// Build and set objective of LPP
double[] zObjective = new double[ObsNumber+VarNumber+1];
for(int i=1;i<=VarNumber; i++) {
zObjective[i] = 0;
}
for(int i=1;i<=ObsNumber; i++) {
zObjective[VarNumber+i] = 1;
}
Lpp.setObjFn(zObjective);
//Solver.set_minim(Lpp);
// Build and set constraints of LPP
double[] Row = new double[ObsNumber+VarNumber+1];
for (int i=0; i<ObsNumber; i++) {
for (int j=1; j<=VarNumber; j++) {
Row[j]=X[i][j-1];
}
for(int j=1; j<=ObsNumber; j++) {
Row[VarNumber+j] = 0;
}
Row[VarNumber+i+1] = -E[i];
// Solver.add_constraint(Lpp, Row, constant.LE, Y[i]);
Lpp.addConstraint(Row, LpConstant.LE, Y[i]);
Row[VarNumber+i+1] = E[i];
// Solver.add_constraint(Lpp, Row, constant.GE, Y[i]);
Lpp.addConstraint(Row, LpConstant.GE, Y[i]);
for (int j=1; j<=ObsNumber+VarNumber; j++) {
Row[j] = 0;
}
Row[VarNumber+i+1] = 1;
// Solver.add_constraint(Lpp, Row, constant.GE, 1);
Lpp.addConstraint(Row, LpConstant.GE, 1);
}
// Solve LPP and get outliers' weights
LpSolver Solver = new LpSolver(Lpp);
ExitCode = Solver.solve();
for(int i = 0; i < ObsNumber; i++) {
outliers[i] = Lpp.getBestSolution(Lpp.getRows()+VarNumber+i+1);
}
} catch(Exception e){
//e.printStackTrace();
}
return outliers;
}
}
| jinterval/jinterval | jinterval-ir/src/main/java/net/java/jinterval/ir/IRPredictor.java | Java | bsd-2-clause | 10,164 |
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.gde.core.properties;
import com.jme3.gde.core.scene.SceneApplication;
import com.jme3.scene.Spatial;
import java.beans.PropertyEditor;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openide.nodes.PropertySupport;
import org.openide.util.Exceptions;
/**
*
* @author normenhansen
*/
public class UserDataProperty extends PropertySupport.ReadWrite<String> {
private Spatial spatial;
private String name = "null";
private int type = 0;
private List<ScenePropertyChangeListener> listeners = new LinkedList<ScenePropertyChangeListener>();
public UserDataProperty(Spatial node, String name) {
super(name, String.class, name, "");
this.spatial = node;
this.name = name;
this.type = getObjectType(node.getUserData(name));
}
public static int getObjectType(Object type) {
if (type instanceof Integer) {
return 0;
} else if (type instanceof Float) {
return 1;
} else if (type instanceof Boolean) {
return 2;
} else if (type instanceof String) {
return 3;
} else if (type instanceof Long) {
return 4;
} else {
Logger.getLogger(UserDataProperty.class.getName()).log(Level.WARNING, "UserData not editable" + (type == null ? "null" : type.getClass()));
return -1;
}
}
@Override
public String getValue() throws IllegalAccessException, InvocationTargetException {
return spatial.getUserData(name) + "";
}
@Override
public void setValue(final String val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (spatial == null) {
return;
}
try {
SceneApplication.getApplication().enqueue(new Callable<Void>() {
public Void call() throws Exception {
switch (type) {
case 0:
spatial.setUserData(name, Integer.parseInt(val));
break;
case 1:
spatial.setUserData(name, Float.parseFloat(val));
break;
case 2:
spatial.setUserData(name, Boolean.parseBoolean(val));
break;
case 3:
spatial.setUserData(name, val);
break;
case 4:
spatial.setUserData(name, Long.parseLong(val));
break;
default:
// throw new UnsupportedOperationException();
}
return null;
}
}).get();
notifyListeners(null, val);
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
} catch (ExecutionException ex) {
Exceptions.printStackTrace(ex);
}
}
@Override
public PropertyEditor getPropertyEditor() {
return null;
// return new AnimationPropertyEditor(control);
}
public void addPropertyChangeListener(ScenePropertyChangeListener listener) {
listeners.add(listener);
}
public void removePropertyChangeListener(ScenePropertyChangeListener listener) {
listeners.remove(listener);
}
private void notifyListeners(Object before, Object after) {
for (Iterator<ScenePropertyChangeListener> it = listeners.iterator(); it.hasNext();) {
ScenePropertyChangeListener propertyChangeListener = it.next();
propertyChangeListener.propertyChange(getName(), before, after);
}
}
}
| chototsu/MikuMikuStudio | sdk/jme3-core/src/com/jme3/gde/core/properties/UserDataProperty.java | Java | bsd-2-clause | 5,643 |
/*
* Copyright (c) 2012 Tom Denley
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright (c) 2003-2008, Franz-Josef Elmer, All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.netmelody.neoclassycle.renderer;
import org.netmelody.neoclassycle.graph.StrongComponent;
/**
* Interface for rendering a {@link StrongComponent}.
*
* @author Franz-Josef Elmer
*/
public interface StrongComponentRenderer {
/** Renderes the specified {@link StrongComponent}. */
public String render(StrongComponent component);
} | netmelody/neoclassycle | src/main/java/org/netmelody/neoclassycle/renderer/StrongComponentRenderer.java | Java | bsd-2-clause | 1,856 |
package org.mastodon.tracking.mamut.trackmate.wizard;
import org.mastodon.mamut.model.Link;
import org.mastodon.mamut.model.Model;
import org.mastodon.mamut.model.Spot;
import org.mastodon.model.AbstractModelImporter;
public class CreateLargeModelExample
{
private static final int N_STARTING_CELLS = 6;
private static final int N_DIVISIONS = 17;
private static final int N_FRAMES_PER_DIVISION = 5;
private static final double VELOCITY = 5;
private static final double RADIUS = 3;
private final Model model;
public CreateLargeModelExample()
{
this.model = new Model();
}
public Model run()
{
return run( N_STARTING_CELLS, N_DIVISIONS, N_FRAMES_PER_DIVISION );
}
public Model run( final int nStartingCells, final int nDivisions, final int nFramesPerDivision )
{
new AbstractModelImporter< Model >( model ){{ startImport(); }};
final Spot tmp = model.getGraph().vertexRef();
for ( int ic = 0; ic < nStartingCells; ic++ )
{
final double angle = 2d * ic * Math.PI / N_STARTING_CELLS;
final double vx = VELOCITY * Math.cos( angle );
final double vy = VELOCITY * Math.sin( angle );
// final int nframes = N_DIVISIONS * N_FRAMES_PER_DIVISION;
final double x = 0.; // nframes * VELOCITY + vx;
final double y = 0.; // nframes * VELOCITY + vy;
final double z = N_DIVISIONS * VELOCITY;
final double[] pos = new double[] { x, y, z };
final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } };
final Spot mother = model.getGraph().addVertex( tmp ).init( 0, pos, cov );
addBranch( mother, vx, vy, 1, nDivisions, nFramesPerDivision );
}
model.getGraph().releaseRef( tmp );
new AbstractModelImporter< Model >( model ){{ finishImport(); }};
return model;
}
private void addBranch( final Spot start, final double vx, final double vy, final int iteration, final int nDivisions, final int nFramesPerDivision )
{
if ( iteration >= nDivisions ) { return; }
final Spot previousSpot = model.getGraph().vertexRef();
final Spot spot = model.getGraph().vertexRef();
final Spot daughter = model.getGraph().vertexRef();
final Link link = model.getGraph().edgeRef();
final double[] pos = new double[ 3 ];
final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } };
// Extend
previousSpot.refTo( start );
for ( int it = 0; it < nFramesPerDivision; it++ )
{
pos[ 0 ] = previousSpot.getDoublePosition( 0 ) + vx;
pos[ 1 ] = previousSpot.getDoublePosition( 1 ) + vy;
pos[ 2 ] = previousSpot.getDoublePosition( 2 );
final int frame = previousSpot.getTimepoint() + 1;
model.getGraph().addVertex( spot ).init( frame, pos, cov );
model.getGraph().addEdge( previousSpot, spot, link ).init();
previousSpot.refTo( spot );
}
// Divide
for ( int id = 0; id < 2; id++ )
{
final double sign = id == 0 ? 1 : -1;
final double x;
final double y;
final double z;
if ( iteration % 2 == 0 )
{
x = previousSpot.getDoublePosition( 0 );
y = previousSpot.getDoublePosition( 1 );
z = previousSpot.getDoublePosition( 2 ) + sign * VELOCITY * ( 1 - 0.5d * iteration / nDivisions ) * 2;
}
else
{
x = previousSpot.getDoublePosition( 0 ) - sign * vy * ( 1 - 0.5d * iteration / nDivisions ) * 2;
y = previousSpot.getDoublePosition( 1 ) + sign * vx * ( 1 - 0.5d * iteration / nDivisions ) * 2;
z = previousSpot.getDoublePosition( 2 );
}
final int frame = previousSpot.getTimepoint() + 1;
pos[ 0 ] = x;
pos[ 1 ] = y;
pos[ 2 ] = z;
model.getGraph().addVertex( daughter ).init( frame, pos, cov );
model.getGraph().addEdge( previousSpot, daughter, link ).init();
addBranch( daughter, vx, vy, iteration + 1, nDivisions, nFramesPerDivision );
}
model.getGraph().releaseRef( previousSpot );
model.getGraph().releaseRef( spot );
model.getGraph().releaseRef( daughter );
model.getGraph().releaseRef( link );
}
public static void main( final String[] args )
{
final CreateLargeModelExample clme = new CreateLargeModelExample();
final long start = System.currentTimeMillis();
final Model model = clme.run();
final long end = System.currentTimeMillis();
System.out.println( "Model created in " + ( end - start ) + " ms." );
System.out.println( "Total number of spots: " + model.getGraph().vertices().size() );
System.out.println( String.format( "Total memory used by the model: %.1f MB", ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / 1e6d ) );
}
}
| TrNdy/mastodon-tracking | src/test/java/org/mastodon/tracking/mamut/trackmate/wizard/CreateLargeModelExample.java | Java | bsd-2-clause | 4,524 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Bill
*/
public class BackRightAutonomous extends CommandBase {
public BackRightAutonomous() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| TeamSprocket/2013Robot | BackRightAutonomous.java | Java | bsd-3-clause | 952 |
package de.uni.freiburg.iig.telematik.sewol.accesscontrol.rbac.lattice.graphic;
import org.apache.commons.collections15.Factory;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
public class RoleGraphViewer {
Graph<Integer, String> g;
int nodeCount, edgeCount;
Factory<Integer> vertexFactory;
Factory<String> edgeFactory;
/** Creates a new instance of SimpleGraphView */
public RoleGraphViewer() {
// Graph<V, E> where V is the type of the vertices and E is the type of
// the edges
g = new SparseMultigraph<Integer, String>();
nodeCount = 0;
edgeCount = 0;
vertexFactory = new Factory<Integer>() { // My vertex factory
public Integer create() {
return nodeCount++;
}
};
edgeFactory = new Factory<String>() { // My edge factory
public String create() {
return "E" + edgeCount++;
}
};
}
}
| iig-uni-freiburg/SEWOL | src/de/uni/freiburg/iig/telematik/sewol/accesscontrol/rbac/lattice/graphic/RoleGraphViewer.java | Java | bsd-3-clause | 874 |
package com.michaelbaranov.microba.gradient;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import com.michaelbaranov.microba.common.AbstractBoundedTableModel;
/**
* A very basic implementation of {@link AbstractBoundedTableModel} used by
* default by {@link GradientBar}. This implementation has bounds 0 - 100 and
* is mutable.
*
* @author Michael Baranov
*
*/
public class DefaultGradientModel extends AbstractBoundedTableModel {
protected static final int POSITION_COLUMN = 0;
protected static final int COLOR_COLUMN = 1;
protected List positionList = new ArrayList(32);
protected List colorList = new ArrayList(32);
/**
* Constructor.
*/
public DefaultGradientModel() {
super();
positionList.add(new Integer(0));
colorList.add(Color.YELLOW);
positionList.add(new Integer(50));
colorList.add(Color.RED);
positionList.add(new Integer(100));
colorList.add(Color.GREEN);
}
public int getLowerBound() {
return 0;
}
public int getUpperBound() {
return 100;
}
public int getRowCount() {
return positionList.size();
}
public int getColumnCount() {
return 2;
}
public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case POSITION_COLUMN:
return Integer.class;
case COLOR_COLUMN:
return Color.class;
}
return super.getColumnClass(columnIndex);
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case POSITION_COLUMN:
return positionList.get(rowIndex);
case COLOR_COLUMN:
return colorList.get(rowIndex);
}
return null;
}
/**
* Adds a color point.
*
* @param color
* @param position
*/
public void add(Color color, int position) {
colorList.add(color);
positionList.add(new Integer(position));
fireTableDataChanged();
}
/**
* Removes a color point at specified index.
*
* @param index
*/
public void remove(int index) {
colorList.remove(index);
positionList.remove(index);
fireTableDataChanged();
}
/**
* Removes all color points.
*/
public void clear() {
colorList.clear();
positionList.clear();
fireTableDataChanged();
}
}
| ezegarra/microbrowser | microba/com/michaelbaranov/microba/gradient/DefaultGradientModel.java | Java | bsd-3-clause | 2,149 |
package com.percolate.sdk.dto;
import com.fasterxml.jackson.annotation.*;
import com.percolate.sdk.interfaces.HasExtraFields;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FacebookConversationMessage implements Serializable, HasExtraFields {
private static final long serialVersionUID = -7978616001157824820L;
@JsonIgnore
public List<FacebookConversationMessage> extraMessages = new ArrayList<>(); // Set by client to group messages happening around the same time
@JsonIgnore
public String stickerUrl; //Set by client. If message is empty, ApiGetFacebookMessage is used to check for images/stickers.
@JsonIgnore
public List<FacebookMessageAttachment> attachments; //Set by client after calling ApiGetFacebookMessage.
@JsonIgnore
public Flag flag; //Set by client after calling ApiGetFlags
@JsonProperty("id")
protected String id;
@JsonProperty("conversation_id")
protected String conversationId;
@JsonProperty("from")
protected FacebookUser from;
// ApiGetFacebookConversations API returns "from"
// ApiGetFlag API returns "from_user"
// The setter method for this value sets <code>from</code> field.
@JsonProperty("from_user")
protected FacebookUser tempFromUser;
@JsonProperty("created_at")
protected String createdAt;
@JsonProperty("has_attachments")
protected Boolean hasAttachments;
@JsonProperty("message")
protected String message;
@JsonIgnore
protected Map<String, Object> extraFields = new HashMap<>();
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getConversationId() {
return conversationId;
}
public void setConversationId(String conversationId) {
this.conversationId = conversationId;
}
public FacebookUser getFrom() {
return from;
}
public void setFrom(FacebookUser from) {
this.from = from;
}
public void setTempFromUser(FacebookUser from) {
this.tempFromUser = from;
this.from = from;
}
public FacebookUser getTempFromUser() {
return tempFromUser;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public Boolean getHasAttachments() {
return hasAttachments;
}
public void setHasAttachments(Boolean hasAttachments) {
this.hasAttachments = hasAttachments;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public Map<String, Object> getExtraFields() {
if(extraFields == null) {
extraFields = new HashMap<>();
}
return extraFields;
}
@Override
@JsonAnySetter
public void putExtraField(String key, Object value) {
getExtraFields().put(key, value);
}
}
| percolate/percolate-java-sdk | core/src/main/java/com/percolate/sdk/dto/FacebookConversationMessage.java | Java | bsd-3-clause | 3,496 |
package net.minidev.ovh.api.price.dedicatedcloud._2014v1.sbg1a.infrastructure.filer;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Enum of Hourlys
*/
public enum OvhHourlyEnum {
@JsonProperty("iscsi-1200-GB")
iscsi_1200_GB("iscsi-1200-GB"),
@JsonProperty("iscsi-13200g-GB")
iscsi_13200g_GB("iscsi-13200g-GB"),
@JsonProperty("iscsi-3300-GB")
iscsi_3300_GB("iscsi-3300-GB"),
@JsonProperty("iscsi-6600-GB")
iscsi_6600_GB("iscsi-6600-GB"),
@JsonProperty("iscsi-800-GB")
iscsi_800_GB("iscsi-800-GB"),
@JsonProperty("nfs-100-GB")
nfs_100_GB("nfs-100-GB"),
@JsonProperty("nfs-1200-GB")
nfs_1200_GB("nfs-1200-GB"),
@JsonProperty("nfs-13200-GB")
nfs_13200_GB("nfs-13200-GB"),
@JsonProperty("nfs-1600-GB")
nfs_1600_GB("nfs-1600-GB"),
@JsonProperty("nfs-2400-GB")
nfs_2400_GB("nfs-2400-GB"),
@JsonProperty("nfs-3300-GB")
nfs_3300_GB("nfs-3300-GB"),
@JsonProperty("nfs-6600-GB")
nfs_6600_GB("nfs-6600-GB"),
@JsonProperty("nfs-800-GB")
nfs_800_GB("nfs-800-GB");
final String value;
OvhHourlyEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
| UrielCh/ovh-java-sdk | ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/price/dedicatedcloud/_2014v1/sbg1a/infrastructure/filer/OvhHourlyEnum.java | Java | bsd-3-clause | 1,119 |
package org.usfirst.frc369.Robot2017Code.subsystems;
import org.usfirst.frc369.Robot2017Code.Robot;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class LED extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void LEDOn(){
Robot.LEDSys.equals(Relay.Value.kForward);
}
public void LEDelse(){
Robot.LEDSys.equals(Relay.Value.kReverse);
}
public void LEDOff(){
Robot.LEDSys.equals(Relay.Value.kOff);
}
}
| ShadowShitler/Bridgette | src/org/usfirst/frc369/Robot2017Code/subsystems/LED.java | Java | bsd-3-clause | 726 |
/*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk-pre411/LICENSE.txt for details.
*/
package gov.nih.nci.system.webservice;
import gov.nih.nci.system.applicationservice.ApplicationService;
import gov.nih.nci.system.client.proxy.ListProxy;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
import gov.nih.nci.system.query.nestedcriteria.NestedCriteriaPath;
import gov.nih.nci.system.util.ClassCache;
import gov.nih.nci.system.webservice.util.WSUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.xml.rpc.ServiceException;
import org.apache.log4j.Logger;
import org.springframework.remoting.jaxrpc.ServletEndpointSupport;
public class WSQueryImpl extends ServletEndpointSupport implements WSQuery{
private static Logger log = Logger.getLogger(WSQueryImpl.class);
private static ApplicationService applicationService;
private static ClassCache classCache;
private static int resultCountPerQuery = 1000;
public void destroy() {
applicationService = null;
classCache = null;
resultCountPerQuery = 0;
}
protected void onInit() throws ServiceException {
classCache = (ClassCache)getWebApplicationContext().getBean("ClassCache");
applicationService = (ApplicationService)getWebApplicationContext().getBean("ApplicationServiceImpl");
Properties systemProperties = (Properties) getWebApplicationContext().getBean("SystemProperties");
try {
String count = systemProperties.getProperty("resultCountPerQuery");
log.debug("resultCountPerQuery: " + count);
if (count != null) {
resultCountPerQuery = Integer.parseInt(count);
}
} catch (Exception ex) {
log.error("Exception initializing resultCountPerQuery: ", ex);
throw new ServiceException("Exception initializing resultCountPerQuery: ", ex);
}
}
public int getTotalNumberOfRecords(String targetClassName, Object criteria) throws Exception{
return getNestedCriteriaResultSet(targetClassName, criteria, 0).size();
}
public List queryObject(String targetClassName, Object criteria) throws Exception
{
return query(targetClassName,criteria,0);
}
public List query(String targetClassName, Object criteria, int startIndex) throws Exception
{
List results = new ArrayList();
results = getNestedCriteriaResultSet(targetClassName, criteria, startIndex);
List alteredResults = alterResultSet(results);
return alteredResults;
}
private List getNestedCriteriaResultSet(String targetClassName, Object searchCriteria, int startIndex) throws Exception{
List results = new ArrayList();
String searchClassName = getSearchClassName(targetClassName);
try
{
if(searchClassName != null && searchCriteria != null){
List<Object> paramList = new ArrayList<Object>();
paramList.add(searchCriteria);
NestedCriteriaPath pathCriteria = new NestedCriteriaPath(targetClassName,paramList);
results = applicationService.query(pathCriteria, startIndex, targetClassName);
}
else{
throw new Exception("Invalid arguments passed over to the server");
}
}
catch(Exception e)
{
log.error("WSQuery caught an exception: ", e);
throw e;
}
return results;
}
public List getAssociation(Object source, String associationName, int startIndex) throws Exception
{
List results = new ArrayList();
String targetClassName = source.getClass().getName();
log.debug("targetClassName: " + targetClassName);
String hql = "select obj."+associationName+" from "+targetClassName+" obj where obj = ?";
log.debug("hql: " + hql);
List<Object> params = new ArrayList<Object>();
params.add(source);
HQLCriteria criteria = new HQLCriteria(hql,params);
results = getHQLResultSet(targetClassName, criteria, startIndex);
List alteredResults = alterResultSet(results);
return alteredResults;
}
private List getHQLResultSet(String targetClassName, Object searchCriteria, int startIndex) throws Exception{
List results = new ArrayList();
String searchClassName = getSearchClassName(targetClassName);
try
{
if(searchClassName != null && searchCriteria != null){
results = applicationService.query(searchCriteria, startIndex, targetClassName);
}
else{
throw new Exception("Invalid arguments passed over to the server");
}
}
catch(Exception e)
{
log.error("WSQuery caught an exception: ", e);
throw e;
}
return results;
}
private String getSearchClassName(String targetClassName)throws Exception {
String searchClassName = "";
if(targetClassName.indexOf(",")>0){
StringTokenizer st = new StringTokenizer(targetClassName, ",");
while(st.hasMoreTokens()){
String className = st.nextToken();
String validClassName = classCache.getQualifiedClassName(className);
log.debug("validClassName: " + validClassName);
searchClassName += validClassName + ",";
}
searchClassName = searchClassName.substring(0,searchClassName.lastIndexOf(","));
} else{
searchClassName = classCache.getQualifiedClassName(targetClassName);
}
if(searchClassName == null){
throw new Exception("Invalid class name: " + targetClassName);
}
return searchClassName;
}
private List alterResultSet(List results) {
List objList;
if (results instanceof ListProxy)
{
ListProxy listProxy = (ListProxy)results;
objList = listProxy.getListChunk();
}
else
{
objList = results;
}
WSUtils util = new WSUtils();
objList = (List)util.convertToProxy(null, objList);
return objList;
}
}
| NCIP/cacore-sdk-pre411 | SDK4/system/src/gov/nih/nci/system/webservice/WSQueryImpl.java | Java | bsd-3-clause | 5,667 |
package au.gov.ga.geodesy.sitelog.domain.model;
import javax.validation.constraints.Size;
/**
* http://sopac.ucsd.edu/ns/geodesy/doc/igsSiteLog/contact/2004/baseContactLib.xsd:contactType
*/
public class Contact {
private Integer id;
@Size(max = 200)
protected String name;
@Size(max = 200)
protected String telephonePrimary;
@Size(max = 200)
protected String telephoneSecondary;
@Size(max = 200)
protected String fax;
@Size(max = 200)
protected String email;
@SuppressWarnings("unused")
private Integer getId() {
return id;
}
@SuppressWarnings("unused")
private void setId(Integer id) {
this.id = id;
}
/**
* Return name.
*/
public String getName() {
return name;
}
/**
* Set name.
*/
public void setName(String value) {
this.name = value;
}
/**
* Return primary telephone number.
*/
public String getTelephonePrimary() {
return telephonePrimary;
}
/**
* Set primary telephone number.
*/
public void setTelephonePrimary(String value) {
this.telephonePrimary = value;
}
/**
* Return secondary telephone number.
*/
public String getTelephoneSecondary() {
return telephoneSecondary;
}
/**
* Set secondary telephone number.
*/
public void setTelephoneSecondary(String value) {
this.telephoneSecondary = value;
}
/**
* Return fax number.
*/
public String getFax() {
return fax;
}
/**
* Set fax number.
*/
public void setFax(String value) {
this.fax = value;
}
/**
* Return email address.
*/
public String getEmail() {
return email;
}
/**
* Set email address.
*/
public void setEmail(String value) {
this.email = value;
}
}
| GeoscienceAustralia/geodesy-sitelog-domain | src/main/java/au/gov/ga/geodesy/sitelog/domain/model/Contact.java | Java | bsd-3-clause | 1,834 |
package edu.cmu.minorthird.text.gui;
import edu.cmu.minorthird.text.FancyLoader;
import edu.cmu.minorthird.text.TextLabels;
import edu.cmu.minorthird.util.gui.ControlledViewer;
import edu.cmu.minorthird.util.gui.VanillaViewer;
import edu.cmu.minorthird.util.gui.Viewer;
import edu.cmu.minorthird.util.gui.ViewerFrame;
import edu.cmu.minorthird.util.gui.ZoomedViewer;
/**
* View the contents of a bunch of spans, using the util.gui.Viewer framework.
*
* <p> Hopefully this will evolve into a cleaner version of the
* TextBaseViewer, TextBaseEditor, etc suite. It replaces an earlier
* attempt, the SpanLooperViewer.
*
* @author William Cohen
*/
public class ZoomingTextLabelsViewer extends ZoomedViewer{
static final long serialVersionUID=20080202L;
public ZoomingTextLabelsViewer(TextLabels labels){
Viewer zoomedOut=new ControlledViewer(new TextLabelsViewer(labels),new MarkupControls(labels));
Viewer zoomedIn=new VanillaViewer("[Empty TextBase]");
if(labels.getTextBase().size()>0){
zoomedIn=new SpanViewer(labels,labels.getTextBase().documentSpanIterator().next());
}
this.setSubViews(zoomedOut,zoomedIn);
}
// test case
public static void main(String[] argv){
try{
final TextLabels labels=FancyLoader.loadTextLabels(argv[0]);
new ViewerFrame(argv[0],new ZoomingTextLabelsViewer(labels));
}catch(Exception e){
e.printStackTrace();
System.out.println("Usage: labelKey");
}
}
}
| TeamCohen/MinorThird | src/main/java/edu/cmu/minorthird/text/gui/ZoomingTextLabelsViewer.java | Java | bsd-3-clause | 1,434 |
/**
*============================================================================
* The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC,
* and Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-workflow/LICENSE.txt for details.
*============================================================================
**/
package gov.nih.nci.cagrid.portal.portlet.workflow.mvc;
import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowExecutionService;
import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowRegistryService;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SessionEprs;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SubmitWorkflowCommand;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowDescription;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowSubmitted;
import gov.nih.nci.cagrid.portal.portlet.workflow.util.Utils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.PortletRequestUtils;
import org.springframework.web.portlet.mvc.SimpleFormController;
@Controller
@RequestMapping(params={"action=newInstance"})
@SuppressWarnings("deprecation")
public class NewInstanceFormController extends SimpleFormController {
protected final Log log = LogFactory.getLog(getClass());
@Autowired
private WorkflowExecutionService workflowService;
@Autowired
@Qualifier("MyExperiment")
private WorkflowRegistryService registry;
@Autowired
private SessionEprs eprs;
@Autowired
private Utils utilities;
/* @see org.springframework.web.portlet.mvc.SimpleFormController#processFormSubmission(javax.portlet.ActionRequest, javax.portlet.ActionResponse, java.lang.Object, org.springframework.validation.BindException) */
@Override
protected void processFormSubmission(ActionRequest request, ActionResponse response, Object command, BindException errors) throws Exception {
String id = PortletRequestUtils.getStringParameter(request, "id", "NaN");
log.debug("processFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id - " + id);
SubmitWorkflowCommand cmd = (SubmitWorkflowCommand)command;
log.debug("Command Object: " + cmd.getTheWorkflow());
try {
WorkflowDescription selectedWorkflow = registry.getWorkflow(id);
log.info("Submitting the selected workflow.. #" + id);
String tempFilePath = saveWorkflowDefinition(selectedWorkflow);
EndpointReferenceType epr = workflowService.submitWorkflow(selectedWorkflow.getName(), tempFilePath, cmd.getInputValues());
UUID uuid = UUID.randomUUID();
log.debug("Will submit UUID : " + uuid.toString());
eprs.put(uuid.toString(), new WorkflowSubmitted(epr, selectedWorkflow, "Submitted"));
cmd.setResult("The Workflow was submitted successfully.");
log.info("The Workflow was submitted successfully.");
} catch(Throwable e) {
log.error("Error submitting workflow", e);
Throwable ex = e.getCause();
while(ex.getCause() !=null ) {
ex = ex.getCause();
}
cmd.setResult(e.getClass().getSimpleName() + " submitting workflow: " + e.getMessage());
}
}
/* @see org.springframework.web.portlet.mvc.SimpleFormController#renderFormSubmission(javax.portlet.RenderRequest, javax.portlet.RenderResponse, java.lang.Object, org.springframework.validation.BindException) */
@Override
protected ModelAndView renderFormSubmission(RenderRequest request, RenderResponse response, Object cmd, BindException errors) throws Exception {
log.debug("renderFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN"));
return new ModelAndView("json", "contents", ((SubmitWorkflowCommand)cmd).getResult());
}
/* @see org.springframework.web.portlet.mvc.SimpleFormController#showForm(javax.portlet.RenderRequest, javax.portlet.RenderResponse, org.springframework.validation.BindException) */
@Override
protected ModelAndView showForm(RenderRequest request, RenderResponse response, BindException errors) throws Exception {
String id = PortletRequestUtils.getStringParameter(request, "id", "NaN");
log.info("showForm. Action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id: " + id);
SubmitWorkflowCommand cmd = new SubmitWorkflowCommand();
cmd.setTheWorkflow(registry.getWorkflow(id));
return new ModelAndView("newInstance", "cmd", cmd);
}
/**
* Download the workflow definition to local filesystem
* @param wd Workflow Definition
* @return path of temporary file
* @throws IOException
* @throws HttpException
*/
private String saveWorkflowDefinition(WorkflowDescription wd) throws HttpException, IOException {
File tmpPath = new File( System.getProperty("java.io.tmpdir")+"/taverna" );
tmpPath.mkdirs();
String defPath = tmpPath.getAbsolutePath()+"/myexperiment_"+wd.getId()+"_v"+wd.getVersion()+".t2flow";
if(new File(defPath).exists()) { log.debug("Definition temporary file already exists so not downloading again."); return defPath; }
getUtilities().saveFile(defPath, getUtilities().download(wd.getContentURI()) );
return defPath;
}
public SessionEprs getSessionEprs() {return eprs;}
public void setSessionEprs(SessionEprs sessionEprs) {this.eprs = sessionEprs;}
public WorkflowExecutionService getWorkflowService() {return workflowService;}
public void setWorkflowService(WorkflowExecutionService workflowService) {this.workflowService = workflowService;}
public WorkflowRegistryService getRegistry() {return registry;}
public void setRegistry(WorkflowRegistryService registry) {this.registry = registry;}
public Utils getUtilities() {return utilities;}
public void setUtilities(Utils utilities) {this.utilities = utilities;}
}
| NCIP/cagrid-workflow | workflow-portlet/src/main/java/gov/nih/nci/cagrid/portal/portlet/workflow/mvc/NewInstanceFormController.java | Java | bsd-3-clause | 6,693 |
/*
* Copyright (c) 2007 BUSINESS OBJECTS SOFTWARE LIMITED
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Business Objects nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* IntellicutList.java
* Creation date: Dec 10th 2002
* By: Ken Wong
*/
package org.openquark.gems.client;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.JList;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import org.openquark.gems.client.IntellicutListModel.FilterLevel;
import org.openquark.gems.client.IntellicutListModelAdapter.IntellicutListEntry;
import org.openquark.gems.client.IntellicutManager.IntellicutMode;
/**
* A list that encapsulates all the details associated with populating
* a list with the unqualified names of gems.
* @author Ken Wong
* @author Frank Worsley
*/
public class IntellicutList extends JList {
private static final long serialVersionUID = -8515575227984050475L;
/** The last list index that was visible when the state was saved. */
private int savedVisibleIndex = -1;
/** The last list entry that was visible when the state was saved. */
private IntellicutListEntry savedVisibleEntry = null;
/** The list entry that was selected when the state was saved. */
private IntellicutListEntry savedSelectedEntry = null;
/** Whether or not this list should be drawn transparently. */
private boolean transparent = false;
/**
* Constructor for IntellicutList.
*/
public IntellicutList(IntellicutMode mode) {
setName("MatchingGemsList");
setCellRenderer(new IntellicutListRenderer(mode));
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
/**
* Enables the list to be transparent. If the list is transparent non selected list items
* will let the components below them show through. Selected list items will draw a blue
* semi-transparent tint as their background.
* @param value whether or not the list should be transparent
*/
void setTransparent(boolean value) {
this.transparent = value;
updateUI();
}
/**
* @return whether or not the intellicut list is transparent
*/
public boolean isTransparent() {
return transparent;
}
/**
* Saves the currently selected list item and the scroll position of the
* list so that the list state can be restored later.
*/
private void saveListState() {
IntellicutListModel listModel = (IntellicutListModel) getModel();
savedVisibleEntry = null;
savedSelectedEntry = null;
savedVisibleIndex = getLastVisibleIndex();
int selectedIndex = getSelectedIndex();
try {
savedVisibleEntry = listModel.get(savedVisibleIndex);
savedSelectedEntry = listModel.get(selectedIndex);
// We only want to make the selected entry visible again after refreshing
// the list if it was visible before.
if (selectedIndex > getLastVisibleIndex() || selectedIndex < getFirstVisibleIndex()) {
savedSelectedEntry = null;
}
} catch (Exception ex) {
// This might throw a NullPointerException or ArrayIndexOutOfBoundsException
// if the model is not initialized. In that case there is no index we can restore.
}
}
/**
* Restores the previously saved list state as closely as possible.
*/
private void restoreListState() {
IntellicutListModel listModel = (IntellicutListModel) getModel();
int newSelectedIndex = listModel.indexOf(savedSelectedEntry);
int newVisibleIndex = listModel.indexOf(savedVisibleEntry);
if (newVisibleIndex == -1) {
newVisibleIndex = savedVisibleIndex;
}
// We have to add one cell height, otherwise the cell will be just
// outside of the visible range of the list. ensureIndexIsVisible doesn't
// work here since we want the index to appear at the very bottom.
Point newLocation = indexToLocation(newVisibleIndex);
if (newLocation != null) {
newLocation.y += getCellBounds(0, 0).height;
scrollRectToVisible(new Rectangle(newLocation));
}
if (newSelectedIndex != -1) {
setSelectedIndex(newSelectedIndex);
ensureIndexIsVisible(newSelectedIndex);
} else {
setSelectedIndex(0);
}
}
/**
* Refreshes the list while remembering the selected item and scroll position
* as closely as possible. Simply refreshing the list model will not remember
* the list state.
* @param prefix the new prefix for values in the list
*/
public void refreshList(String prefix) {
IntellicutListModel listModel = (IntellicutListModel) getModel();
saveListState();
listModel.refreshList(prefix);
restoreListState();
}
/**
* Finds the JViewport this list is embedded in.
* @return the viewport or null if there is no viewport
*/
private JViewport getViewport() {
Container parent = getParent();
while (parent != null && !(parent instanceof JViewport)) {
parent = parent.getParent ();
}
return (JViewport) parent;
}
/**
* Scrolls the given index as close as possible to the top of the list's viewport.
* @param index index of the item to scroll to the top
*/
void scrollToTop(int index) {
Point location = indexToLocation(index);
if (location == null) {
return;
}
JViewport viewport = getViewport();
// Scroll this element as close to the top as possible.
if (viewport.getViewSize().height - location.y < viewport.getSize().height) {
location.y -= viewport.getSize().height - viewport.getViewSize().height + location.y;
}
viewport.setViewPosition(location);
}
/**
* Sets the current gem filtering level.
*
* The list is automatically refreshed after doing this. This method also saves
* the list's displayed state as opposed to just setting the filter level which
* will not remember the list state.
* @param filterLevel the new level to filter at
*/
void setFilterLevel(FilterLevel filterLevel) {
if (filterLevel == null) {
throw new NullPointerException("filterLevel must not be null in IntellicutList.setFilterLevel");
}
IntellicutListModel listModel = (IntellicutListModel) getModel();
saveListState();
listModel.setFilterLevel(filterLevel);
restoreListState();
}
/**
* Returns the user selected IntellicutListEntry
* @return IntellicutListEntry
*/
IntellicutListEntry getSelected(){
return getModel().getSize() > 0 ? (IntellicutListEntry) getSelectedValue() : null;
}
/**
* We want tooltips to be displayed to the right of an item.
* If there is no item at the coordinates it returns null.
* @param e the mouse event for which to determine the location
* @return the tooltip location for the list item at the coordinates of the mouse event
*/
@Override
public Point getToolTipLocation(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (index == -1) {
return null;
}
Rectangle cellBounds = getCellBounds(index, index);
// take off 50 and add 5 for good looks
return new Point (cellBounds.x + cellBounds.width - 50, cellBounds.y + 5);
}
/**
* @param e the MouseEvent for which to get the tooltip text
* @return the tooltip text for the list item at the coordinates or null if there is no
* item at the coordinates
*/
@Override
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (index == -1) {
return null;
}
IntellicutListEntry listEntry = (IntellicutListEntry) getModel().getElementAt(index);
if (listEntry == null) {
return null;
}
IntellicutListModel listModel = (IntellicutListModel) getModel();
return listModel.getAdapter().getToolTipTextForEntry(listEntry, this);
}
}
| levans/Open-Quark | src/Quark_Gems/src/org/openquark/gems/client/IntellicutList.java | Java | bsd-3-clause | 10,380 |
/*
* HE_Mesh Frederik Vanhoutte - www.wblut.com
*
* https://github.com/wblut/HE_Mesh
* A Processing/Java library for for creating and manipulating polygonal meshes.
*
* Public Domain: http://creativecommons.org/publicdomain/zero/1.0/
* I , Frederik Vanhoutte, have waived all copyright and related or neighboring
* rights.
*
* This work is published from Belgium. (http://creativecommons.org/publicdomain/zero/1.0/)
*
*/
package wblut.geom;
/**
* Interface for implementing mutable mathematical operations on 3D coordinates.
*
* All of the operators defined in the interface change the calling object. All
* operators use the label "Self", such as "addSelf" to indicate this.
*
* @author Frederik Vanhoutte
*
*/
public interface WB_MutableCoordinateMath3D extends WB_CoordinateMath3D {
/**
* Add coordinate values.
*
* @param x
* @return this
*/
public WB_Coord addSelf(final double... x);
/**
* Add coordinate values.
*
* @param p
* @return this
*/
public WB_Coord addSelf(final WB_Coord p);
/**
* Subtract coordinate values.
*
* @param x
* @return this
*/
public WB_Coord subSelf(final double... x);
/**
* Subtract coordinate values.
*
* @param p
* @return this
*/
public WB_Coord subSelf(final WB_Coord p);
/**
* Multiply by factor.
*
* @param f
* @return this
*/
public WB_Coord mulSelf(final double f);
/**
* Divide by factor.
*
* @param f
* @return this
*/
public WB_Coord divSelf(final double f);
/**
* Add multiple of coordinate values.
*
* @param f
* multiplier
* @param x
* @return this
*/
public WB_Coord addMulSelf(final double f, final double... x);
/**
* Add multiple of coordinate values.
*
* @param f
* @param p
* @return this
*/
public WB_Coord addMulSelf(final double f, final WB_Coord p);
/**
* Multiply this coordinate by factor f and add other coordinate values
* multiplied by g.
*
* @param f
* @param g
* @param x
* @return this
*/
public WB_Coord mulAddMulSelf(final double f, final double g, final double... x);
/**
* Multiply this coordinate by factor f and add other coordinate values
* multiplied by g.
*
* @param f
* @param g
* @param p
* @return this
*/
public WB_Coord mulAddMulSelf(final double f, final double g, final WB_Coord p);
/**
*
*
* @param p
* @return this
*/
public WB_Coord crossSelf(final WB_Coord p);
/**
* Normalize this vector. Return the length before normalization. If this
* vector is degenerate 0 is returned and the vector remains the zero
* vector.
*
* @return this
*/
public double normalizeSelf();
/**
* If vector is larger than given value, trim vector.
*
* @param d
* @return this
*/
public WB_Coord trimSelf(final double d);
}
| DweebsUnited/CodeMonkey | java/CodeMonkey/HEMesh/wblut/geom/WB_MutableCoordinateMath3D.java | Java | bsd-3-clause | 2,810 |
/*================================================================================
Copyright (c) 2012 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class StaticRouteProfile extends ApplyProfile {
public String key;
public String getKey() {
return this.key;
}
public void setKey(String key) {
this.key=key;
}
} | xebialabs/vijava | src/com/vmware/vim25/StaticRouteProfile.java | Java | bsd-3-clause | 1,954 |
package com.krishagni.catissueplus.core.biospecimen.events;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.krishagni.catissueplus.core.administrative.events.StorageLocationSummary;
import com.krishagni.catissueplus.core.common.events.UserSummary;
import com.krishagni.catissueplus.core.de.events.ExtensionDetail;
public class SpecimenAliquotsSpec {
private Long parentId;
private String parentLabel;
private String derivedReqCode;
private String cpShortTitle;
private Integer noOfAliquots;
private String labels;
private String barcodes;
private BigDecimal qtyPerAliquot;
private String specimenClass;
private String type;
private BigDecimal concentration;
private Date createdOn;
private UserSummary createdBy;
private String parentContainerName;
private String containerType;
private String containerName;
private String positionX;
private String positionY;
private Integer position;
private List<StorageLocationSummary> locations;
private Integer freezeThawCycles;
private Integer incrParentFreezeThaw;
private Boolean closeParent;
private Boolean createDerived;
private Boolean printLabel;
private String comments;
private ExtensionDetail extensionDetail;
private boolean linkToReqs;
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getParentLabel() {
return parentLabel;
}
public void setParentLabel(String parentLabel) {
this.parentLabel = parentLabel;
}
public String getDerivedReqCode() {
return derivedReqCode;
}
public void setDerivedReqCode(String derivedReqCode) {
this.derivedReqCode = derivedReqCode;
}
public String getCpShortTitle() {
return cpShortTitle;
}
public void setCpShortTitle(String cpShortTitle) {
this.cpShortTitle = cpShortTitle;
}
public Integer getNoOfAliquots() {
return noOfAliquots;
}
public void setNoOfAliquots(Integer noOfAliquots) {
this.noOfAliquots = noOfAliquots;
}
public String getLabels() {
return labels;
}
public void setLabels(String labels) {
this.labels = labels;
}
public String getBarcodes() {
return barcodes;
}
public void setBarcodes(String barcodes) {
this.barcodes = barcodes;
}
public BigDecimal getQtyPerAliquot() {
return qtyPerAliquot;
}
public void setQtyPerAliquot(BigDecimal qtyPerAliquot) {
this.qtyPerAliquot = qtyPerAliquot;
}
public String getSpecimenClass() {
return specimenClass;
}
public void setSpecimenClass(String specimenClass) {
this.specimenClass = specimenClass;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public BigDecimal getConcentration() {
return concentration;
}
public void setConcentration(BigDecimal concentration) {
this.concentration = concentration;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public UserSummary getCreatedBy() {
return createdBy;
}
public void setCreatedBy(UserSummary createdBy) {
this.createdBy = createdBy;
}
public String getParentContainerName() {
return parentContainerName;
}
public void setParentContainerName(String parentContainerName) {
this.parentContainerName = parentContainerName;
}
public String getContainerType() {
return containerType;
}
public void setContainerType(String containerType) {
this.containerType = containerType;
}
public String getContainerName() {
return containerName;
}
public void setContainerName(String containerName) {
this.containerName = containerName;
}
public String getPositionX() {
return positionX;
}
public void setPositionX(String positionX) {
this.positionX = positionX;
}
public String getPositionY() {
return positionY;
}
public void setPositionY(String positionY) {
this.positionY = positionY;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public List<StorageLocationSummary> getLocations() {
return locations;
}
public void setLocations(List<StorageLocationSummary> locations) {
this.locations = locations;
}
public Integer getFreezeThawCycles() {
return freezeThawCycles;
}
public void setFreezeThawCycles(Integer freezeThawCycles) {
this.freezeThawCycles = freezeThawCycles;
}
public Integer getIncrParentFreezeThaw() {
return incrParentFreezeThaw;
}
public void setIncrParentFreezeThaw(Integer incrParentFreezeThaw) {
this.incrParentFreezeThaw = incrParentFreezeThaw;
}
public Boolean getCloseParent() {
return closeParent;
}
public void setCloseParent(Boolean closeParent) {
this.closeParent = closeParent;
}
public boolean closeParent() {
return closeParent != null && closeParent;
}
public Boolean getCreateDerived() {
return createDerived;
}
public void setCreateDerived(Boolean createDerived) {
this.createDerived = createDerived;
}
public boolean createDerived() { return createDerived != null && createDerived; }
public Boolean getPrintLabel() {
return printLabel;
}
public void setPrintLabel(Boolean printLabel) {
this.printLabel = printLabel;
}
public boolean printLabel() { return printLabel != null && printLabel; }
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public ExtensionDetail getExtensionDetail() {
return extensionDetail;
}
public void setExtensionDetail(ExtensionDetail extensionDetail) {
this.extensionDetail = extensionDetail;
}
public boolean isLinkToReqs() {
return linkToReqs;
}
public void setLinkToReqs(boolean linkToReqs) {
this.linkToReqs = linkToReqs;
}
} | krishagni/openspecimen | WEB-INF/src/com/krishagni/catissueplus/core/biospecimen/events/SpecimenAliquotsSpec.java | Java | bsd-3-clause | 5,811 |
// $Id: MainClass.java,v 1.6 2003/10/07 21:46:08 idgay Exp $
/* tab:4
* "Copyright (c) 2000-2003 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
* Copyright (c) 2002-2003 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
/**
* @author Wei Hong
*/
//***********************************************************************
//***********************************************************************
//this is the main class that holds all global variables
//and from where "main" is run.
//the global variables can be accessed as: MainClass.MainFrame for example.
//***********************************************************************
//***********************************************************************
package net.tinyos.tinydb.topology;
import java.util.*;
import net.tinyos.tinydb.*;
import net.tinyos.tinydb.topology.event.*;
import net.tinyos.tinydb.topology.util.*;
import net.tinyos.tinydb.topology.PacketAnalyzer.*;
import net.tinyos.tinydb.topology.Dialog.*;
import net.tinyos.tinydb.topology.Packet.*;
import javax.swing.event.*;
import java.beans.*;
import java.awt.*;
import java.io.*;
import net.tinyos.tinydb.parser.*;
public class MainClass implements ResultListener
{
public static MainFrame mainFrame;
public static DisplayManager displayManager;
public static ObjectMaintainer objectMaintainer;
public static SensorAnalyzer sensorAnalyzer;
public static LocationAnalyzer locationAnalyzer;
public static Vector packetAnalyzers;
public static TinyDBQuery topologyQuery;
public static boolean topologyQueryRunning = false;
public static String topologyQueryText = "select nodeid, parent, light, temp, voltage epoch duration 2048";
TinyDBNetwork nw;
public MainClass(TinyDBNetwork nw, byte qid) throws IOException
{
this.nw = nw;
nw.addResultListener(this, false, qid);
mainFrame = new MainFrame("Sensor Network Topology", nw);
displayManager = new DisplayManager(mainFrame);
packetAnalyzers = new Vector();
objectMaintainer = new ObjectMaintainer();
objectMaintainer.AddEdgeEventListener(displayManager);
objectMaintainer.AddNodeEventListener(displayManager);
locationAnalyzer = new LocationAnalyzer();
sensorAnalyzer = new SensorAnalyzer();
packetAnalyzers.add(objectMaintainer);
packetAnalyzers.add(sensorAnalyzer);
//make the MainFrame visible as the last thing
mainFrame.setVisible(true);
try
{
System.out.println("Topology Query: " + topologyQueryText);
topologyQuery = SensorQueryer.translateQuery(topologyQueryText, qid);
}
catch (ParseException pe)
{
System.out.println("Topology Query: " + topologyQueryText);
System.out.println("Parse Error: " + pe.getParseError());
topologyQuery = null;
}
nw.sendQuery(topologyQuery);
TinyDBMain.notifyAddedQuery(topologyQuery);
topologyQueryRunning = true;
}
public void addResult(QueryResult qr) {
Packet packet = new Packet(qr);
try {
if (packet.getNodeId().intValue() < 0 ||
packet.getNodeId().intValue() > 128 ||
packet.getParent().intValue() < 0 ||
packet.getParent().intValue() > 128 )
return;
} catch (ArrayIndexOutOfBoundsException e) {
return;
}
PacketEventListener currentListener;
for(Enumeration list = packetAnalyzers.elements(); list.hasMoreElements();)
{
currentListener = (PacketEventListener)list.nextElement();
PacketEvent e = new PacketEvent(nw, packet,
Calendar.getInstance().getTime());
currentListener.PacketReceived(e);//send the listener an event
}
}
}
| fresskarma/tinyos-1.x | tools/java/net/tinyos/tinydb/topology/MainClass.java | Java | bsd-3-clause | 4,833 |
package me.hatter.tools.resourceproxy.commons.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
public class FilePrintWriter extends PrintWriter {
public FilePrintWriter(File file) throws FileNotFoundException {
super(new OutputStreamWriter(new FileOutputStream(file)));
}
public FilePrintWriter(File file, String charset) throws UnsupportedEncodingException, FileNotFoundException {
super(new OutputStreamWriter(new FileOutputStream(file), charset));
}
}
| KingBowser/hatter-source-code | resourceproxy/commons/src/me/hatter/tools/resourceproxy/commons/io/FilePrintWriter.java | Java | bsd-3-clause | 646 |
// Generated by delombok at Sat Jun 11 11:12:44 CEST 2016
public final class Zoo {
private final String meerkat;
private final String warthog;
public Zoo create() {
return new Zoo("tomon", "pumbaa");
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
Zoo(final String meerkat, final String warthog) {
this.meerkat = meerkat;
this.warthog = warthog;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public static class ZooBuilder {
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
private String meerkat;
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
private String warthog;
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
ZooBuilder() {
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public ZooBuilder meerkat(final String meerkat) {
this.meerkat = meerkat;
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public ZooBuilder warthog(final String warthog) {
this.warthog = warthog;
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public Zoo build() {
return new Zoo(meerkat, warthog);
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public java.lang.String toString() {
return "Zoo.ZooBuilder(meerkat=" + this.meerkat + ", warthog=" + this.warthog + ")";
}
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public static ZooBuilder builder() {
return new ZooBuilder();
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public String getMeerkat() {
return this.meerkat;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public String getWarthog() {
return this.warthog;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public boolean equals(final java.lang.Object o) {
if (o == this) return true;
if (!(o instanceof Zoo)) return false;
final Zoo other = (Zoo) o;
final java.lang.Object this$meerkat = this.getMeerkat();
final java.lang.Object other$meerkat = other.getMeerkat();
if (this$meerkat == null ? other$meerkat != null : !this$meerkat.equals(other$meerkat)) return false;
final java.lang.Object this$warthog = this.getWarthog();
final java.lang.Object other$warthog = other.getWarthog();
if (this$warthog == null ? other$warthog != null : !this$warthog.equals(other$warthog)) return false;
return true;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public int hashCode() {
final int PRIME = 59;
int result = 1;
final java.lang.Object $meerkat = this.getMeerkat();
result = result * PRIME + ($meerkat == null ? 43 : $meerkat.hashCode());
final java.lang.Object $warthog = this.getWarthog();
result = result * PRIME + ($warthog == null ? 43 : $warthog.hashCode());
return result;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public java.lang.String toString() {
return "Zoo(meerkat=" + this.getMeerkat() + ", warthog=" + this.getWarthog() + ")";
}
}
| AlexejK/lombok-intellij-plugin | testData/after/value/ValueAndBuilder93.java | Java | bsd-3-clause | 3,489 |
package ru.ac.uniyar.dots;
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);
}
} | ivparamonov/android-course-examples | dots/app/src/androidTest/java/ru/ac/uniyar/dots/ApplicationTest.java | Java | bsd-3-clause | 348 |
/*
* Copyright (c) 2005, Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of the University of California, Berkeley nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package blog.model;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import blog.bn.BayesNetVar;
import blog.sample.EvalContext;
/**
* A Formula consisting of a single boolean-valued term.
*
* @see blog.model.Term
* @see blog.model.Formula
*/
public class AtomicFormula extends Formula {
public AtomicFormula(Term sent) {
this.sent = sent;
}
public Term getTerm() {
return sent;
}
public Object evaluate(EvalContext context) {
Object value = sent.evaluate(context);
if (value == null) {
return null;
}
if (!(value instanceof Boolean)) {
throw new IllegalStateException("Sentence " + sent
+ " has non-Boolean value " + value);
}
return (value.equals(Boolean.TRUE) ? Boolean.TRUE : Boolean.FALSE);
}
/**
* Returns the (basic or derived) random variable that this atomic formula
* corresponds to under the given assignment. This is just the random variable
* corresponding to underlying Boolean term.
*/
public BayesNetVar getVariable() {
return sent.getVariable();
}
/**
* Returns a singleton collection containing the term in this atomic formula.
*/
public Collection getSubExprs() {
return Collections.singletonList(sent);
}
/**
* Returns true.
*/
public boolean isLiteral() {
return true;
}
public List<Term> getTopLevelTerms() {
return Collections.singletonList(sent);
}
public Set getSatisfiersIfExplicit(EvalContext context, LogicalVar subject,
GenericObject genericObj) {
Set result = null;
context.assign(subject, genericObj);
// The only time we can determine the satisfiers is if this
// formula can be evaluated on genericObj.
Boolean value = (Boolean) evaluate(context);
if (value != null) {
result = (value.booleanValue() == true ? Formula.ALL_OBJECTS
: Collections.EMPTY_SET);
}
context.unassign(subject);
return result;
}
public Set getNonSatisfiersIfExplicit(EvalContext context,
LogicalVar subject, GenericObject genericObj) {
Set result = null;
context.assign(subject, genericObj);
// The only time we can determine the non-satisfiers is if
// this formula can be evaluated on genericObj.
Boolean value = (Boolean) evaluate(context);
if (value != null) {
result = (value.booleanValue() == false ? Formula.ALL_OBJECTS
: Collections.EMPTY_SET);
}
context.unassign(subject);
return result;
}
/**
* Two atomic formulas are equal if their underlying terms are equal.
*/
public boolean equals(Object o) {
if (o instanceof AtomicFormula) {
AtomicFormula other = (AtomicFormula) o;
return sent.equals(other.getTerm());
}
return false;
}
public int hashCode() {
return sent.hashCode();
}
/**
* Returns the string representation of the underlying term.
*/
public String toString() {
return sent.toString();
}
/**
* Returns true if the underlying term satisfies the type/scope constraints
* and has a Boolean type.
*/
public boolean checkTypesAndScope(Model model, Map scope, Type childType) {
Term sentInScope = sent.getTermInScope(model, scope);
if (sentInScope == null) {
return false;
}
sent = sentInScope;
if (!sent.getType().isSubtypeOf(BuiltInTypes.BOOLEAN)) {
System.err.println("Error: Non-Boolean term treated as "
+ "atomic formula: " + sent);
return false;
}
return true;
}
public ArgSpec replace(Term t, ArgSpec another) {
Term newSent = (Term) sent.replace(t, another);
if (newSent != sent)
return compileAnotherIfCompiled(new AtomicFormula(newSent));
return this;
}
public ArgSpec getSubstResult(Substitution subst, Set<LogicalVar> boundVars) {
return new AtomicFormula((Term) sent.getSubstResult(subst, boundVars));
}
/** The Term instance, assumed to be boolean-valued */
private Term sent;
}
| BayesianLogic/blog | src/main/java/blog/model/AtomicFormula.java | Java | bsd-3-clause | 5,685 |
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.magetab;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* A repository of controlled vocabulary terms. Must have a non-null, non-empty name
*/
public final class TermSource {
private String name;
private String file;
private String version;
/**
* Create new TermSource with given name.
* @param name the repository name; must not be blank or null
*/
public TermSource(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Term source name must not be blank");
}
this.name = name;
}
/**
* Create new TermSource with given name, url and version.
* @param name the repository name
* @param file the url (called file in MAGE TAB terminology)
* @param version the version;
*/
public TermSource(String name, String file, String version) {
this(name);
this.file = file;
this.version = version;
}
/**
* @return the file
*/
public String getFile() {
return this.file;
}
/**
* @param file the file to set
*/
public void setFile(String file) {
this.file = file;
}
/**
* @return the name
*/
public String getName() {
return this.name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Term source name must not be blank");
}
this.name = name;
}
/**
* @return the version
*/
public String getVersion() {
return this.version;
}
/**
* @param version the version to set
*/
public void setVersion(String version) {
this.version = version;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TermSource)) {
return false;
}
if (obj == this) {
return true;
}
TermSource ts = (TermSource) obj;
return new EqualsBuilder().append(this.getName(), ts.getName()).append(this.getFile(), ts.getFile()).append(
this.getVersion(), ts.getVersion()).isEquals();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.getName()).append(this.getFile()).append(this.getVersion())
.toHashCode();
}
}
| NCIP/caarray | software/caarray-common.jar/src/main/java/gov/nih/nci/caarray/magetab/TermSource.java | Java | bsd-3-clause | 3,123 |
package com.github.dandelion.gua.core.field;
public enum EventTrackingField implements AnalyticsField, AnalyticsCreateField {
@AnalyticsFieldControl(AnalyticsFieldControl.Policy.TEXT) eventCategory,
@AnalyticsFieldControl(AnalyticsFieldControl.Policy.TEXT) eventAction,
@AnalyticsFieldControl(AnalyticsFieldControl.Policy.TEXT) eventLabel,
@AnalyticsFieldControl(AnalyticsFieldControl.Policy.INTEGER) eventValue,
}
| dandelion/dandelion-gua | gua-core/src/main/java/com/github/dandelion/gua/core/field/EventTrackingField.java | Java | bsd-3-clause | 432 |
/*L
* Copyright Georgetown University, Washington University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cab2b/LICENSE.txt for details.
*/
package edu.wustl.cab2b.server.analyticalservice;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.wustl.cab2b.common.analyticalservice.ServiceDetailsInterface;
import edu.wustl.cab2b.common.exception.RuntimeException;
/**
* This is a singleton class which parses the EntityToAnalyticalServiceMapping.xml file and stores the mapping information into an internal map.
* This class provieds the methods to get the service interface and the service invoker interface.
* @author chetan_patil
*/
public class EntityToAnalyticalServiceMapper {
/**
* Self reference
*/
private static EntityToAnalyticalServiceMapper entityServiceMapper = null;
/**
* Map to store the entity to service mapping
*/
private Map<String, List<String>> entityServiceNameMap = new HashMap<String, List<String>>();
/**
* Map to store the service to method mapping
*/
private Map<String, List<String>> serviceNameDetailClassNameMap = new HashMap<String, List<String>>();
/**
* Map to store the service detail class and the corresponding service invoker class.
*/
private Map<String, String> serviceDetailInvokerMap = new HashMap<String, String>();
/**
* Name of the Entity Service Mapper file
*/
private static final String ENTITY_SERVICE_MAPPER_FILENAME = "EntityToAnalyticalServiceMapping.xml";
/**
* Entity tag
*/
private static final String ENTITY = "entity";
/**
* Service tag
*/
private static final String SERVICE = "service";
/**
* Method tag
*/
private static final String METHOD = "method";
/**
* Name attribute
*/
private static final String ATTRIBUTE_NAME = "name";
/**
* Service Detail Class attribute
*/
private static final String ATTRIBUTE_SERVICE_DETAIL_CLASS = "serviceDetailClass";
/**
* Service Invoker Class attribute
*/
private static final String ATTRIBUTE_SERVICE_INVOKER_CLASS = "serviceInvokerClass";
/**
* Service name attribute
*/
private static final String ATTRIBUTE_SERVICE_NAME = "serviceName";
/**
* Private constructor
*/
private EntityToAnalyticalServiceMapper() {
parseEntityServiceMapperXMLFile();
}
/**
* This method returns an instance of this class
* @return an instance of this class
*/
public static synchronized EntityToAnalyticalServiceMapper getInstance() {
if (entityServiceMapper == null) {
entityServiceMapper = new EntityToAnalyticalServiceMapper();
}
return entityServiceMapper;
}
/**
* This method parses the EntityServiceMapper.XML file and stores the parsed data into an internally maintained Maps.
*/
private void parseEntityServiceMapperXMLFile() {
//Read the xml file
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(
ENTITY_SERVICE_MAPPER_FILENAME);
if (inputStream == null) {
throw new RuntimeException("File not found: " + ENTITY_SERVICE_MAPPER_FILENAME);
}
//Parse xml into the Document
Document document = null;
try {
document = new SAXReader().read(inputStream);
} catch (DocumentException e) {
throw new RuntimeException("Unable to parse XML file: " + ENTITY_SERVICE_MAPPER_FILENAME, e);
}
//Traverse and fetch the data from the Document
Element entityServiceMapperElement = document.getRootElement();
if (entityServiceMapperElement != null) {
List<Element> serviceElementList = entityServiceMapperElement.elements(SERVICE);
if (serviceElementList == null || serviceElementList.isEmpty()) {
throw new RuntimeException("Invalid XML file: Service entries not found.");
}
registerServiceElements(serviceElementList);
List<Element> entityElementList = entityServiceMapperElement.elements(ENTITY);
if (entityElementList == null || entityElementList.isEmpty()) {
throw new RuntimeException("Invalid XML file: Entity entries not found.");
}
registerEntityElements(entityElementList);
} else {
throw new RuntimeException("Invalid XML file: Root element not found.");
}
}
/**
* This method stores the data of all the service tags into serviceMethodMap
* @param serviceElementList the root element of the XML document
*/
private void registerServiceElements(List<Element> serviceElementList) {
for (Element serviceElement : serviceElementList) {
List<String> serviceDetailClassList = new ArrayList<String>();
List<Element> methodElementList = serviceElement.elements(METHOD);
for (Element methodElement : methodElementList) {
String serviceDetailClassName = methodElement.attributeValue(ATTRIBUTE_SERVICE_DETAIL_CLASS);
String serviceInvokerClassName = methodElement.attributeValue(ATTRIBUTE_SERVICE_INVOKER_CLASS);
if (!serviceDetailClassList.contains(serviceDetailClassName)) {
serviceDetailClassList.add(serviceDetailClassName);
}
if (serviceDetailInvokerMap.get(serviceDetailClassName) == null) {
serviceDetailInvokerMap.put(serviceDetailClassName, serviceInvokerClassName);
}
}
String serviceName = serviceElement.attributeValue(ATTRIBUTE_NAME);
if (serviceNameDetailClassNameMap.get(serviceName) == null) {
serviceNameDetailClassNameMap.put(serviceName, serviceDetailClassList);
}
}
}
/**
* This method stores the data of all the entity tags into entityServiceMap
* @param entityElementList the root element of the XML document
*/
private void registerEntityElements(List<Element> entityElementList) {
for (Element entityElement : entityElementList) {
String entityName = entityElement.attributeValue(ATTRIBUTE_NAME);
String serviceName = entityElement.attributeValue(ATTRIBUTE_SERVICE_NAME);
List<String> serviceList = entityServiceNameMap.get(entityName);
if (serviceList == null) {
serviceList = new ArrayList<String>();
entityServiceNameMap.put(entityName, serviceList);
}
serviceList.add(serviceName);
}
}
/**
* This method returns the instance given the respective class name.
* @param className name of the class
* @return an instance of the given class name
*/
private <E> E getInstance(String className, Class<E> clazz) {
Object instance = null;
try {
Class classDefinition = Class.forName(className);
instance = classDefinition.newInstance();
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (ClassNotFoundException e) {
}
Class<?> instanceClass = instance.getClass();
if (!clazz.isAssignableFrom(instanceClass)) {
throw new RuntimeException(instanceClass.getName() + " does not implement the interface "
+ clazz.getName());
}
return (E) instance;
}
/**
* This method returns the List of the service names of the respective givne entity name.
* @param entityName the name of the entity
* @return the List of the service names
*/
private List<String> getServiceDetailClassNames(String entityName) {
List<String> serviceDetailClassList = new ArrayList<String>();
List<String> serviceNameList = entityServiceNameMap.get(entityName);
if (serviceNameList != null) {
for (String serviceName : serviceNameList) {
List<String> serviceDetailClassNameList = serviceNameDetailClassNameMap.get(serviceName);
if (serviceDetailClassNameList != null) {
serviceDetailClassList.addAll(serviceDetailClassNameList);
}
}
}
return serviceDetailClassList;
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
/**
* Clones this object
* @return Cloned object
* @throws CloneNotSupportedException
*/
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
/**
* This method returns the List of all the corresponding ServiceDetailsClass given the Entity.
* @param entity an instance of Entity
* @return List of all the ServiceDetailClass corresponding to the given Entity
*/
public List<ServiceDetailsInterface> getServices(EntityInterface entity) {
List<ServiceDetailsInterface> serviceDetailsInstanceList = new ArrayList<ServiceDetailsInterface>();
List<String> serviceDetailClassList = getServiceDetailClassNames(entity.getName());
//TODO This is a hack. To be deleted after testing.
//List<String> serviceDetailClassList = getServiceDetailClassNames("gov.nih.nci.mageom.domain.BioAssay.BioAssay");
for (String serviceDetailClassName : serviceDetailClassList) {
ServiceDetailsInterface serviceDetails = getInstance(serviceDetailClassName,
ServiceDetailsInterface.class);
serviceDetailsInstanceList.add(serviceDetails);
}
return serviceDetailsInstanceList;
}
/**
* This method returns an instance of the Service Invoker Class given the respective Service Details Class.
* @param serviceDetails the instance of the Service Details class
* @return an instance of the Service Invoker Class
*/
public ServiceInvokerInterface getServiceInvoker(ServiceDetailsInterface serviceDetails) {
String serviceDetailClassName = serviceDetails.getClass().getName();
String serviceInvokerClassName = serviceDetailInvokerMap.get(serviceDetailClassName);
ServiceInvokerInterface serviceInvoker = null;
if (serviceInvokerClassName != null) {
serviceInvoker = getInstance(serviceInvokerClassName, ServiceInvokerInterface.class);
}
return serviceInvoker;
}
// public static void main(String[] args) {
// EntityInterface entity = new Entity();
// entity.setName("Entity1");
//
// EntityToAnalyticalServiceMapper entityServiceMapper = EntityToAnalyticalServiceMapper.getInstance();
// List<ServiceDetailsInterface> serviceList = entityServiceMapper.getServices(entity);
// ServiceInvokerInterface serviceInvoker1 = entityServiceMapper.getServiceInvoker(serviceList.get(0));
// ServiceInvokerInterface serviceInvoker2 = entityServiceMapper.getServiceInvoker(serviceList.get(1));
// }
} | NCIP/cab2b | software/cab2b/src/java/server/edu/wustl/cab2b/server/analyticalservice/EntityToAnalyticalServiceMapper.java | Java | bsd-3-clause | 11,873 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.jtex.plot;
/**
*
* @author hios
*/
public interface ScatterCanvas {
public ScatterOptions getScatterOptions();
public void setScatterOptions(ScatterOptions options);
}
| luttero/Maud | src/com/jtex/plot/ScatterCanvas.java | Java | bsd-3-clause | 380 |
/**
* CArtAgO - DEIS, University of Bologna
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package cartago;
/**
* Unique identifier of an operation (instance)
* executed by an artifact
*
* @author aricci
*
*/
public class OpId implements java.io.Serializable {
private int id;
private ArtifactId aid;
private AgentId agentId;
private String opName;
OpId(ArtifactId aid, String opName, int id, AgentId ctxId){
this.id = id;
this.aid = aid;
this.agentId = ctxId;
this.opName = opName;
}
/**
* Get the numeric identifier of the operation id
*
* @return
*/
public int getId(){
return id;
}
/**
* Get the operation name.
*
* @return
*/
public String getOpName(){
return opName;
}
/**
* Get the id of the artifact where the operation has been executed
*
* @return
*/
public ArtifactId getArtifactId(){
return aid;
}
/**
* Get the identifier of the agent performer of the operation
*
* @return
*/
public AgentId getAgentBodyId(){
return agentId;
}
AgentId getContextId(){
return agentId;
}
public boolean equals(Object obj){
return aid.equals(((OpId)obj).aid) && ((OpId)obj).id==id;
}
public String toString(){
return "opId("+id+","+opName+","+aid+","+agentId+")";
}
}
| lsa-pucrs/jason-ros-releases | cartago-2.0.1/src/main/cartago/OpId.java | Java | bsd-3-clause | 2,026 |
package team.gif;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.DigitalIOButton;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import team.gif.commands.*;
public class OI {
public static final Joystick leftStick = new Joystick(1);
public static final rightStick = new Joystick(2);
public static final auxStick = new Joystick(3);
private final Button leftTrigger = new JoystickButton(leftStick, 1);
private final Button right2 = new JoystickButton(rightStick, 2);
private final Button right3 = new JoystickButton(rightStick, 3);
private final Button right6 = new JoystickButton(rightStick, 6);
private final Button right7 = new JoystickButton(rightStick, 7);
public static final Button auxTrigger = new JoystickButton(rightStick, 1);
public OI() {
leftTrigger.whileHeld(new ShifterHigh());
right2.whileHeld(new CollectorReceive());
right2.whenPressed(new EarsOpen());
right3.whileHeld(new CollectorPass());
right3.whenPressed(new EarsOpen());
right3.whenReleased(new CollectorStandby());
right3.whenReleased(new EarsClosed());
right6.whileHeld(new BumperUp());
right7.whileHeld(new CollectorRaise());
}
}
| Team2338/Fumper | src/team/gif/OI.java | Java | bsd-3-clause | 1,352 |
/*
* Copyright Ekagra and SemanticBits, LLC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/clinical-connector/LICENSE.txt for details.
*/
package gov.nih.nci.cdmsconnector.c3d.service.globus.resource;
import gov.nih.nci.cdmsconnector.c3d.common.C3DGridServiceConstants;
import gov.nih.nci.cdmsconnector.c3d.stubs.C3DGridServiceResourceProperties;
import org.apache.axis.components.uuid.UUIDGen;
import org.apache.axis.components.uuid.UUIDGenFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.wsrf.InvalidResourceKeyException;
import org.globus.wsrf.PersistenceCallback;
import org.globus.wsrf.Resource;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.ResourceKey;
import org.globus.wsrf.ResourceContext;
import gov.nih.nci.cagrid.introduce.servicetools.SingletonResourceHomeImpl;
import org.globus.wsrf.jndi.Initializable;
/**
* DO NOT EDIT: This class is autogenerated!
*
* This class implements the resource home for the resource type represented
* by this service.
*
* @created by Introduce Toolkit version 1.2
*
*/
public class C3DGridServiceResourceHome extends SingletonResourceHomeImpl implements Initializable {
static final Log logger = LogFactory.getLog(C3DGridServiceResourceHome.class);
private static final UUIDGen UUIDGEN = UUIDGenFactory.getUUIDGen();
public Resource createSingleton() {
logger.info("Creating a single resource.");
try {
C3DGridServiceResourceProperties props = new C3DGridServiceResourceProperties();
C3DGridServiceResource resource = new C3DGridServiceResource();
if (resource instanceof PersistenceCallback) {
//try to load the resource if it was persisted
try{
((PersistenceCallback) resource).load(null);
} catch (InvalidResourceKeyException ex){
//persisted singleton resource was not found so we will just create a new one
resource.initialize(props, C3DGridServiceConstants.RESOURCE_PROPERTY_SET, UUIDGEN.nextUUID());
}
} else {
resource.initialize(props, C3DGridServiceConstants.RESOURCE_PROPERTY_SET, UUIDGEN.nextUUID());
}
return resource;
} catch (Exception e) {
logger.error("Exception when creating the resource",e);
return null;
}
}
public Resource find(ResourceKey key) throws ResourceException {
C3DGridServiceResource resource = (C3DGridServiceResource) super.find(key);
return resource;
}
/**
* Initialze the singleton resource, when the home is initialized.
*/
public void initialize() throws Exception {
logger.info("Attempting to initialize resource.");
Resource resource = find(null);
if (resource == null) {
logger.error("Unable to initialize resource!");
} else {
logger.info("Successfully initialized resource.");
}
}
/**
* Get the resouce that is being addressed in this current context
*/
public C3DGridServiceResource getAddressedResource() throws Exception {
C3DGridServiceResource thisResource;
thisResource = (C3DGridServiceResource) ResourceContext.getResourceContext().getResource();
return thisResource;
}
}
| NCIP/clinical-connector | software/C3DGridService/src/gov/nih/nci/cdmsconnector/c3d/service/globus/resource/C3DGridServiceResourceHome.java | Java | bsd-3-clause | 3,275 |
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
*******************************************************************************/
package org.caleydo.view.relationshipexplorer.ui.collection;
import java.util.HashSet;
import java.util.Set;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.data.perspective.variable.Perspective;
import org.caleydo.core.data.virtualarray.VirtualArray;
import org.caleydo.core.id.IDCategory;
import org.caleydo.core.id.IDType;
import org.caleydo.view.relationshipexplorer.ui.ConTourElement;
import org.caleydo.view.relationshipexplorer.ui.collection.idprovider.IElementIDProvider;
import org.caleydo.view.relationshipexplorer.ui.column.factory.ColumnFactories;
import org.caleydo.view.relationshipexplorer.ui.column.factory.IColumnFactory;
import org.caleydo.view.relationshipexplorer.ui.detail.parcoords.ParallelCoordinatesDetailViewFactory;
import com.google.common.collect.Sets;
/**
* @author Christian
*
*/
public class TabularDataCollection extends AEntityCollection {
protected final ATableBasedDataDomain dataDomain;
protected final IDCategory itemIDCategory;
protected final TablePerspective tablePerspective;
protected final IDType itemIDType;
protected final VirtualArray va;
protected final Perspective dimensionPerspective;
protected final IDType mappingIDType;
public TabularDataCollection(TablePerspective tablePerspective, IDCategory itemIDCategory,
IElementIDProvider elementIDProvider, ConTourElement relationshipExplorer) {
super(relationshipExplorer);
dataDomain = tablePerspective.getDataDomain();
this.itemIDCategory = itemIDCategory;
this.tablePerspective = tablePerspective;
this.mappingIDType = dataDomain.getDatasetDescriptionIDType(itemIDCategory);
if (dataDomain.getDimensionIDCategory() == itemIDCategory) {
va = tablePerspective.getDimensionPerspective().getVirtualArray();
itemIDType = tablePerspective.getDimensionPerspective().getIdType();
dimensionPerspective = tablePerspective.getRecordPerspective();
} else {
va = tablePerspective.getRecordPerspective().getVirtualArray();
itemIDType = tablePerspective.getRecordPerspective().getIdType();
dimensionPerspective = tablePerspective.getDimensionPerspective();
}
if (elementIDProvider == null)
elementIDProvider = getDefaultElementIDProvider(va);
allElementIDs.addAll(elementIDProvider.getElementIDs());
filteredElementIDs.addAll(allElementIDs);
setLabel(dataDomain.getLabel());
detailViewFactory = new ParallelCoordinatesDetailViewFactory();
}
@Override
public IDType getBroadcastingIDType() {
return itemIDType;
}
@Override
protected Set<Object> getBroadcastIDsFromElementID(Object elementID) {
return Sets.newHashSet(elementID);
}
@Override
protected Set<Object> getElementIDsFromBroadcastID(Object broadcastingID) {
return Sets.newHashSet(broadcastingID);
}
@Override
protected IColumnFactory getDefaultColumnFactory() {
return ColumnFactories.createDefaultTabularDataColumnFactory();
}
/**
* @return the dataDomain, see {@link #dataDomain}
*/
public ATableBasedDataDomain getDataDomain() {
return dataDomain;
}
/**
* @return the perspective, see {@link #dimensionPerspective}
*/
public Perspective getDimensionPerspective() {
return dimensionPerspective;
}
/**
* @return the itemIDCategory, see {@link #itemIDCategory}
*/
public IDCategory getItemIDCategory() {
return itemIDCategory;
}
/**
* @return the itemIDType, see {@link #itemIDType}
*/
public IDType getItemIDType() {
return itemIDType;
}
@Override
public IDType getMappingIDType() {
return mappingIDType;
}
/**
* @return the tablePerspective, see {@link #tablePerspective}
*/
public TablePerspective getTablePerspective() {
return tablePerspective;
}
/**
* @return the va, see {@link #va}
*/
public VirtualArray getVa() {
return va;
}
public static IElementIDProvider getDefaultElementIDProvider(final VirtualArray va) {
return new IElementIDProvider() {
@Override
public Set<Object> getElementIDs() {
return new HashSet<Object>(va.getIDs());
}
};
}
@Override
public String getText(Object elementID) {
return elementID.toString();
}
}
| Caleydo/org.caleydo.view.contour | src/main/java/org/caleydo/view/relationshipexplorer/ui/collection/TabularDataCollection.java | Java | bsd-3-clause | 4,540 |
/*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
* Copyright (c) 2008, Nationwide Health Information Network (NHIN) Connect. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* - Neither the name of the NHIN Connect Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* END OF TERMS AND CONDITIONS
*/
package gov.hhs.fha.nhinc.common.dda;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for GetDetailDataForUserRequestType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="GetDetailDataForUserRequestType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="userId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="dataSource" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="itemId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GetDetailDataForUserRequestType", propOrder = {
"userId",
"dataSource",
"itemId"
})
public class GetDetailDataForUserRequestType {
@XmlElement(required = true)
protected String userId;
@XmlElement(required = true)
protected String dataSource;
@XmlElement(required = true)
protected String itemId;
/**
* Gets the value of the userId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUserId() {
return userId;
}
/**
* Sets the value of the userId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUserId(String value) {
this.userId = value;
}
/**
* Gets the value of the dataSource property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDataSource() {
return dataSource;
}
/**
* Sets the value of the dataSource property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDataSource(String value) {
this.dataSource = value;
}
/**
* Gets the value of the itemId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getItemId() {
return itemId;
}
/**
* Sets the value of the itemId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setItemId(String value) {
this.itemId = value;
}
}
| TATRC/KMR2 | Services/Common/XDSCommonLib/src/main/java/gov/hhs/fha/nhinc/common/dda/GetDetailDataForUserRequestType.java | Java | bsd-3-clause | 4,397 |
/**
* Copyright (c) 2015 See AUTHORS file
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mini2Dx.core.di.exception;
/**
* A base class for bean exceptions
*/
public class BeanException extends Exception {
private static final long serialVersionUID = 4487528732406582847L;
public BeanException(String message) {
super(message);
}
}
| hyperverse/mini2Dx | core/src/main/java/org/mini2Dx/core/di/exception/BeanException.java | Java | bsd-3-clause | 1,761 |
/* CoAP on Moterunner Demonstration
* Copyright (c) 2013-2014, SAP AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the SAP AG nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SAP 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.
*
* Contributors:
* Matthias Thoma
* Martin Zabel
* Theofilos Kakantousis
*
* The following things need to be added before any public release:
* 3. Consider to add TTL / Resend stuff (see hellosensor.java)
* 4. Have a look at rules for message id and consider to move it either here or to some generic class
*/
package com.sap.coap;
import com.ibm.saguaro.system.*;
import com.ibm.iris.*;
import com.ibm.saguaro.mrv6.*;
//##if LOGGING
import com.ibm.saguaro.logger.*;
//##endif
public class Message {
public byte[] header = new byte[4];
public byte[] token = null;
public byte[] payload = null;
public int payloadLength = 0;
public byte[] options;
public int optionArraySize = 0;
public int roundCounter = 0;
@Immutable public static final byte CON = 0x00;
@Immutable public static final byte NON = 0x01;
@Immutable public static final byte ACK = 0x02;
@Immutable public static final byte RST = 0x03;
@Immutable public static final byte EMPTY = 0x00;
@Immutable public static final byte GET = 0x01;
@Immutable public static final byte POST = 0x02;
@Immutable public static final byte PUT = 0x03;
@Immutable public static final byte DELETE = 0x04;
public final void setPayload(byte[] mypayload){
this.payload = mypayload;
this.payloadLength = mypayload.length;
}
public Message() {
header[0] = 0x40; // set the version number
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type"> something </param>
/// <param name="tokenLen"> token legnth </param>
/// <param name="code"> CoAP message code </param>
/// <param name="msgid"> CoAP message id </param>
public Message(byte type, byte tokenLen, byte code, int msgid) {
setMessageHeader(type, tokenLen, code, msgid);
}
public final void setMessageHeader(byte type, byte tokenLen, byte code, int msgid) {
header[0] = (byte) ((0x40 | (type << 4)) | tokenLen);
header[1] = code;
Util.set16be(header,2,msgid);
}
public static byte createResponseCode(final byte cl, final byte cc) {
return (byte) ((cl << 5) | cc);
}
public final byte getVersion() {
return (byte) ((header[0] >>> 6) & 0x03);
}
public final byte getType() {
return (byte) ((header[0] & 0x30) >> 4);
}
public final void setType(final byte type) {
byte tl = (byte) (header [0] & 0x0F);
header[0] = (byte) ((0x40 | (type << 4)) | tl); // set the version number
}
public final byte getTokenLength() {
return (byte) (header[0] & 0x0F);
}
public final byte getCode() {
return header[1];
}
public final int getMessageId() {
return Util.get16be(header,2);
}
public final void clearOptions() {
options=null;
optionArraySize=0;
}
public final void clearPayload() {
payloadLength = 0;
payload = null;
}
public final byte[] getPayload() {
return this.payload;
}
public final int getPayloadSize() {
return this.payloadLength;
}
public byte[] getURIfromOptionArray() {
int partNo = 0;
int bufferOffset = 0;
int offset = getOffsetOfOptionWithId(11, partNo);
if (offset<0)
return null;
int bufferSize = 0;
// Calculate buffer size
int firstOffset = offset;
while (offset>=0) {
if (partNo>0)
bufferSize++;
int valueSize = getValueSizeOfOptionWithOffset(offset);
bufferSize += valueSize;
partNo++;
offset = getOffsetOfOptionWithId(11, partNo);
}
byte[] buffer = new byte[bufferSize];
partNo=0;
offset = getOffsetOfOptionWithId(11, partNo);
int valueSize = getValueSizeOfOptionWithOffset(offset);
byte[] data = getValueOfOptionWithOffset(offset);
while (data != null) {
if (partNo>0) {
buffer[bufferOffset]='/';
bufferOffset++;
}
partNo++;
Util.copyData(data, 0, buffer, bufferOffset, valueSize);
bufferOffset += valueSize;
offset = getOffsetOfOptionWithId(11, partNo);
data = null;
if (offset>=0) {
valueSize = getValueSizeOfOptionWithOffset(offset);
data = getValueOfOptionWithOffset(offset);
}
}
return buffer;
}
public boolean hasOption(int id) {
return (getOffsetOfOptionWithId(id,0) != -1);
}
public void insertOption(int id, byte[] value, int valueSize) {
//1. find position
// an ascending order of the options has to be kept
// find start offsets of the 'enclosing' options left and right of the one to insert
// special case: inserting at the beginning: offsetRightOption = 0
// special case: inserting at the end: offsetRightOption = optionArraySize (i.e. points behind the array)
int offsetRightOption = 0;
int idRightOption = 0;
int idLeftOption = 0;
while(offsetRightOption < optionArraySize) { //if the loop is not left by a break, the option has to be inserted at the end
idRightOption = idOfOptionWithOffset(options, offsetRightOption, idRightOption);
if(idRightOption > id) { //insertion point found
break;
}
idLeftOption = idRightOption;
offsetRightOption = findOffsetOfNextOption(options, offsetRightOption);
}
//2. calculate value length field size for this option
int optionExtendedLengthFieldSize = getExtendedOptionFieldSizeFor(valueSize);
//3. calculate delta value for this option.
// depends on the previous id (being 0 when no previous option exists)
int delta = id - idLeftOption;
//4. calculate delta field size for this option
int optionExtendedDeltaFieldSize = getExtendedOptionFieldSizeFor(delta);
//5. recalculate the delta field size for the next option
// the delta value for the next option decreases due to the insertion
// this may result in less bytes being used for the size field
int deltaFieldSizeRightOption = 0;
int deltaFieldSizeRightOptionNew = 0;
int deltaRightOptionNew = 0;
int extendedDeltaFieldSizeDifferenceRightOption = 0;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//get the old field size for the next option
deltaFieldSizeRightOption = optionExtendedDeltaFieldSize(options, offsetRightOption);
//recalculate delta field size for next option
deltaRightOptionNew = idRightOption - id;
deltaFieldSizeRightOptionNew = getExtendedOptionFieldSizeFor(deltaRightOptionNew);
//determine the size difference between the new and the old field
extendedDeltaFieldSizeDifferenceRightOption = deltaFieldSizeRightOption - deltaFieldSizeRightOptionNew;
}
//7. calculate total size of new option array
int optionArraySizeNew = optionArraySize
+ 1
+ optionExtendedLengthFieldSize
+ optionExtendedDeltaFieldSize
+ valueSize
- extendedDeltaFieldSizeDifferenceRightOption;
//8. allocate mem for new option array
byte[] optionsNew = new byte[optionArraySizeNew];
//9. copy options until insertion point to new array
if(offsetRightOption>0) {
Util.copyData(options, 0, optionsNew, 0, offsetRightOption);
}
int currentOffset = offsetRightOption; //next position to read from the old options where no additional option is present. points now to the header byte of the next option
int offsetFirstByte = offsetRightOption; //points to the header byte of the option to insert
int currentOffsetNew = offsetFirstByte+1; //next position to write in the new array (after the header byte of the option to insert)
//10. write delta
if(optionExtendedDeltaFieldSize == 1) {
optionsNew[offsetFirstByte] += 13 << 4;
optionsNew[currentOffsetNew] = (byte)(delta-13);
}
else if(optionExtendedDeltaFieldSize == 2) {
optionsNew[offsetFirstByte] += 14 << 4;
Util.set16(optionsNew, currentOffsetNew, delta-269);
}
else { //optionExtendedDeltaFieldSize == 0
optionsNew[offsetFirstByte] += delta << 4;
}
currentOffsetNew += optionExtendedDeltaFieldSize;
//11. write value length
if(optionExtendedLengthFieldSize == 1) {
optionsNew[offsetFirstByte] += 13;
optionsNew[currentOffsetNew] = (byte)(valueSize-13);
}
else if(optionExtendedLengthFieldSize == 2) {
optionsNew[offsetFirstByte] += 14;
Util.set16(optionsNew, currentOffsetNew, valueSize-269);
}
else { //optionExtendedLengthFieldSize == 0
optionsNew[offsetFirstByte] += valueSize;
}
currentOffsetNew += optionExtendedLengthFieldSize;
//12. copy value
if(valueSize>0) {
Util.copyData(value, 0, optionsNew, currentOffsetNew, valueSize);
}
currentOffsetNew += valueSize;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//13. write header of next option with adjusted delta
//length stays constant, delta is erased
optionsNew[currentOffsetNew] = (byte) (options[currentOffset] & 0x0F);
//write recalculated delta to the next option
if(deltaFieldSizeRightOptionNew == 1) {
optionsNew[currentOffsetNew] += 13 << 4;
optionsNew[currentOffsetNew+1] = (byte) (deltaRightOptionNew-13);
}
else if(deltaFieldSizeRightOptionNew == 2){
optionsNew[currentOffsetNew] += 14 << 4;
Util.set16(optionsNew, currentOffsetNew+1, deltaRightOptionNew-269);
}
else { //deltaFieldSizeRightOptionNew == 0
optionsNew[currentOffsetNew] += deltaRightOptionNew << 4;
}
//jump behind the next option's extended delta field delta in the new array
currentOffsetNew += 1+deltaFieldSizeRightOptionNew;
//jump behind the next option's extended delta field in the old array
currentOffset += 1+deltaFieldSizeRightOption;
//14. copy rest of array (= next option's extended value length field, next option's value, all subsequent options)
int restLength = optionArraySize - currentOffset;
Util.copyData(options, currentOffset, optionsNew, currentOffsetNew, restLength);
}
//15. replace old options by new
options = optionsNew;
optionArraySize = optionArraySizeNew;
}
public int getOffsetOfOptionWithId(int wantedOptionId, int matchNumber) {
int currentOptionOffset = 0;
int currentDelta = 0;
while(currentOptionOffset < optionArraySize) {
int currentOptionId = idOfOptionWithOffset(options, currentOptionOffset, currentDelta);
if(currentOptionId == wantedOptionId) { //first of the options has been found. iterate them until the right match number is found
for(int i = 0; i<matchNumber; i++) {
currentOptionOffset = findOffsetOfNextOption(options, currentOptionOffset);
if(currentOptionOffset == optionArraySize || (options[currentOptionOffset] & 0xF0) != 0x00) {
return -1; //array length has been exceeded or the delta is not 0, i.e. an option with an higher id was found
}
}
return currentOptionOffset;
}
if(currentOptionId > wantedOptionId) {
return -1;
}
currentDelta = currentOptionId;
currentOptionOffset = findOffsetOfNextOption(options, currentOptionOffset);
}
return -1;
}
public byte[] getValueOfOptionWithOffset(int offset) {
int valueSize = getValueSizeOfOptionWithOffset(options, offset);
int headerSize = headerSizeOfOptionWithOffset(options, offset);
offset += headerSize;
byte[] value = new byte[valueSize];
if(valueSize>0) {
Util.copyData(options, offset, value, 0, valueSize);
}
return value;
}
public int getValueSizeOfOptionWithOffset(int offset) {
return getValueSizeOfOptionWithOffset(options, offset);
}
public void removeOptionWithOffset(int offset) {
//1. get delta of this option
int delta = idOfOptionWithOffset(options, offset, 0); //this method with 0 as previous delta gives just the delta of this option
//2. get length of the block to remove
int optionSize = headerSizeOfOptionWithOffset(options, offset)
+ getValueSizeOfOptionWithOffset(options, offset);
//3. recalculate next option's new delta value
int offsetRightOption = offset + optionSize; //same as findOffsetOfNextOption(options, offset);
int deltaRightOption;
int deltaFieldSizeRightOption = 0;
int deltaRightOptionNew = 0;
int deltaFieldSizeRightOptionNew = 0;
int deltaFieldSizeDifferenceRightOption = 0;
if(offsetRightOption != optionArraySize) {
//get the old field size for the next option
deltaRightOption = idOfOptionWithOffset(options, offsetRightOption, 0); //this method with 0 as previous delta gives just the delta of this option
deltaFieldSizeRightOption = optionExtendedDeltaFieldSize(options, offsetRightOption);
//recalculate delta field size for next option
deltaRightOptionNew = delta + deltaRightOption;
deltaFieldSizeRightOptionNew = getExtendedOptionFieldSizeFor(deltaRightOptionNew);
//determine the size difference between the new and the old field
deltaFieldSizeDifferenceRightOption = deltaFieldSizeRightOptionNew - deltaFieldSizeRightOption;
}
//6. calculate new array size
int optionArraySizeNew = optionArraySize
- optionSize
+ deltaFieldSizeDifferenceRightOption;
//7. allocate mem for new option array
byte[] optionsNew = new byte[optionArraySizeNew];
//8. copy old option array to the start of the option to remove
if (offset>0)
Util.copyData(options, 0, optionsNew, 0, offset);
int offsetNew = offset;
offset += optionSize;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//9. write new delta for next option
//length stays constant, delta is erased
optionsNew[offsetNew] = (byte) (options[offset] & 0x0F);
//write recalculated delta to the next option
if(deltaFieldSizeRightOptionNew == 1) {
optionsNew[offsetNew] += 13 << 4;
optionsNew[offsetNew+1] = (byte) (deltaRightOptionNew-13);
}
else if(deltaFieldSizeRightOptionNew == 2){
optionsNew[offsetNew] += 14 << 4;
Util.set16(optionsNew, offsetNew+1, deltaRightOptionNew-269);
}
else { //deltaFieldSizeRightOptionNew == 0
optionsNew[offsetNew] += deltaRightOptionNew << 4;
}
//jump behind the next option's extended delta field delta in the new array
offsetNew += 1+deltaFieldSizeRightOptionNew;
//jump behind the next option's extended delta field in the old array
offset += 1+deltaFieldSizeRightOption;
//10. copy rest of the array
int restLength = optionArraySizeNew - offsetNew;
Util.copyData(options, offset, optionsNew, offsetNew, restLength);
}
options = optionsNew;
optionArraySize = optionArraySizeNew;
}
public void removeOptionWithId(int id, int matchNumber) {
int offset = getOffsetOfOptionWithId(id, matchNumber);
removeOptionWithOffset(offset);
}
public byte[] valueOfOptionWithId(int id, int no) {
int partNo = 0;
int offset = getOffsetOfOptionWithId(id, no);
if (offset>=0) {
int valueSize = getValueSizeOfOptionWithOffset(offset);
byte[] data = getValueOfOptionWithOffset(offset);
return data;
}
return null;
}
public int findOffsetOfNextOption(int offset) {
return findOffsetOfNextOption(this.options, offset);
}
public int idOfOptionWithOffset(int offset, int currentDelta) {
return idOfOptionWithOffset(this.options, offset, currentDelta);
}
public void encodeTo(byte[] buffer, int offset) {
int iOffset = 0;
Util.copyData(header, 0, buffer, offset, 4);
iOffset+=4;
byte tokenLength = this.getTokenLength();
if (tokenLength > 0) {
Util.copyData(token,0, buffer, offset+iOffset, tokenLength);
iOffset += tokenLength;
}
if (optionArraySize>0) {
Util.copyData(options, 0, buffer, offset+iOffset, optionArraySize);
iOffset += optionArraySize;
}
if (this.payloadLength!=0) {
buffer[offset+iOffset] = (byte) 0xFF;
iOffset++;
Util.copyData(this.payload,0, buffer, offset+iOffset, this.payloadLength);
}
}
//
// Return:
// 0: OK
// -1: Protocol error
// -2: Currently unsupported feature
public byte decode(byte[] inBuffer, int offset, int len) {
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: ENTER DECODE"));
Logger.flush(Mote.INFO);
//##endif
int inOffset = offset;
int endLen = offset+len;
payloadLength = 0;
Util.copyData(inBuffer, offset, header, 0, 4);
inOffset += 4;
// Read token
byte tokenLength = getTokenLength();
if(tokenLength > 8) {
return -1;
}
if(inOffset == -1) {
return -1;
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: token len"));
Logger.appendInt(tokenLength);
Logger.flush(Mote.INFO);
//##endif
if (tokenLength>0) {
token = new byte[tokenLength];
Util.copyData(inBuffer, inOffset, token, 0, tokenLength);
}
inOffset += tokenLength;
// Check if end of Message
if (inOffset >= endLen) // Zero length Message, zero options
return 0;
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: start reading options "));
Logger.flush(Mote.INFO);
//##endif
// Check if payload marker or options
int optionOffset = inOffset;
inOffset = jumpOverOptions(inBuffer, inOffset, endLen);
if(inOffset == -1) {
return -1;
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: new offset"));
Logger.appendInt(inOffset);
Logger.appendString(csr.s2b("CoAPDecode :: endlen"));
Logger.appendInt(endLen);
Logger.flush(Mote.INFO);
//##endif
optionArraySize = inOffset - optionOffset; //may be 0 if no options are given
options = new byte[optionArraySize];
if(optionArraySize > 0) {
Util.copyData(inBuffer, optionOffset, options, 0, optionArraySize);
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: end reading options "));
Logger.flush(Mote.INFO);
//##endif
if (inOffset == endLen) { // Zero length Message
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: no payload "));
Logger.flush(Mote.INFO);
//##endif
return 0;
}
if (inBuffer[inOffset] == (byte) 0xFF) {
inOffset++;
if(inOffset == endLen) { //protocol error: there is no payload though the marker indicates
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: protocol error "));
Logger.flush(Mote.INFO);
//##endif
return -1;
}
// Payload
payloadLength = endLen-inOffset;
payload = new byte[payloadLength];
Util.copyData(inBuffer, inOffset, payload, 0, payloadLength);
}
else {
inOffset++;
if(inOffset < endLen) { //protocol error: there is payload though there is no marker
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: protocol error "));
Logger.flush(Mote.INFO);
//##endif
return -1;
}
}
return 0;
}
public final int getMessageLength() {
int len=4+getTokenLength();
if (this.payloadLength!=0)
len += 1+payloadLength;
len += optionArraySize;
return len;
}
public final Packet prepareResponseForSourcePacket(int inDstPort, byte[] inDstAddr, byte[] inSrcAddr, int srcPort) {
int dstport = inDstPort;
int lenp = getMessageLength();
Packet tempPacket = Mac.getPacket();
tempPacket.release();
Address.copyAddress(inDstAddr, 0, tempPacket.dstaddr, 0);
Address.copyAddress(inSrcAddr, 0, tempPacket.srcaddr, 0);
tempPacket.create(dstport, srcPort, lenp);
encodeTo(tempPacket.payloadBuf, tempPacket.payloadOff);
return tempPacket;
}
private static int jumpOverOptions(byte[] inBuffer, int offset, int len) {
int nextOptionOffset = offset;
while(nextOptionOffset < len && inBuffer[nextOptionOffset] != (byte) 0xFF) {
// checking for protocol violation -- one of the nibbles is F but it's not the payload marker
// check belongs only here since the first time parsing of a received message happens here
if( (inBuffer[offset] & 0x0F) == 0x0F || (inBuffer[offset] & 0xF0) == 0xF0 ) {
return -1;
}
nextOptionOffset = findOffsetOfNextOption(inBuffer, nextOptionOffset);
}
return nextOptionOffset;
}
private static int findOffsetOfNextOption(byte[] inBuffer, int offset) {
int headerSize = headerSizeOfOptionWithOffset(inBuffer, offset);
int valueSize = getValueSizeOfOptionWithOffset(inBuffer, offset);
int currentOptionSize = headerSize + valueSize;
return offset + currentOptionSize;
}
private static int headerSizeOfOptionWithOffset(byte[] inBuffer, int offset) {
int size = 1;
size += optionExtendedDeltaFieldSize(inBuffer, offset);
size += optionExtendedLengthFieldSize(inBuffer, offset);
return size;
}
private static int optionExtendedDeltaFieldSize(byte[] inBuffer, int offset) {
byte optionDelta = (byte) (((inBuffer[offset] & 0xF0) >> 4));
if(optionDelta < 13)
return 0;
if(optionDelta == 13)
return 1;
return 2; //optionDelta == 14
}
private static int optionExtendedLengthFieldSize(byte[] inBuffer, int offset) {
byte optionLength = (byte) (inBuffer[offset] & 0x0F);
if(optionLength < 13)
return 0;
if(optionLength == 13)
return 1;
return 2; //optionLength == 14
}
private static int getValueSizeOfOptionWithOffset(byte[] inBuffer, int offset) {
byte optionLength = (byte) (inBuffer[offset] & 0x0F);
if(optionLength < 13)
return optionLength;
else {
offset += 1 + optionExtendedDeltaFieldSize(inBuffer, offset);
if(optionLength == 13) {
return inBuffer[offset] + 13;
}
return Util.get16(inBuffer, offset) + 269; //optionLength == 14
}
}
private static int idOfOptionWithOffset(byte[] inBuffer, int offset, int currentDelta) {
byte optionDelta = (byte) (((inBuffer[offset] & 0xF0) >> 4));
if(optionDelta < 13)
return currentDelta + optionDelta;
else {
offset += 1;
if(optionDelta == 13) {
return currentDelta + inBuffer[offset] + 13;
}
return currentDelta + Util.get16(inBuffer, offset) + 269; //optionDelta == 14
}
}
private static int getExtendedOptionFieldSizeFor(int input) {
if(input<13)
return 0;
else if(input >= 13 && input < 269)
return 1;
return 2; //input >= 269
}
} | MR-CoAP/CoAP | src/com/sap/coap/Message.java | Java | bsd-3-clause | 26,430 |
/* Copyright (c) 2014 Andrea Zoli. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
package it.inaf.android;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class DateFormatter {
public static String formatType1(String date)
{
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
public static String formatType2(String date)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
public static String formatType3(String date)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
} | mediainaf/AppINAFAndroid | app/src/main/java/it/inaf/android/DateFormatter.java | Java | bsd-3-clause | 1,724 |
/*******************************************************************************
* Copyright (c) 2009-2012, University of Manchester
*
* Licensed under the New BSD License.
* Please see LICENSE file that is distributed with the source code
******************************************************************************/
package uk.ac.manchester.cs.owl.semspreadsheets.model;
/**
* Author: Matthew Horridge<br>
* The University of Manchester<br>
* Information Management Group<br>
* Date: 08-Nov-2009
*/
public interface NamedRange {
String getName();
Range getRange();
}
| Tokebluff/RightField | src/main/java/uk/ac/manchester/cs/owl/semspreadsheets/model/NamedRange.java | Java | bsd-3-clause | 595 |
/*L
* Copyright SAIC, SAIC-Frederick.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caadapter/LICENSE.txt for details.
*/
package gov.nih.nci.caadapter.sdtm.util;
/**
* This class represents a entity
*
* @author OWNER: Harsha Jayanna
* @author LAST UPDATE $Author: phadkes $
* @version Since caAdapter v4.0 revision
* $Revision: 1.4 $
* $Date: 2008-06-09 19:53:51 $
*/
public class Entity {
private String schema = null;
private String entityName = null;
/**
* Creates a new instance of Entity
*/
public Entity(String schema, String entityName) {
this.setSchema(schema);
this.setEntityName(entityName);
}
public String toString() {
return getEntityName();
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
}
/**
* Change History
* $Log: not supported by cvs2svn $
* Revision 1.3 2008/06/06 18:55:19 phadkes
* Changes for License Text
*
* Revision 1.2 2007/08/16 19:04:58 jayannah
* Reformatted and added the Comments and the log tags for all the files
*
*/
| NCIP/caadapter | software/caadapter/src/java/gov/nih/nci/caadapter/sdtm/util/Entity.java | Java | bsd-3-clause | 1,371 |
/**
* Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caintegrator/LICENSE.txt for details.
*/
package gov.nih.nci.caintegrator.web.action.study.management;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import gov.nih.nci.caintegrator.application.study.LogEntry;
import gov.nih.nci.caintegrator.application.study.StudyConfiguration;
import gov.nih.nci.caintegrator.application.study.StudyManagementServiceStub;
import gov.nih.nci.caintegrator.web.action.AbstractSessionBasedTest;
import gov.nih.nci.caintegrator.web.action.study.management.EditStudyLogAction;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import com.opensymphony.xwork2.Action;
/**
*
*/
public class EditStudyLogActionTest extends AbstractSessionBasedTest {
private EditStudyLogAction action = new EditStudyLogAction();
private StudyManagementServiceStub studyManagementService;
private LogEntry logEntry1;
private LogEntry logEntry2;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
action.setStudyConfiguration(new StudyConfiguration());
action = new EditStudyLogAction();
studyManagementService = new StudyManagementServiceStub();
action.setStudyManagementService(studyManagementService);
action.setWorkspaceService(workspaceService);
logEntry1 = new LogEntry();
logEntry1.setTrimSystemLogMessage("message");
logEntry1.setLogDate(new Date());
logEntry1.setTrimDescription("desc");
try {
Thread.sleep(20l);
} catch (InterruptedException e) {
}
logEntry2 = new LogEntry();
logEntry2.setSystemLogMessage("message2");
logEntry2.setLogDate(new Date());
logEntry2.setDescription("desc");
action.getStudyConfiguration().getLogEntries().add(logEntry1);
action.getStudyConfiguration().getLogEntries().add(logEntry2);
}
@Test
public void testPrepare() throws InterruptedException {
action.prepare();
// Verify the most recent ones are sorted first.
assertEquals(logEntry2, action.getDisplayableLogEntries().get(0).getLogEntry());
assertEquals(logEntry1, action.getDisplayableLogEntries().get(1).getLogEntry());
assertTrue(studyManagementService.getRefreshedStudyEntityCalled);
}
@Test
public void testSave() {
action.prepare();
// logEntry2 is first
action.getDisplayableLogEntries().get(0).setDescription("new");
action.getDisplayableLogEntries().get(0).setUpdateDescription(true);
// logEntry1 will have a new description, but the checkbox will be false.
action.getDisplayableLogEntries().get(1).setDescription("new");
action.getDisplayableLogEntries().get(1).setUpdateDescription(false);
assertEquals(Action.SUCCESS, action.save());
assertEquals("new", logEntry2.getDescription());
assertEquals("desc", logEntry1.getDescription());
assertTrue(studyManagementService.saveCalled);
}
@Test
public void testAcceptableParameterName() {
assertTrue(action.acceptableParameterName(null));
assertTrue(action.acceptableParameterName("ABC"));
assertFalse(action.acceptableParameterName("123"));
assertFalse(action.acceptableParameterName("d-123-e"));
}
}
| NCIP/caintegrator | caintegrator-war/test/src/gov/nih/nci/caintegrator/web/action/study/management/EditStudyLogActionTest.java | Java | bsd-3-clause | 3,632 |
/*
* Copyright (c) 2008, Keith Woodward
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Keith Woodward nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package straightedge.geom.vision;
import straightedge.geom.*;
public class CollinearOverlap{
public KPolygon polygon;
public int pointIndex;
public int nextPointIndex;
public KPolygon polygon2;
public int point2Index;
public CollinearOverlap(KPolygon polygon, int pointIndex, int nextPointIndex, KPolygon polygon2, int point2Index){
this.polygon = polygon;
this.pointIndex = pointIndex;
this.nextPointIndex = nextPointIndex;
this.polygon2 = polygon2;
this.point2Index = point2Index;
}
public KPolygon getPolygon() {
return polygon;
}
public int getPointIndex() {
return pointIndex;
}
public int getNextPointIndex() {
return nextPointIndex;
}
public KPolygon getPolygon2() {
return polygon2;
}
public int getPoint2Index() {
return point2Index;
}
} | rpax/straightedge | src/main/java/straightedge/geom/vision/CollinearOverlap.java | Java | bsd-3-clause | 2,372 |
package edu.ucdenver.ccp.datasource.fileparsers.snomed;
import edu.ucdenver.ccp.datasource.fileparsers.SingleLineFileRecord;
/*
* #%L
* Colorado Computational Pharmacology's common module
* %%
* Copyright (C) 2012 - 2015 Regents of the University of Colorado
* %%
* 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. Neither the name of the Regents of the University of Colorado nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import lombok.Getter;
/**
* @author Center for Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu
*
*/
@Getter
public class SnomedRf2DescriptionFileRecord extends SingleLineFileRecord {
public enum DescriptionType {
FULLY_SPECIFIED_NAME("900000000000003001"),
SYNONYM("900000000000013009");
private final String typeId;
private DescriptionType(String typeId) {
this.typeId = typeId;
}
public String typeId() {
return typeId;
}
public static DescriptionType getType(String typeId) {
for (DescriptionType type : values()) {
if (type.typeId().equals(typeId)) {
return type;
}
}
throw new IllegalArgumentException("Invalid SnoMed description type id: " + typeId);
}
}
/*
* id effectiveTime active moduleId conceptId languageCode typeId term caseSignificanceId
*/
private final String descriptionId;
private final String effectiveTime;
private final boolean active;
private final String moduleId;
private final String conceptId;
private final String languageCode;
private final DescriptionType type;
private final String term;
private final String caseSignificanceId;
/**
* @param byteOffset
* @param lineNumber
* @param definitionId
* @param effectiveTime
* @param active
* @param moduleId
* @param conceptId
* @param languageCode
* @param typeId
* @param term
* @param caseSignificanceId
*/
public SnomedRf2DescriptionFileRecord(String descriptionId, String effectiveTime, boolean active, String moduleId,
String conceptId, String languageCode, DescriptionType type, String term, String caseSignificanceId,
long byteOffset, long lineNumber) {
super(byteOffset, lineNumber);
this.descriptionId = descriptionId;
this.effectiveTime = effectiveTime;
this.active = active;
this.moduleId = moduleId;
this.conceptId = conceptId;
this.languageCode = languageCode;
this.type = type;
this.term = term;
this.caseSignificanceId = caseSignificanceId;
}
}
| UCDenver-ccp/datasource | datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/fileparsers/snomed/SnomedRf2DescriptionFileRecord.java | Java | bsd-3-clause | 3,805 |
package com.mattunderscore.trees.base;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import com.mattunderscore.iterators.SingletonIterator;
import com.mattunderscore.trees.mutable.MutableNode;
import com.mattunderscore.trees.tree.Node;
/**
* Unit tests for {@link MutableChildIterator}.
*
* @author Matt Champion on 29/08/2015
*/
public final class MutableChildIteratorTest {
@Mock
private MutableNode<String> parent;
@Mock
private MutableNode<String> child;
private Iterator<? extends MutableNode<String>> iterator;
@Before
public void setUp() {
initMocks(this);
iterator = new SingletonIterator<>(child);
}
@Test
public void hasNext() {
final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
assertTrue(mutableIterator.hasNext());
mutableIterator.next();
assertFalse(mutableIterator.hasNext());
}
@Test(expected = NoSuchElementException.class)
public void next() {
final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
final MutableNode<String> node = mutableIterator.next();
assertSame(child, node);
mutableIterator.next();
}
@Test
public void remove() {
final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
mutableIterator.next();
mutableIterator.remove();
verify(parent).removeChild(child);
}
}
| mattunderscorechampion/tree-root | trees-basic-nodes/src/test/java/com/mattunderscore/trees/base/MutableChildIteratorTest.java | Java | bsd-3-clause | 1,823 |
package com.spm.store;
import java.io.Serializable;
import java.util.List;
import android.content.Context;
/**
*
* @author Agustin Sgarlata
* @param <T>
*/
public class DbProvider<T extends Serializable> extends Db4oHelper {
public Class<T> persistentClass;
public DbProvider(Class<T> persistentClass, Context ctx) {
super(ctx);
this.persistentClass = persistentClass;
}
public void store(T obj) {
db().store(obj);
db().commit();
}
public void delete(T obj) {
db().delete(obj);
db().commit();
}
public List<T> findAll() {
return db().query(persistentClass);
}
public List<T> get(T obj) {
return db().queryByExample(obj);
}
} | mural/spm | SPM/src/main/java/com/spm/store/DbProvider.java | Java | bsd-3-clause | 670 |
/**
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2008-2011, Sebastian Staudt
*/
package com.github.koraktor.steamcondenser.steam.community;
import static com.github.koraktor.steamcondenser.steam.community.XMLUtil.loadXml;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.github.koraktor.steamcondenser.steam.community.portal2.Portal2Stats;
/**
* @author Guto Maia
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ DocumentBuilderFactory.class, DocumentBuilder.class })
public class Portal2StatsTest extends StatsTestCase<Portal2Stats>{
public Portal2StatsTest() {
super("gutomaia", "portal2");
}
@Test
public void getPortal2Stats() throws Exception {
assertEquals("Portal 2", stats.getGameName());
assertEquals("Portal2", stats.getGameFriendlyName());
assertEquals(620, stats.getAppId());
assertEquals("0", stats.getHoursPlayed());
assertEquals(76561197985077150l, stats.getSteamId64());
}
@Test
public void achievements() throws Exception {
assertEquals(17, stats.getAchievementsDone());
}
} | gutomaia/steam-condenser-java | src/test/java/com/github/koraktor/steamcondenser/steam/community/Portal2StatsTest.java | Java | bsd-3-clause | 1,630 |
package com.atlassian.pageobjects.components.aui;
import com.atlassian.pageobjects.PageBinder;
import com.atlassian.pageobjects.binder.Init;
import com.atlassian.pageobjects.binder.InvalidPageStateException;
import com.atlassian.pageobjects.components.TabbedComponent;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.PageElementFinder;
import com.atlassian.pageobjects.elements.query.Poller;
import org.openqa.selenium.By;
import javax.inject.Inject;
import java.util.List;
/**
* Represents a tabbed content area created via AUI.
*
* This is an example of a reusable components.
*/
public class AuiTabs implements TabbedComponent
{
@Inject
protected PageBinder pageBinder;
@Inject
protected PageElementFinder elementFinder;
private final By rootLocator;
private PageElement rootElement;
public AuiTabs(By locator)
{
this.rootLocator = locator;
}
@Init
public void initialize()
{
this.rootElement = elementFinder.find(rootLocator);
}
public PageElement selectedTab()
{
List<PageElement> items = rootElement.find(By.className("tabs-menu")).findAll(By.tagName("li"));
for(int i = 0; i < items.size(); i++)
{
PageElement tab = items.get(i);
if(tab.hasClass("active-tab"))
{
return tab;
}
}
throw new InvalidPageStateException("A tab must be active.", this);
}
public PageElement selectedView()
{
List<PageElement> panes = rootElement.findAll(By.className("tabs-pane"));
for(int i = 0; i < panes.size(); i++)
{
PageElement pane = panes.get(i);
if(pane.hasClass("active-pane"))
{
return pane;
}
}
throw new InvalidPageStateException("A pane must be active", this);
}
public List<PageElement> tabs()
{
return rootElement.find(By.className("tabs-menu")).findAll(By.tagName("li"));
}
public PageElement openTab(String tabText)
{
List<PageElement> tabs = rootElement.find(By.className("tabs-menu")).findAll(By.tagName("a"));
for(int i = 0; i < tabs.size(); i++)
{
if(tabs.get(i).getText().equals(tabText))
{
PageElement listItem = tabs.get(i);
listItem.click();
// find the pane and wait until it has class "active-pane"
String tabViewHref = listItem.getAttribute("href");
String tabViewClassName = tabViewHref.substring(tabViewHref.indexOf('#') + 1);
PageElement pane = rootElement.find(By.id(tabViewClassName));
Poller.waitUntilTrue(pane.timed().hasClass("active-pane"));
return pane;
}
}
throw new InvalidPageStateException("Tab not found", this);
}
public PageElement openTab(PageElement tab)
{
String tabIdentifier = tab.getText();
return openTab(tabIdentifier);
}
}
| adini121/atlassian | atlassian-pageobjects-elements/src/main/java/com/atlassian/pageobjects/components/aui/AuiTabs.java | Java | bsd-3-clause | 3,108 |
package com.xoba.smr;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.util.Collection;
import java.util.Formatter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.codec.binary.Base64;
import com.amazonaws.Request;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.handlers.AbstractRequestHandler;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.LaunchSpecification;
import com.amazonaws.services.ec2.model.RequestSpotInstancesRequest;
import com.amazonaws.services.ec2.model.RequestSpotInstancesResult;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.xoba.util.ILogger;
import com.xoba.util.LogFactory;
import com.xoba.util.MraUtils;
public class SimpleMapReduce {
private static final ILogger logger = LogFactory.getDefault().create();
public static void launch(Properties config, Collection<String> inputSplitPrefixes, AmazonInstance ai,
int machineCount) throws Exception {
launch(config, inputSplitPrefixes, ai, machineCount, true);
}
public static void launch(Properties config, Collection<String> inputSplitPrefixes, AmazonInstance ai,
int machineCount, boolean spotInstances) throws Exception {
if (!config.containsKey(ConfigKey.JOB_ID.toString())) {
config.put(ConfigKey.JOB_ID.toString(), MraUtils.md5Hash(new TreeMap<Object, Object>(config).toString())
.substring(0, 8));
}
String id = config.getProperty(ConfigKey.JOB_ID.toString());
AWSCredentials aws = create(config);
AmazonSimpleDB db = new AmazonSimpleDBClient(aws);
AmazonSQS sqs = new AmazonSQSClient(aws);
AmazonS3 s3 = new AmazonS3Client(aws);
final String mapQueue = config.getProperty(ConfigKey.MAP_QUEUE.toString());
final String reduceQueue = config.getProperty(ConfigKey.REDUCE_QUEUE.toString());
final String dom = config.getProperty(ConfigKey.SIMPLEDB_DOM.toString());
final String mapInputBucket = config.getProperty(ConfigKey.MAP_INPUTS_BUCKET.toString());
final String shuffleBucket = config.getProperty(ConfigKey.SHUFFLE_BUCKET.toString());
final String reduceOutputBucket = config.getProperty(ConfigKey.REDUCE_OUTPUTS_BUCKET.toString());
final int hashCard = new Integer(config.getProperty(ConfigKey.HASH_CARDINALITY.toString()));
s3.createBucket(reduceOutputBucket);
final long inputSplitCount = inputSplitPrefixes.size();
for (String key : inputSplitPrefixes) {
Properties p = new Properties();
p.setProperty("input", "s3://" + mapInputBucket + "/" + key);
sqs.sendMessage(new SendMessageRequest(mapQueue, serialize(p)));
}
SimpleDbCommitter.commitNewAttribute(db, dom, "parameters", "splits", "" + inputSplitCount);
SimpleDbCommitter.commitNewAttribute(db, dom, "parameters", "hashes", "" + hashCard);
SimpleDbCommitter.commitNewAttribute(db, dom, "parameters", "done", "1");
for (String hash : getAllHashes(hashCard)) {
Properties p = new Properties();
p.setProperty("input", "s3://" + shuffleBucket + "/" + hash);
sqs.sendMessage(new SendMessageRequest(reduceQueue, serialize(p)));
}
if (machineCount == 1) {
// run locally
SMRDriver.main(new String[] { MraUtils.convertToHex(serialize(config).getBytes()) });
} else if (machineCount > 1) {
// run in the cloud
String userData = produceUserData(ai, config,
new URI(config.getProperty(ConfigKey.RUNNABLE_JARFILE_URI.toString())));
logger.debugf("launching job with id %s:", id);
System.out.println(userData);
AmazonEC2 ec2 = new AmazonEC2Client(aws);
if (spotInstances) {
RequestSpotInstancesRequest sir = new RequestSpotInstancesRequest();
sir.setSpotPrice(new Double(ai.getPrice()).toString());
sir.setInstanceCount(machineCount);
sir.setType("one-time");
LaunchSpecification spec = new LaunchSpecification();
spec.setImageId(ai.getDefaultAMI());
spec.setUserData(new String(new Base64().encode(userData.getBytes("US-ASCII"))));
spec.setInstanceType(ai.getApiName());
sir.setLaunchSpecification(spec);
RequestSpotInstancesResult result = ec2.requestSpotInstances(sir);
logger.debugf("spot instance request result: %s", result);
} else {
RunInstancesRequest req = new RunInstancesRequest(ai.getDefaultAMI(), machineCount, machineCount);
req.setClientToken(id);
req.setInstanceType(ai.getApiName());
req.setInstanceInitiatedShutdownBehavior("terminate");
req.setUserData(new String(new Base64().encode(userData.getBytes("US-ASCII"))));
RunInstancesResult resp = ec2.runInstances(req);
logger.debugf("on demand reservation id: %s", resp.getReservation().getReservationId());
labelEc2Instance(ec2, resp, "smr-" + id);
}
}
}
public static void labelEc2Instance(AmazonEC2 ec2, RunInstancesResult resp, String title) throws Exception {
int tries = 0;
boolean done = false;
while (tries++ < 3 && !done) {
try {
List<String> resources = new LinkedList<String>();
for (Instance i : resp.getReservation().getInstances()) {
resources.add(i.getInstanceId());
}
List<Tag> tags = new LinkedList<Tag>();
tags.add(new Tag("Name", title));
CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
ec2.createTags(ctr);
done = true;
logger.debugf("set tag(s)");
} catch (Exception e) {
logger.warnf("exception setting tags: %s", e);
Thread.sleep(3000);
}
}
}
public static String produceUserData(AmazonInstance ai, Properties c, URI jarFileURI) throws Exception {
StringWriter sw = new StringWriter();
LinuxLineConventionPrintWriter pw = new LinuxLineConventionPrintWriter(new PrintWriter(sw));
pw.println("#!/bin/sh");
pw.println("cd /root");
pw.println("chmod 777 /mnt");
pw.println("aptitude update");
Set<String> set = new TreeSet<String>();
set.add("openjdk-6-jdk");
set.add("wget");
if (set.size() > 0) {
pw.print("aptitude install -y ");
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String x = it.next();
pw.print(x);
if (it.hasNext()) {
pw.print(" ");
}
}
pw.println();
}
pw.printf("wget %s", jarFileURI);
pw.println();
String[] parts = jarFileURI.getPath().split("/");
String jar = parts[parts.length - 1];
pw.printf("java -Xmx%.0fm -cp %s %s %s", 1000 * 0.8 * ai.getMemoryGB(), jar, SMRDriver.class.getName(),
MraUtils.convertToHex(serialize(c).getBytes()));
pw.println();
pw.println("poweroff");
pw.close();
return sw.toString();
}
public static AmazonS3 getS3(AWSCredentials aws) {
AmazonS3Client s3 = new AmazonS3Client(aws);
s3.addRequestHandler(new AbstractRequestHandler() {
@Override
public void beforeRequest(Request<?> request) {
request.addHeader("x-amz-request-payer", "requester");
}
});
return s3;
}
public static String prefixedName(String p, String n) {
return p + "-" + n;
}
public static AWSCredentials create(final Properties p) {
return new AWSCredentials() {
@Override
public String getAWSSecretKey() {
return p.getProperty(ConfigKey.AWS_SECRETKEY.toString());
}
@Override
public String getAWSAccessKeyId() {
return p.getProperty(ConfigKey.AWS_KEYID.toString());
}
};
}
public static SortedSet<String> getAllHashes(long mod) {
SortedSet<String> out = new TreeSet<String>();
for (long i = 0; i < mod; i++) {
out.add(fmt(i, mod));
}
return out;
}
public static String hash(byte[] key, long mod) {
byte[] buf = MraUtils.md5HashBytesToBytes(key);
long x = Math.abs(MraUtils.extractLongValue(buf));
return fmt(x % mod, mod);
}
private static String fmt(long x, long mod) {
long places = Math.round(Math.ceil(Math.log10(mod)));
if (places == 0) {
places = 1;
}
return new Formatter().format("%0" + places + "d", x).toString();
}
public static String serialize(Properties p) throws Exception {
StringWriter sw = new StringWriter();
try {
p.store(sw, "n/a");
} finally {
sw.close();
}
return sw.toString();
}
public static Properties marshall(String s) throws Exception {
Properties p = new Properties();
StringReader sr = new StringReader(s);
try {
p.load(sr);
} finally {
sr.close();
}
return p;
}
}
| mrallc/smr | code/src/com/xoba/smr/SimpleMapReduce.java | Java | bsd-3-clause | 9,071 |
package org.broadinstitute.hellbender.engine;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.hellbender.cmdline.TestProgramGroup;
/**
* A Dummy / Placeholder class that can be used where a {@link GATKTool} is required.
* DO NOT USE THIS FOR ANYTHING OTHER THAN TESTING.
* THIS MUST BE IN THE ENGINE PACKAGE DUE TO SCOPE ON `features`!
* Created by jonn on 9/19/18.
*/
@CommandLineProgramProperties(
summary = "A dummy GATKTool to help test Funcotator.",
oneLineSummary = "Dummy dumb dumb tool for testing.",
programGroup = TestProgramGroup.class
)
public final class DummyPlaceholderGatkTool extends GATKTool {
public DummyPlaceholderGatkTool() {
parseArgs(new String[]{});
onStartup();
}
@Override
public void traverse() {
}
@Override
void initializeFeatures(){
features = new FeatureManager(this, FeatureDataSource.DEFAULT_QUERY_LOOKAHEAD_BASES, cloudPrefetchBuffer, cloudIndexPrefetchBuffer,
referenceArguments.getReferencePath());
}
}
| magicDGS/gatk | src/test/java/org/broadinstitute/hellbender/engine/DummyPlaceholderGatkTool.java | Java | bsd-3-clause | 1,099 |
/*
* Created on 02/04/2005
*
* JRandTest package
*
* Copyright (c) 2005, Zur Aougav, aougav@hotmail.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of the JRandTest nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.fasteasytrade.jrandtest.algo;
import java.math.BigInteger;
import java.util.Random;
/**
* QuadraidResidue1 Prng algorithm from NIST test package
* <p>
* Fix random p, prime, length 512 bits.
* <p>
* Fix random g, prime, length 512 bits. g < p.
* <p>
* Each prng iteration calculate g = g**2 mod p.<br>
* The lowest 64 bits of g are the prng result.
*
* @author Zur Aougav
*/
public class QuadraticResidue1Prng extends Cipher {
/**
* n's length/num of bits
*/
public final int bit_length = 512;
/**
* prime (with probability < 2 ** -100).
* <p>
* Length of p is bit_length = 512 bits = 64 bytes.
*/
BigInteger p;
/**
* Initial g is a random prime (with probability < 2 ** -100)
* <p>
* Length of g is bit_length = 512 bits = 64 bytes.
* <p>
* g is the "state" of the prng.
* <p>
* g = take 64 lowr bits of ( g**2 mod n ).
*/
BigInteger g;
/**
* g0 is the "initial state" of the prng.
* <p>
* reset method set g to g0.
*/
BigInteger g0;
QuadraticResidue1Prng() {
setup(bit_length);
}
QuadraticResidue1Prng(int x) {
if (x < bit_length) {
setup(bit_length);
} else {
setup(x);
}
}
QuadraticResidue1Prng(BigInteger p, BigInteger g) {
this.p = p;
this.g = g;
g0 = g;
}
QuadraticResidue1Prng(BigInteger p, BigInteger g, BigInteger g0) {
this.p = p;
this.g = g;
this.g0 = g0;
}
/**
* Generate the key and seed for Quadratic Residue Prng.
* <p>
* Select random primes - p, g. g < p.
*
* @param len
* length of p and g, num of bits.
*/
void setup(int len) {
Random rand = new Random();
p = BigInteger.probablePrime(len, rand);
g = BigInteger.probablePrime(len, rand);
/**
* if g >= p swap(g, p).
*/
if (g.compareTo(p) > -1) {
BigInteger temp = g;
g = p;
p = temp;
}
/**
* here for sure g < p
*/
g0 = g;
}
/**
* calculate g**2 mod p and returns lowest 64 bits, long.
*
*/
public long nextLong() {
g = g.multiply(g).mod(p);
/**
* set g to 2 if g <= 1.
*/
if (g.compareTo(BigInteger.ONE) < 1) {
g = BigInteger.valueOf(2);
}
return g.longValue();
}
/**
* Public key.
*
* @return p prime (with probability < 2 ** -100)
*/
public BigInteger getP() {
return p;
}
/**
* Secret key
*
* @return g prime (with probability < 2 ** -100)
*/
public BigInteger getG() {
return g;
}
/**
* Reset "state" of prng by setting g to g0 (initial g).
*
*/
public void reset() {
g = g0;
}
} | cryptopony/jrandtest | src/com/fasteasytrade/jrandtest/algo/QuadraticResidue1Prng.java | Java | bsd-3-clause | 4,818 |
package de.uni.freiburg.iig.telematik.wolfgang.properties.check;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import de.invation.code.toval.graphic.component.DisplayFrame;
import de.invation.code.toval.graphic.util.SpringUtilities;
import de.uni.freiburg.iig.telematik.sepia.petrinet.cpn.properties.cwn.CWNProperties;
import de.uni.freiburg.iig.telematik.sepia.petrinet.properties.PropertyCheckingResult;
import javax.swing.SpringLayout;
public class CWNPropertyCheckView extends AbstractPropertyCheckView<CWNProperties> {
private static final long serialVersionUID = -950169446391727139L;
private PropertyCheckResultLabel lblStructure;
private PropertyCheckResultLabel lblInOutPlaces;
private PropertyCheckResultLabel lblConnectedness;
private PropertyCheckResultLabel lblValidMarking;
private PropertyCheckResultLabel lblCFDependency;
private PropertyCheckResultLabel lblNoDeadTransitions;
private PropertyCheckResultLabel lblCompletion;
private PropertyCheckResultLabel lblOptionComplete;
private PropertyCheckResultLabel lblBounded;
@Override
protected String getHeadline() {
return "Colored WF Net Check";
}
@Override
protected void addSpecificFields(JPanel pnl) {
lblStructure = new PropertyCheckResultLabel("\u2022 CWN Structure", PropertyCheckingResult.UNKNOWN);
pnl.add(lblStructure);
JPanel pnlStructureSub = new JPanel(new SpringLayout());
pnl.add(pnlStructureSub);
lblInOutPlaces = new PropertyCheckResultLabel("\u2022 Valid InOut Places", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblInOutPlaces);
lblConnectedness = new PropertyCheckResultLabel("\u2022 Strong Connectedness", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblConnectedness);
lblValidMarking = new PropertyCheckResultLabel("\u2022 Valid Initial Marking", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblValidMarking);
lblCFDependency = new PropertyCheckResultLabel("\u2022 Control Flow Dependency", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblCFDependency);
SpringUtilities.makeCompactGrid(pnlStructureSub, pnlStructureSub.getComponentCount(), 1, 15, 0, 0, 0);
pnl.add(new JPopupMenu.Separator());
lblBounded = new PropertyCheckResultLabel("\u2022 Is Bounded", PropertyCheckingResult.UNKNOWN);
pnl.add(lblBounded);
pnl.add(new JPopupMenu.Separator());
lblOptionComplete = new PropertyCheckResultLabel("\u2022 Option To Complete", PropertyCheckingResult.UNKNOWN);
pnl.add(lblOptionComplete);
pnl.add(new JPopupMenu.Separator());
lblCompletion = new PropertyCheckResultLabel("\u2022 Proper Completion", PropertyCheckingResult.UNKNOWN);
pnl.add(lblCompletion);
pnl.add(new JPopupMenu.Separator());
lblNoDeadTransitions = new PropertyCheckResultLabel("\u2022 No Dead Transitions", PropertyCheckingResult.UNKNOWN);
pnl.add(lblNoDeadTransitions);
}
@Override
public void resetFieldContent() {
super.updateFieldContent(null, null);
lblStructure.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblInOutPlaces.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblConnectedness.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblValidMarking.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblCFDependency.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblBounded.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblOptionComplete.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblCompletion.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblNoDeadTransitions.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
}
@Override
public void updateFieldContent(CWNProperties checkResult, Exception exception) {
super.updateFieldContent(checkResult, exception);
lblStructure.updatePropertyCheckingResult(checkResult.hasCWNStructure);
lblInOutPlaces.updatePropertyCheckingResult(checkResult.validInOutPlaces);
lblConnectedness.updatePropertyCheckingResult(checkResult.strongConnectedness);
lblValidMarking.updatePropertyCheckingResult(checkResult.validInitialMarking);
lblCFDependency.updatePropertyCheckingResult(checkResult.controlFlowDependency);
lblBounded.updatePropertyCheckingResult(checkResult.isBounded);
lblOptionComplete.updatePropertyCheckingResult(checkResult.optionToCompleteAndProperCompletion);
lblCompletion.updatePropertyCheckingResult(checkResult.optionToCompleteAndProperCompletion);
lblNoDeadTransitions.updatePropertyCheckingResult(checkResult.noDeadTransitions);
}
public static void main(String[] args) {
CWNPropertyCheckView view = new CWNPropertyCheckView();
view.setUpGui();
view.updateFieldContent(new CWNProperties(), null);
new DisplayFrame(view, true);
}
}
| iig-uni-freiburg/WOLFGANG | src/de/uni/freiburg/iig/telematik/wolfgang/properties/check/CWNPropertyCheckView.java | Java | bsd-3-clause | 5,138 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.