answer
stringlengths
17
10.2M
package org.realityforge.jeo.geolatte.jpa.eclipselink; import java.lang.reflect.Field; import java.sql.SQLException; import org.eclipse.persistence.internal.helper.DatabaseField; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.mappings.DirectCollectionMapping; import org.eclipse.persistence.mappings.converters.Converter; import org.eclipse.persistence.sessions.Session; import org.geolatte.geom.ByteBuffer; import org.geolatte.geom.Geometry; import org.geolatte.geom.LineString; import org.geolatte.geom.LinearRing; import org.geolatte.geom.MultiLineString; import org.geolatte.geom.MultiPoint; import org.geolatte.geom.MultiPolygon; import org.geolatte.geom.Point; import org.geolatte.geom.Polygon; import org.geolatte.geom.codec.Wkb; import org.geolatte.geom.codec.Wkt; import org.geolatte.geom.codec.Wkt.Dialect; import org.postgis.PGgeometry; public class PostgisConverter implements Converter { @Override public Object convertObjectValueToDataValue( final Object objectValue, final Session session ) { if( null == objectValue ) { return null; } final Geometry geometry = (Geometry) objectValue; final String wkt = Wkt.newEncoder( Dialect.POSTGIS_EWKT_1 ).encode( geometry ); try { return new PGgeometry( wkt ); } catch ( final SQLException se ) { throw new IllegalStateException( "Failed converting geometry", se ); } } @Override public Geometry convertDataValueToObjectValue( final Object dataValue, final Session session ) { if( null == dataValue ) { return null; } final String wkt; if ( dataValue instanceof PGgeometry ) { final org.postgis.Geometry geometry = ( (PGgeometry) dataValue ).getGeometry(); wkt = geometry.toString(); } else { wkt = (String) dataValue; } //Stored as WKB ??? return Wkb.newDecoder( Wkb.Dialect.POSTGIS_EWKB_1 ).decode( ByteBuffer.from( wkt ) ); //return Wkt.newDecoder( Wkt.Dialect.POSTGIS_EWKT_1 ).decode( wkt ); } @Override public boolean isMutable() { return false; } @Override public void initialize( final DatabaseMapping mapping, final Session session ) { final DatabaseField field; if ( mapping instanceof DirectCollectionMapping ) { field = ( (DirectCollectionMapping) mapping ).getDirectField(); } else { field = mapping.getField(); } field.setSqlType( java.sql.Types.OTHER ); if ( null == field.getTypeName() ) { field.setTypeName( "geometry" ); } if ( null == field.getColumnDefinition() ) { final Field javaField = getJavaField( mapping, field ); final Class<?> javaFieldType = javaField.getType(); //TODO: Dervive the SRS from an annotation //TODO: Dervive the M from an annotation if ( Point.class == javaFieldType ) { field.setColumnDefinition( "geometry(POINT,-1)" ); } else if ( Polygon.class == javaFieldType ) { field.setColumnDefinition( "geometry(POLYGON,-1)" ); } else if ( LineString.class == javaFieldType ) { field.setColumnDefinition( "geometry(LINESTRING,-1)" ); } else if ( MultiPoint.class == javaFieldType ) { field.setColumnDefinition( "geometry(MULTIPOINT,-1)" ); } else if ( MultiPolygon.class == javaFieldType ) { field.setColumnDefinition( "geometry(MULTIPOLYGON,-1)" ); } else if ( MultiLineString.class == javaFieldType ) { field.setColumnDefinition( "geometry(MULTILINESTRING,-1)" ); } else if ( LinearRing.class == javaFieldType ) { field.setColumnDefinition( "geometry(LINEARRING,-1)" ); } else { field.setColumnDefinition( "geometry" ); } } } private Field getJavaField( final DatabaseMapping mapping, final DatabaseField field ) { try { final String fieldName = field.getName(); final Class type = mapping.getDescriptor().getJavaClass(); return type.getField( fieldName ); } catch ( final NoSuchFieldException nsfe ) { throw new IllegalStateException( "Unable to locate expected field", nsfe ); } } }
package org.sagebionetworks.web.client.widget.entity.download; import java.util.List; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.attachment.UploadResult; import org.sagebionetworks.repo.model.attachment.UploadStatus; import org.sagebionetworks.repo.model.file.ExternalUploadDestination; import org.sagebionetworks.repo.model.file.S3UploadDestination; import org.sagebionetworks.repo.model.file.UploadDestination; import org.sagebionetworks.repo.model.file.UploadType; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.web.client.ClientProperties; import org.sagebionetworks.web.client.DisplayConstants; import org.sagebionetworks.web.client.GWTWrapper; import org.sagebionetworks.web.client.GlobalApplicationState; import org.sagebionetworks.web.client.SynapseClientAsync; import org.sagebionetworks.web.client.SynapseJSNIUtils; import org.sagebionetworks.web.client.events.CancelEvent; import org.sagebionetworks.web.client.events.CancelHandler; import org.sagebionetworks.web.client.events.EntityUpdatedEvent; import org.sagebionetworks.web.client.events.EntityUpdatedHandler; import org.sagebionetworks.web.client.security.AuthenticationController; import org.sagebionetworks.web.client.transform.NodeModelCreator; import org.sagebionetworks.web.client.utils.Callback; import org.sagebionetworks.web.client.utils.CallbackP; import org.sagebionetworks.web.client.widget.SynapsePersistable; import org.sagebionetworks.web.client.widget.SynapseWidgetPresenter; import org.sagebionetworks.web.client.widget.entity.dialog.AddAttachmentDialog; import org.sagebionetworks.web.client.widget.upload.ProgressingFileUploadHandler; import org.sagebionetworks.web.client.widget.upload.MultipartUploader; import org.sagebionetworks.web.shared.EntityWrapper; import org.sagebionetworks.web.shared.WebConstants; import org.sagebionetworks.web.shared.exceptions.ConflictException; import org.sagebionetworks.web.shared.exceptions.NotFoundException; import org.sagebionetworks.web.shared.exceptions.RestServiceException; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; /** * This Uploader class supports 3 use cases: * A. Legacy data types (like the Data Entity): Uploads to the FileUpload servlet, using the Form submit (POST). @see org.sagebionetworks.web.server.servlet.FileUpload * B. File Entity, newer client browser: Direct multipart upload to S3, using a PUT to presigned URLs. * * Case B will be the most common case. */ public class Uploader implements UploaderView.Presenter, SynapseWidgetPresenter, SynapsePersistable, ProgressingFileUploadHandler { public static final long OLD_BROWSER_MAX_SIZE = (long)ClientProperties.MB * 5; //5MB private UploaderView view; private NodeModelCreator nodeModelCreator; private HandlerManager handlerManager; private Entity entity; private String parentEntityId; //set if we are uploading to an existing file entity private String entityId; private CallbackP<String> fileHandleIdCallback; private SynapseClientAsync synapseClient; private SynapseJSNIUtils synapseJsniUtils; private GlobalApplicationState globalAppState; private GWTWrapper gwt; MultipartUploader multiPartUploader; AuthenticationController authenticationController; private String[] fileNames; private int currIndex; private NumberFormat percentFormat; private boolean fileHasBeenUploaded = false; private UploadType currentUploadType; @Inject public Uploader( UploaderView view, NodeModelCreator nodeModelCreator, SynapseClientAsync synapseClient, SynapseJSNIUtils synapseJsniUtils, GWTWrapper gwt, AuthenticationController authenticationController, MultipartUploader multiPartUploader, GlobalApplicationState globalAppState ) { this.view = view; this.nodeModelCreator = nodeModelCreator; this.synapseClient = synapseClient; this.synapseJsniUtils = synapseJsniUtils; this.gwt = gwt; this.percentFormat = gwt.getNumberFormat(" this.authenticationController = authenticationController; this.globalAppState = globalAppState; this.multiPartUploader = multiPartUploader; view.setPresenter(this); clearHandlers(); } public Widget asWidget(Entity entity) { return asWidget(entity, null, null, true); } public Widget asWidget(String parentEntityId) { return asWidget((Entity)null, parentEntityId, null, true); } public Widget asWidget(Entity entity, String parentEntityId, CallbackP<String> fileHandleIdCallback, boolean isEntity) { this.view.setPresenter(this); this.entity = entity; this.parentEntityId = parentEntityId; this.fileHandleIdCallback = fileHandleIdCallback; this.view.createUploadForm(isEntity, parentEntityId); view.resetToInitialState(); resetUploadProgress(); view.showUploaderUI(); return this.view.asWidget(); } public void clearState() { view.clear(); // remove handlers handlerManager = new HandlerManager(this); this.entity = null; this.parentEntityId = null; this.currentUploadType = null; resetUploadProgress(); } @Override public Widget asWidget() { return null; } public void uploadFiles() { view.triggerUpload(); } @Override public void handleUploads() { currentUploadType = null; if (fileNames == null) { //setup upload process. fileHasBeenUploaded = false; currIndex = 0; if ((fileNames = synapseJsniUtils.getMultipleUploadFileNames(UploaderViewImpl.FILE_FIELD_ID)) == null) { //no files selected. view.showNoFilesSelectedForUpload(); return; } } entityId = null; if (entity != null) { entityId = entity.getId(); } uploadBasedOnConfiguration(); } /** * Get the upload destination (based on the project settings), and continue the upload. */ public void uploadBasedOnConfiguration() { if (parentEntityId == null) { uploadToS3(); } else { //we have a parent entity, check to see where we are suppose to upload the file(s) synapseClient.getUploadDestinations(parentEntityId, new AsyncCallback<List<UploadDestination>>() { public void onSuccess(List<UploadDestination> uploadDestinations) { if (uploadDestinations == null || uploadDestinations.isEmpty() || uploadDestinations.get(0) instanceof S3UploadDestination) { uploadToS3(); } else if (uploadDestinations.get(0) instanceof ExternalUploadDestination){ ExternalUploadDestination d = (ExternalUploadDestination) uploadDestinations.get(0); uploadToExternal(d); } else { //unsupported upload destination type onFailure(new org.sagebionetworks.web.client.exceptions.IllegalArgumentException("Unsupported upload destination: " + uploadDestinations.get(0).getClass().getName())); } }; @Override public void onFailure(Throwable caught) { uploadError(caught.getMessage()); } }); } } public void uploadToExternal(ExternalUploadDestination d) { if (UploadType.SFTP.equals(d.getUploadType())){ //upload to the sftp proxy! uploadToSftpProxy(d.getUrl()); } else { //not yet supported uploadError("External upload destination type not yet handled: " + d.getUploadType().name()); } } /** * Given a sftp link, return a link that goes through the sftp proxy to do the action (GET file or POST upload form) * @param realSftpUrl * @param globalAppState * @return */ public static String getSftpProxyLink(String realSftpUrl, GlobalApplicationState globalAppState) { String sftpProxy = globalAppState.getSynapseProperty(WebConstants.SFTP_PROXY_ENDPOINT); if (sftpProxy != null) { String delimiter = sftpProxy.contains("?") ? "&" : "?"; return sftpProxy + delimiter + "url="+realSftpUrl; } else { //unlikely state throw new IllegalArgumentException("Unable to determine SFTP endpoint"); } } public void uploadToSftpProxy(final String url) { currentUploadType = UploadType.SFTP; try { String destinationUrl = url; if (!destinationUrl.endsWith("/")) destinationUrl += "/"; view.submitForm(getSftpProxyLink(destinationUrl, globalAppState)); } catch (Exception e) { uploadError(e.getMessage()); } } public void uploadToS3() { currentUploadType = UploadType.S3; boolean isFileEntity = entity == null || entity instanceof FileEntity; if (isFileEntity) { //use case B from above directUploadStep1(fileNames[currIndex]); } else { //use case A from above //uses the default action url //if using this method, block if file size is > MAX_SIZE try { checkFileSize(); } catch (Exception e) { view.showErrorMessage(e.getMessage()); fireCancelEvent(); return; } view.submitForm(getOldUploadUrl()); } } public void checkFileSize() throws IllegalArgumentException{ long fileSize = (long)synapseJsniUtils.getFileSize(UploaderViewImpl.FILE_FIELD_ID, currIndex); //check if (fileSize > OLD_BROWSER_MAX_SIZE) { throw new IllegalArgumentException(DisplayConstants.LARGE_FILE_ON_UNSUPPORTED_BROWSER); } } /** * Look for a file with the same name (if we aren't uploading to an existing File already). * @param fileName */ public void directUploadStep1(final String fileName) { if (entity != null || parentEntityId == null) { directUploadStep2(fileName); } else { synapseClient.getFileEntityIdWithSameName(fileName, parentEntityId, new AsyncCallback<String>() { @Override public void onSuccess(final String result) { //there was already a file with this name in the directory. //confirm we can overwrite view.showConfirmDialog("A file named \""+fileName+"\" ("+result+") already exists in this location. Do you want to replace it with the one you're uploading?", new Callback() { @Override public void invoke() { //yes, override entityId = result; directUploadStep2(fileName); } }, new Callback() { @Override public void invoke() { handleCancelledFileUpload(); } }); } @Override public void onFailure(Throwable caught) { if (caught instanceof NotFoundException) { //there was not already a file with this name in this directory. directUploadStep2(fileName); } else if (caught instanceof ConflictException) { //there was an entity found with same parent ID and name, but //it was not a File Entity. view.showErrorMessage("An item named \""+fileName+"\" already exists in this location. File could not be uploaded."); handleCancelledFileUpload(); } else { uploadError(caught.getMessage()); } } }); } } private void directUploadStep2(String fileName) { this.multiPartUploader.uploadFile(fileName, UploaderViewImpl.FILE_FIELD_ID, this.currIndex, this); } private void handleCancelledFileUpload() { if (currIndex + 1 == fileNames.length) { //uploading the last file if (!fileHasBeenUploaded) { //cancel the upload fireCancelEvent(); clearState(); } else { //finish upload view.updateProgress(.99d, "99%"); uploadSuccess(); } } else { //more files to upload currIndex++; handleUploads(); } } public void setFileEntityFileHandle(String fileHandleId) { if (entityId != null || parentEntityId != null) { try { synapseClient.setFileEntityFileHandle(fileHandleId, entityId, parentEntityId, new AsyncCallback<String>() { @Override public void onSuccess(String entityId) { fileHasBeenUploaded = true; if (currIndex + 1 == fileNames.length) { //to new file handle id, or create new file entity with this file handle id view.hideLoading(); refreshAfterSuccessfulUpload(entityId); } else { //more files to upload currIndex++; handleUploads(); } } @Override public void onFailure(Throwable t) { uploadError(t.getMessage()); } }); } catch (RestServiceException e) { uploadError(e.getMessage()); } } if (fileHandleIdCallback != null) { fileHandleIdCallback.invoke(fileHandleId); uploadSuccess(); } } @Override public void setExternalFilePath(String path, String name) { if (entity==null || entity instanceof FileEntity) { //new data, use the appropriate synapse call //if we haven't created the entity yet, do that first if (entity == null) { createNewExternalFileEntity(path, name); } else { updateExternalFileEntity(entity.getId(), path, name); } } else { //old data String entityId = entity.getId(); synapseClient.updateExternalLocationable(entityId, path, name, new AsyncCallback<EntityWrapper>() { public void onSuccess(EntityWrapper result) { externalLinkUpdated(result, entity.getClass()); }; @Override public void onFailure(Throwable caught) { view.showErrorMessage(DisplayConstants.TEXT_LINK_FAILED); } } ); } } public void externalLinkUpdated(EntityWrapper result, Class<? extends Entity> entityClass) { try { entity = nodeModelCreator.createJSONEntity(result.getEntityJson(), entityClass); view.showInfo(DisplayConstants.TEXT_LINK_FILE, DisplayConstants.TEXT_LINK_SUCCESS); entityUpdated(); } catch (JSONObjectAdapterException e) { view.showErrorMessage(DisplayConstants.TEXT_LINK_FAILED); } } public void updateExternalFileEntity(String entityId, String path, String name) { try { synapseClient.updateExternalFile(entityId, path, name, new AsyncCallback<EntityWrapper>() { @Override public void onSuccess(EntityWrapper result) { externalLinkUpdated(result, FileEntity.class); } @Override public void onFailure(Throwable caught) { view.showErrorMessage(DisplayConstants.TEXT_LINK_FAILED); } }); } catch (Throwable t) { view.showErrorMessage(DisplayConstants.TEXT_LINK_FAILED); } } public void createNewExternalFileEntity(final String path, final String name) { try { synapseClient.createExternalFile(parentEntityId, path, name, new AsyncCallback<EntityWrapper>() { @Override public void onSuccess(EntityWrapper result) { externalLinkUpdated(result, FileEntity.class); } @Override public void onFailure(Throwable caught) { view.showErrorMessage(DisplayConstants.TEXT_LINK_FAILED); } }); } catch (RestServiceException e) { view.showErrorMessage(DisplayConstants.TEXT_LINK_FAILED); } } @Override public void disableMultipleFileUploads() { view.disableMultipleFileUploads(); } @Override @SuppressWarnings("unchecked") public void addCancelHandler(CancelHandler handler) { handlerManager.addHandler(CancelEvent.getType(), handler); } @Override public void clearHandlers() { handlerManager = new HandlerManager(this); } @Override public void addPersistSuccessHandler(EntityUpdatedHandler handler) { handlerManager.addHandler(EntityUpdatedEvent.getType(), handler); } public void entityUpdated() { handlerManager.fireEvent(new EntityUpdatedEvent()); } /** * This method is called after the form submit is complete. Note that this is used for use case A and B (see above). */ @Override public void handleSubmitResult(String resultHtml) { if(resultHtml == null) resultHtml = ""; // response from server //try to parse UploadResult uploadResult = null; String detailedErrorMessage = null; try{ uploadResult = AddAttachmentDialog.getUploadResult(resultHtml); if (uploadResult.getUploadStatus() == UploadStatus.SUCCESS) { if (currentUploadType == null || currentUploadType.equals(UploadType.S3)) { //upload result has file handle id if successful String fileHandleId = uploadResult.getMessage(); setFileEntityFileHandle(fileHandleId); } else if (UploadType.SFTP.equals(currentUploadType)) { //should respond with the new path String path = uploadResult.getMessage(); String fileName = fileNames[currIndex]; setExternalFilePath(path, fileName); } }else { uploadError("Upload result status indicated upload was unsuccessful."); } } catch (Throwable th) {detailedErrorMessage = th.getMessage();};//wasn't an UplaodResult if (uploadResult == null) { if(!resultHtml.contains(DisplayConstants.UPLOAD_SUCCESS)) { uploadError(detailedErrorMessage); } else { uploadSuccess(); } } } public void showCancelButton(boolean showCancel) { view.setShowCancelButton(showCancel); } @Override public void cancelClicked() { fireCancelEvent(); } /* * Private Methods */ private void refreshAfterSuccessfulUpload(String entityId) { synapseClient.getEntity(entityId, new AsyncCallback<EntityWrapper>() { @Override public void onSuccess(EntityWrapper result) { try { entity = nodeModelCreator.createEntity(result); uploadSuccess(); } catch (JSONObjectAdapterException e) { view.showErrorMessage(DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION); } } @Override public void onFailure(Throwable caught) { view.showErrorMessage(caught.getMessage()); } }); } private void uploadError(String message) { String details = ""; if (message != null && message.length() > 0) details = " \n" + message; view.showErrorMessage(DisplayConstants.ERROR_UPLOAD + details); fireCancelEvent(); } private void fireCancelEvent(){ //Verified that when this method is called, the input field used for direct upload is no longer available, //so that this effectively cancels chunked upload too (after the current chunk upload completes) view.hideLoading(); view.clear(); handlerManager.fireEvent(new CancelEvent()); view.resetToInitialState(); } private void uploadSuccess() { view.showInfo(DisplayConstants.TEXT_UPLOAD_FILE_OR_LINK, DisplayConstants.TEXT_UPLOAD_SUCCESS); view.clear(); view.resetToInitialState(); resetUploadProgress(); handlerManager.fireEvent(new EntityUpdatedEvent()); } private String getOldUploadUrl() { String entityIdString = entity != null ? WebConstants.ENTITY_PARAM_KEY + "=" + entity.getId() : ""; return gwt.getModuleBaseURL() + WebConstants.LEGACY_DATA_UPLOAD_SERVLET + "?" + entityIdString; } private void resetUploadProgress() { fileNames = null; fileHasBeenUploaded = false; currIndex = 0; } /** * For testing purposes * @return */ public String getDirectUploadFileEntityId() { return entityId; } /** * For testing purposes * @return */ public void setFileNames(String[] fileNames) { this.fileNames = fileNames; } @Override public void updateProgress(double currentProgress, String progressText) { view.showProgressBar(); double percentOfAllFiles = calculatePercentOverAllFiles(this.fileNames.length, this.currIndex, currentProgress); String textOfAllFiles = percentFormat.format(percentOfAllFiles*100.0) + "%"; view.updateProgress(percentOfAllFiles, textOfAllFiles); } @Override public void uploadSuccess(String fileHandleId) { this.setFileEntityFileHandle(fileHandleId); } @Override public void uploadFailed(String string) { this.uploadError(string); } /** * Calculate the upload progress over all file upload given the progress of the current file. * This method assumes each file contributes equally to the total upload times. * @param numberFiles Number of files to upload. * @param currentFileIndex Index of the current file with zero being the first file. * @param percentOfCurrentFile The percent complete for the current file. This number should be between 0.0 and 1.0 (%/100). * @return */ public static double calculatePercentOverAllFiles(int numberFiles, int currentFileIndex, double percentOfCurrentFile){ double percentPerFile = 1.0/(double)numberFiles; double percentOfAllFiles = percentPerFile*percentOfCurrentFile + (percentPerFile*currentFileIndex); return percentOfAllFiles; } }
package com.vaadin.terminal.gwt.client.ui; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.FormElement; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.Hidden; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.SimplePanel; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.Paintable; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.VConsole; /** * * Note, we are not using GWT FormPanel as we want to listen submitcomplete * events even though the upload component is already detached. * */ public class VUpload extends SimplePanel implements Paintable { private final class MyFileUpload extends FileUpload { @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); if (event.getTypeInt() == Event.ONCHANGE) { if (immediate && fu.getFilename() != null && !"".equals(fu.getFilename())) { submit(); } } else if (event.getTypeInt() == Event.ONFOCUS) { // IE and user has clicked on hidden textarea part of upload // field. Manually open file selector, other browsers do it by // default. fireNativeClick(fu.getElement()); // also remove focus to enable hack if user presses cancel // button fireNativeBlur(fu.getElement()); } } } public static final String CLASSNAME = "v-upload"; /** * FileUpload component that opens native OS dialog to select file. */ FileUpload fu = new MyFileUpload(); Panel panel = new FlowPanel(); UploadIFrameOnloadStrategy onloadstrategy = GWT .create(UploadIFrameOnloadStrategy.class); ApplicationConnection client; private String paintableId; /** * Button that initiates uploading */ private final VButton submitButton; /** * When expecting big files, programmer may initiate some UI changes when * uploading the file starts. Bit after submitting file we'll visit the * server to check possible changes. */ private Timer t; /** * some browsers tries to send form twice if submit is called in button * click handler, some don't submit at all without it, so we need to track * if form is already being submitted */ private boolean submitted = false; private boolean enabled = true; private boolean immediate; private Hidden maxfilesize = new Hidden(); private FormElement element; private com.google.gwt.dom.client.Element synthesizedFrame; private int nextUploadId; public VUpload() { super(com.google.gwt.dom.client.Document.get().createFormElement()); element = getElement().cast(); setEncoding(getElement(), FormPanel.ENCODING_MULTIPART); element.setMethod(FormPanel.METHOD_POST); setWidget(panel); panel.add(maxfilesize); panel.add(fu); submitButton = new VButton(); submitButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { if (immediate) { // fire click on upload (eg. focused button and hit space) fireNativeClick(fu.getElement()); } else { submit(); } } }); panel.add(submitButton); setStyleName(CLASSNAME); } private static native void setEncoding(Element form, String encoding) /*-{ form.enctype = encoding; // For IE6 form.encoding = encoding; }-*/; public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { if (client.updateComponent(this, uidl, true)) { return; } if (uidl.hasAttribute("notStarted")) { t.schedule(400); return; } setImmediate(uidl.getBooleanAttribute("immediate")); this.client = client; paintableId = uidl.getId(); nextUploadId = uidl.getIntAttribute("nextid"); final String action = client.translateVaadinUri(uidl .getStringVariable("action")); element.setAction(action); submitButton.setText(uidl.getStringAttribute("buttoncaption")); fu.setName(paintableId + "_file"); if (uidl.hasAttribute("disabled") || uidl.hasAttribute("readonly")) { disableUpload(); } else if (!uidl.getBooleanAttribute("state")) { // Enable the button only if an upload is not in progress enableUpload(); ensureTargetFrame(); } } private void setImmediate(boolean booleanAttribute) { if (immediate != booleanAttribute) { immediate = booleanAttribute; if (immediate) { fu.sinkEvents(Event.ONCHANGE); fu.sinkEvents(Event.ONFOCUS); } } setStyleName(getElement(), CLASSNAME + "-immediate", immediate); } private static native void fireNativeClick(Element element) /*-{ element.click(); }-*/; private static native void fireNativeBlur(Element element) /*-{ element.blur(); }-*/; protected void disableUpload() { submitButton.setEnabled(false); if (!submitted) { // Cannot disable the fileupload while submitting or the file won't // be submitted at all fu.getElement().setPropertyBoolean("disabled", true); } enabled = false; } protected void enableUpload() { submitButton.setEnabled(true); fu.getElement().setPropertyBoolean("disabled", false); enabled = true; } /** * Re-creates file input field and populates panel. This is needed as we * want to clear existing values from our current file input field. */ private void rebuildPanel() { panel.remove(submitButton); panel.remove(fu); fu = new MyFileUpload(); fu.setName(paintableId + "_file"); fu.getElement().setPropertyBoolean("disabled", !enabled); panel.add(fu); panel.add(submitButton); if (immediate) { fu.sinkEvents(Event.ONCHANGE); } } /** * Called by JSNI (hooked via {@link #onloadstrategy}) */ private void onSubmitComplete() { /* Needs to be run dereferred to avoid various browser issues. */ Scheduler.get().scheduleDeferred(new Command() { public void execute() { if (submitted) { if (client != null) { if (t != null) { t.cancel(); } VConsole.log("VUpload:Submit complete"); client.sendPendingVariableChanges(); } rebuildPanel(); submitted = false; enableUpload(); if (!isAttached()) { /* * Upload is complete when upload is already abandoned. */ cleanTargetFrame(); } } } }); } private void submit() { if (fu.getFilename().length() == 0 || submitted || !enabled) { VConsole.log("Submit cancelled (disabled, no file or already submitted)"); return; } // flush possibly pending variable changes, so they will be handled // before upload client.sendPendingVariableChanges(); element.submit(); submitted = true; VConsole.log("Submitted form"); disableUpload(); /* * Visit server a moment after upload has started to see possible * changes from UploadStarted event. Will be cleared on complete. */ t = new Timer() { @Override public void run() { VConsole.log("Visiting server to see if upload started event changed UI."); client.updateVariable(paintableId, "pollForStart", nextUploadId, true); } }; t.schedule(800); } @Override protected void onAttach() { super.onAttach(); if (client != null) { ensureTargetFrame(); } } private void ensureTargetFrame() { if (synthesizedFrame == null) { // Attach a hidden IFrame to the form. This is the target iframe to // which // the form will be submitted. We have to create the iframe using // innerHTML, // because setting an iframe's 'name' property dynamically doesn't // work on // most browsers. DivElement dummy = Document.get().createDivElement(); dummy.setInnerHTML("<iframe src=\"javascript:''\" name='" + getFrameName() + "' style='position:absolute;width:0;height:0;border:0'>"); synthesizedFrame = dummy.getFirstChildElement(); Document.get().getBody().appendChild(synthesizedFrame); element.setTarget(getFrameName()); onloadstrategy.hookEvents(synthesizedFrame, this); } } private String getFrameName() { return paintableId + "_TGT_FRAME"; } @Override protected void onDetach() { super.onDetach(); if (!submitted) { cleanTargetFrame(); } } private void cleanTargetFrame() { if (synthesizedFrame != null) { Document.get().getBody().removeChild(synthesizedFrame); onloadstrategy.unHookEvents(synthesizedFrame); synthesizedFrame = null; } } }
package org.spongepowered.api.util.command.dispatcher; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import org.spongepowered.api.util.command.CommandCallable; import org.spongepowered.api.util.command.CommandException; import org.spongepowered.api.util.command.CommandMapping; import org.spongepowered.api.util.command.CommandSource; import org.spongepowered.api.util.command.ImmutableCommandMapping; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; /** * A simple implementation of a {@link Dispatcher}. */ public class SimpleDispatcher implements Dispatcher { private final Map<String, CommandMapping> commands = Maps.newHashMap(); /** * Register a given command using the given list of aliases. * * <p>If there is a conflict with one of the aliases (i.e. that alias * is already assigned to another command), then the alias will be skipped. * It is possible for there to be no alias to be available out of * the provided list of aliases, which would mean that the command would not * be assigned to any aliases.</p> * * <p>The first non-conflicted alias becomes the "primary alias."</p> * * @param callable The command * @param alias An array of aliases * @return The registered command mapping, unless no aliases could be registered */ public Optional<CommandMapping> register(CommandCallable callable, String... alias) { checkNotNull(alias); return register(callable, Arrays.asList(alias)); } /** * Register a given command using the given list of aliases. * * <p>If there is a conflict with one of the aliases (i.e. that alias * is already assigned to another command), then the alias will be skipped. * It is possible for there to be no alias to be available out of * the provided list of aliases, which would mean that the command would not * be assigned to any aliases.</p> * * <p>The first non-conflicted alias becomes the "primary alias."</p> * * @param callable The command * @param aliases A list of aliases * @return The registered command mapping, unless no aliases could be registered */ public Optional<CommandMapping> register(CommandCallable callable, List<String> aliases) { return register(callable, aliases, Functions.<List<String>>identity()); } public synchronized Optional<CommandMapping> register(CommandCallable callable, List<String> aliases, Function<List<String>, List<String>> callback) { checkNotNull(aliases); checkNotNull(callable); checkNotNull(callback); List<String> free = new ArrayList<String>(); // Filter out commands that are already registered for (String alias : aliases) { if (!commands.containsKey(alias.toLowerCase())) { free.add(alias); } } // Invoke the callback with the commands that /can/ be registered //noinspection ConstantConditions free = new ArrayList<String>(callback.apply(free)); if (!free.isEmpty()) { // The callback should /not/ have added any new commands for (String alias : free) { if (commands.containsKey(alias.toLowerCase())) { throw new IllegalArgumentException("A command by the name of '" + alias + "' already exists"); } } String primary = free.get(0); List<String> secondary = free.subList(1, free.size()); CommandMapping mapping = new ImmutableCommandMapping(callable, primary, secondary); for (String alias : free) { commands.put(alias.toLowerCase(), mapping); } return Optional.of(mapping); } else { return Optional.absent(); } } /** * Remove a mapping identified by the given alias. * * @param alias The alias * @return The previous mapping associated with the alias, if one was found */ public synchronized Optional<CommandMapping> remove(String alias) { return Optional.of(commands.remove(alias.toLowerCase())); } /** * Remove all mappings identified by the given aliases. * * @param c A collection of aliases * @return Whether any were found */ public synchronized boolean removeAll(Collection<?> c) { checkNotNull(c); boolean found = false; for (Object alias : c) { commands.remove(alias.toString().toLowerCase()); found = true; } return found; } /** * Remove a command identified by the given mapping. * * @param mapping The mapping * @return The previous mapping associated with the alias, if one was found */ public synchronized Optional<CommandMapping> removeMapping(CommandMapping mapping) { checkNotNull(mapping); CommandMapping found = null; Iterator<CommandMapping> it = commands.values().iterator(); while (it.hasNext()) { CommandMapping current = it.next(); if (current.equals(mapping)) { it.remove(); found = current; } } return Optional.fromNullable(found); } /** * Remove all mappings contained with the given collection. * * @param c The collection * @return Whether the at least one command was removed */ public synchronized boolean removeMappings(Collection<?> c) { checkNotNull(c); boolean found = false; Iterator<CommandMapping> it = commands.values().iterator(); while (it.hasNext()) { if (c.contains(it.next())) { it.remove(); found = true; } } return found; } @Override public synchronized Set<CommandMapping> getCommands() { return ImmutableSet.copyOf(commands.values()); } @Override public synchronized Set<String> getPrimaryAliases() { Set<String> aliases = new HashSet<String>(); for (CommandMapping mapping : commands.values()) { aliases.add(mapping.getPrimaryAlias()); } return Collections.unmodifiableSet(aliases); } @Override public synchronized Set<String> getAliases() { Set<String> aliases = new HashSet<String>(); for (CommandMapping mapping : commands.values()) { aliases.addAll(mapping.getAllAliases()); } return Collections.unmodifiableSet(aliases); } @Override public synchronized Optional<CommandMapping> get(String alias) { return Optional.fromNullable(commands.get(alias.toLowerCase())); } @Override public synchronized boolean containsAlias(String alias) { return commands.containsKey(alias.toLowerCase()); } @Override public boolean containsMapping(CommandMapping mapping) { checkNotNull(mapping); for (CommandMapping test : commands.values()) { if (mapping.equals(test)) { return true; } } return false; } /** * Get the number of registered aliases. * * @return The number of aliases */ public synchronized int size() { return commands.size(); } @Override public boolean call(CommandSource source, String arguments, List<String> parents) throws CommandException { String[] parts = arguments.split(" +", 2); Optional<CommandMapping> mapping = get(parts[0]); if (mapping.isPresent()) { List<String> passedParents = new ArrayList<String>(parents.size() + 1); passedParents.addAll(parents); passedParents.add(parts[0]); mapping.get().getCallable().call(source, parts.length > 1 ? parts[1] : "", Collections.unmodifiableList(passedParents)); return true; } else { return false; } } @Override public synchronized boolean testPermission(CommandSource source) { for (CommandMapping mapping : commands.values()) { if (!mapping.getCallable().testPermission(source)) { return false; } } return true; } @Override public List<String> getSuggestions(CommandSource source, String arguments) throws CommandException { String[] parts = arguments.split(" +", 2); List<String> suggestions = new ArrayList<String>(); if (parts.length == 1) { // Auto completing commands String incompleteCommand = parts[0].toLowerCase(); synchronized (this) { for (CommandMapping mapping : commands.values()) { for (String alias : mapping.getAllAliases()) { if (alias.toLowerCase().startsWith(incompleteCommand)) { suggestions.add(alias); } } } } } else { // Complete using subcommand Optional<CommandMapping> mapping = get(parts[0]); if (mapping.isPresent()) { mapping.get().getCallable().getSuggestions(source, parts.length > 1 ? parts[1] : ""); } } return Collections.unmodifiableList(suggestions); } @Override public Optional<String> getShortDescription() { return Optional.absent(); } @Override public Optional<String> getHelp() { return Optional.absent(); } @Override public String getUsage() { return "<sub-command>"; // @TODO: Translate } }
package java8_in_action.chapter5; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.function.LongSupplier; import java.util.stream.*; public class Exercise5_5_1 { public static void main(String... args) { System.out.println("exercise 5.5.1 starting..."); // domain for this exercise Trader raoul = new Trader("Raoul", "Cambridge"); Trader mario = new Trader("Mario", "Milan"); Trader alan = new Trader("Alan", "Cambridge"); Trader brian = new Trader("Brian", "Cambridge"); List<Transaction> transactions = Arrays.asList( new Transaction(brian, 2011, 300), new Transaction(raoul, 2012, 1000), new Transaction(raoul, 2011, 400), new Transaction(mario, 2012, 710), new Transaction(mario, 2012, 700), new Transaction(alan, 2012, 950)); //1.  Find all transactions in the year 2011 and sort them by value (small to high). List<Transaction> txn2011ByValue = transactions.stream() .filter(t -> t.getYear() == 2011) .sorted(Comparator.comparing(Transaction::getValue)) .collect(Collectors.toList()); System.out.println("2011 txns by value, list=" + txn2011ByValue); //2.  What are all the unique cities where the traders work? List<String> uniqueCities = transactions.stream() .map(Transaction::getTrader) .map(Trader::getCity) .distinct() .collect(Collectors.toList()); System.out.println("unique cities=" + uniqueCities); //3.  Find all traders from Cambridge and sort them by name. List<Trader> cambridgeTraders = transactions.stream() .map(Transaction::getTrader) .filter(trader -> trader.getCity().equalsIgnoreCase("cambridge")) .distinct() .sorted(Comparator.comparing(Trader::getName)) .collect(Collectors.toList()); System.out.println("Cambridge traders=" + cambridgeTraders); String traders = transactions.stream() .map(Transaction::getTrader) .map(Trader::getName) .distinct() .sorted() .collect(Collectors.joining(" ")); System.out.println("trader names=" + traders); //5.  Are any traders based in Milan? boolean anyMilanTraders = transactions.stream().anyMatch(t -> t.getTrader().getCity().equalsIgnoreCase("milan")); System.out.println("any milan traders=" + anyMilanTraders); List<Integer> txnVals = transactions.stream() .filter(transaction -> transaction.getTrader().getCity().equalsIgnoreCase("cambridge")) .map(Transaction::getValue) .collect(Collectors.toList()); System.out.println("cambridge txn vals=" + txnVals); transactions.stream().map(Transaction::getValue).max(Integer::compareTo) .ifPresent(val -> System.out.println("max txn val=" + val)); // TODO - how to handle no max case? //8.  Find the transaction with the smallest value. transactions.stream() .reduce((t1,t2) -> t1.getValue() <= t2.getValue() ? t1 : t2) .ifPresent(t -> System.out.println("min val txn=" + t)); // same solution using min transactions.stream() .min(Comparator.comparing(Transaction::getValue)) .ifPresent(t -> System.out.println("#2 min val txn=" + t)); System.out.println("exercise 5.5.1 done."); // exercise from 5.6 to generate pythagorean triples int max = 100; IntStream.rangeClosed(1, max) .boxed() .flatMap(a -> IntStream.rangeClosed(a, max) .mapToObj( b -> new double[] {a, b, Math.sqrt(a*a + b*b)}) ) .filter(i -> i[2] % 1.0 == 0) .forEach(i -> System.out.println("[" + (int) i[0] + "," + (int) i[1] + "," + (int) i[2] + "]")); // 5.7 generate fibonacci tuples (0,1), (1,1), (1,2), (2,3), (3,5), (5,8) Stream.iterate(new int[]{0,1}, i -> new int[]{i[1], i[0] + i[1]}) .limit(20) .forEach(i -> System.out.println("(" + i[0] + "," + i[1] + ")")); // same as above but only print Fibonacci series Stream.iterate(new int[]{0,1}, i -> new int[]{i[1], i[0] + i[1]}) .limit(20) .mapToInt(i -> i[0]) .forEach(System.out::println); // 5.7 generate random numbers DoubleStream.generate(Math::random) .limit(5) .forEach(System.out::println); // 5.7 generate numbers using stateful supplier LongStream.generate(new SquaresSupplier()) .limit(15) .forEach(System.out::println); } public static class SquaresSupplier implements LongSupplier { long initialVal; public SquaresSupplier(long i) { initialVal = i; } public SquaresSupplier() { this(0); } @Override public long getAsLong() { // increment val and then square it return ++initialVal * initialVal; } } }
package com.vav.CTCI.Chapter1; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; public class QX_RemoveDuplicates { public static void main(String arg[]){ System.out.println(removeDuplicatesBF(new String("testeddbybxx"))); Enumeration<Character> en = removeDuplicatesHashmaps(new String("testeddbybxx")); while(en.hasMoreElements()){ System.out.print(en.nextElement()+"-"); } } //1. Replacing the last character with duplicates O(n2), only replaces duplicates not triples or more public static String removeDuplicatesBF(String str){ char[] chars = str.toCharArray(); int length = str.length(); char temp; for(int i=0;i<chars.length-1;i++){ for(int j=chars.length-1;j>i;){ if(chars[i]==chars[j]){ --length; temp=chars[j]; chars[j]=chars[length]; chars[length]=temp; } --j; } } return new String(chars).substring(0,length); } //2. Sorting and then replacing last chars with duplicates O(nlog(n)) public static String removeDuplicatesSorting(String str){ char[] chars = str.toCharArray(); Arrays.sort(chars); int length = str.length(); char temp; int i=0; for(int j=1;j<chars.length-1;j++){ if(chars[i]!=chars[j]){ i++; chars[i]=chars[j]; } } return new String(chars).substring(0,i+1); } //3. Remove duplicates using hashmaps O(n) private static Enumeration removeDuplicatesHashmaps(String s) { char[] chars = s.toCharArray(); Hashtable hashtable = new Hashtable(); for(int i=0;i<chars.length;i++){ if(!hashtable.containsKey(chars[i])){ hashtable.put(chars[i],0); } } return hashtable.keys(); } }
package com.frc4343.robot2; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DriverStationLCD.Line; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Victor; public class RobotTemplate extends IterativeRobot { Logger logger = new Logger(); Timer indexingTimer = new Timer(); Timer loadingDelayTimer = new Timer(); Timer accelerationTimer = new Timer(); Joystick joystick = new Joystick(1); Joystick joystick2 = new Joystick(2); Victor launcher = new Victor(3); Relay indexer = new Relay(2); RobotDrive robotDrive = new RobotDrive(1, 2); Piston firingPiston = new Piston((byte) 1, (byte) 2, true); Piston climbingPiston = new Piston((byte) 3, (byte) 4, true); Compressor compressor = new Compressor(1, 1); DigitalInput indexerLimitSwitch = new DigitalInput(2); // The default speed for the launch motor to start at. double launcherSpeed = 0.4; double axisCompensation = 0.8; double indexerTimeoutInSeconds = 1.5; double loadingDelay = 0.15; double accelerationDelay = 0.1; // Motor Booleans boolean launcherMotor = false; boolean indexerMotor = false; // Auto-Fire Booleans boolean isIndexing = false; boolean frisbeeLoaded = false; // Button mappings final byte TRIGGER = 1; final byte SPEED_DECREASE = 4; final byte SPEED_INCREASE = 5; final byte LAUNCHER_MOTOR_ENABLE = 6; final byte LAUNCHER_MOTOR_DISABLE = 7; final byte EXTEND_CLIMBING_PISTONS = 3; final byte RETRACT_CLIMBING_PISTONS = 2; // Button Checks boolean triggerHeld = false; boolean adjustedSpeed = false; // This section is relevant only to autonomous. boolean initialAutonomousDelayOver = false; byte numberOfFrisbeesFiredInAutonomous = 0; byte maxFrisbeesToFireInAutonomous = 3; final double autonomousDelayBeforeFirstShot = 4; final double autonomousDelayBetweenEachShot = 3; final double launcherSpeedAtPyramidBack = 0.4; private void resetRobot() { compressor.start(); // Reset the timer. loadingDelayTimer.reset(); loadingDelayTimer.stop(); // Reset the pistons to their default positions. firingPiston.extend(); climbingPiston.extend(); // Reset the number of fired frisbees in autonomous to zero and reset the timer delay to allow for the re-enabling of autonomous. numberOfFrisbeesFiredInAutonomous = 0; // Launcher motor will be enabled in case the drivers forget. launcherMotor = true; } public void teleopInit() { // Initialize the compressor, reset the values, disable the motors. resetRobot(); indexerMotor = false; } public void teleopPeriodic() { /*// This combines the axes in order to allow for both joysticks to control the robot's movement. // One of the joysticks will be made less sensitive to allow for precision control. double sumXAxes = joystick2.getAxis(Joystick.AxisType.kY) + (joystick.getAxis(Joystick.AxisType.kY) * 0.5); double sumYAxes = -joystick2.getAxis(Joystick.AxisType.kX) * axisCompensation + ((-joystick.getAxis(Joystick.AxisType.kX) * axisCompensation) * 0.4); // Floor the values of the combined joysticks in case they are above 1 or below -1. sumXAxes = sumXAxes > 1 ? 1 : sumXAxes; sumXAxes = sumXAxes < -1 ? -1 : sumXAxes; sumYAxes = sumYAxes > 1 ? 1 : sumYAxes; sumYAxes = sumYAxes < -1 ? -1 : sumYAxes; robotDrive.arcadeDrive(sumXAxes, sumYAxes);*/ // The previous code *allegedly* did not allow for the y axis on the second joystick to function. // This new code will arcade drive twice (once for each joystick) to allow for precision control. robotDrive.arcadeDrive(joystick.getAxis(Joystick.AxisType.kX), joystick.getAxis(Joystick.AxisType.kY) * axisCompensation); robotDrive.arcadeDrive(joystick2.getAxis(Joystick.AxisType.kX) * 0.5, joystick2.getAxis(Joystick.AxisType.kY) * 0.5); firingHandler(); launcherMotorHandler(); climbingHandler(); handleConsoleOutputAndMotorBooleans(); } public void autonomousInit() { resetRobot(); // The delay which occurs at the beginning of autonomous must be reset. initialAutonomousDelayOver = false; launcherSpeed = launcherSpeedAtPyramidBack; indexerMotor = true; - loadingDelayTimer.start(); } public void autonomousPeriodic() { frisbeeLoaded = loadingDelayTimer.get() >= loadingDelay; // Disable the indexer motor if a frisbee triggers the limit switch. if (indexerLimitSwitch.get()) { isIndexing = true; indexerMotor = false; } // Default Position of Piston if (!frisbeeLoaded) { firingPiston.extend(); } // If the autonomous delay has not finished previously and the is now over, set the boolean and reset the timer. if (loadingDelayTimer.get() >= autonomousDelayBeforeFirstShot && !initialAutonomousDelayOver) { initialAutonomousDelayOver = true; loadingDelayTimer.reset(); } if (initialAutonomousDelayOver) { if (numberOfFrisbeesFiredInAutonomous <= maxFrisbeesToFireInAutonomous) { if (frisbeeLoaded) { if (loadingDelayTimer.get() >= autonomousDelayBetweenEachShot) { numberOfFrisbeesFiredInAutonomous++; launcherSpeed = 1; accelerationTimer.start(); } } } } if (accelerationTimer.get() >= accelerationDelay) { firingPiston.retract(); isIndexing = false; frisbeeLoaded = false; loadingDelayTimer.reset(); launcherSpeed = 0.4; accelerationTimer.stop(); accelerationTimer.reset(); } if (initialAutonomousDelayOver && !frisbeeLoaded && !isIndexing) { indexerMotor = true; } handleConsoleOutputAndMotorBooleans(); } private void handleConsoleOutputAndMotorBooleans() { // Set the state of the motors based on the values of the booleans controlling them. indexer.set(indexerMotor ? Relay.Value.kForward : Relay.Value.kOff); launcher.set(launcherMotor ? launcherSpeed : 0); // Print the debug output the the DriverStation console. printConsoleOutput(); } private void launcherMotorHandler() { // Manual Enable/Disable if (joystick.getRawButton(LAUNCHER_MOTOR_ENABLE) || joystick2.getRawButton(LAUNCHER_MOTOR_ENABLE)) { launcherMotor = true; } else if (joystick.getRawButton(LAUNCHER_MOTOR_DISABLE) || joystick2.getRawButton(LAUNCHER_MOTOR_DISABLE)) { launcherMotor = false; } if (joystick.getRawButton(SPEED_INCREASE) ^ joystick.getRawButton(SPEED_DECREASE)) { // If the buttons have not been pressed previously. if (!adjustedSpeed) { // speed change if (joystick.getRawButton(SPEED_INCREASE)) { launcherSpeed += 0.001; } if (joystick.getRawButton(SPEED_DECREASE)) { launcherSpeed -= 0.001; } } adjustedSpeed = true; } } private void firingHandler() { frisbeeLoaded = loadingDelayTimer.get() >= loadingDelay; if (frisbeeLoaded) { loadingDelayTimer.stop(); loadingDelayTimer.reset(); } else if (!frisbeeLoaded) { firingPiston.extend(); } if (indexerLimitSwitch.get() || indexingTimer.get() >= indexerTimeoutInSeconds) { indexerMotor = false; indexingTimer.stop(); indexingTimer.reset(); if (indexerLimitSwitch.get() && !(indexingTimer.get() >= indexerTimeoutInSeconds)) { isIndexing = true; loadingDelayTimer.start(); } } if (joystick.getRawButton(TRIGGER)) { if (!triggerHeld) { if (frisbeeLoaded) { launcherSpeed = 1; accelerationTimer.start(); } else if (!frisbeeLoaded && !isIndexing) { indexerMotor = true; indexingTimer.start(); } } triggerHeld = joystick.getRawButton(TRIGGER); } if (accelerationTimer.get() >= accelerationDelay) { firingPiston.retract(); isIndexing = false; frisbeeLoaded = false; launcherSpeed = 0.4; accelerationTimer.stop(); accelerationTimer.reset(); } // Just in case, keeping manual eject :P if (joystick.getRawButton(9)) { firingPiston.retract(); frisbeeLoaded = false; } } private void climbingHandler() { if (joystick.getRawButton(EXTEND_CLIMBING_PISTONS)) { climbingPiston.extend(); } else if (joystick.getRawButton(RETRACT_CLIMBING_PISTONS)) { climbingPiston.retract(); } } private void printConsoleOutput() { // Clears driverStation text. logger.clearWindow(); // Prints State of Frisbee logger.printLine(Line.kUser1, frisbeeLoaded ? "Frisbee Loaded: YES" : "Frisbee Loaded: NO"); // Print the speed. logger.printLine(Line.kUser2, "Launcher Speed: " + (byte)(launcherSpeed * 100) + "%"); // Prints State of Launcher Motor logger.printLine(Line.kUser3, launcherMotor ? "Launcher Motor: ON" : "Launcher Motor: OFF"); // Prints State of Launcher Motor logger.printLine(Line.kUser4, indexerMotor ? "Indexer Motor: ON" : "Indexer Motor: OFF"); // Print the tank pressurization state. logger.printLine(Line.kUser5, compressor.getPressureSwitchValue() ? "Tanks Full: YES" : "Tanks Full: NO"); // Updates the output window. logger.updateLCD(); } }
package me.gowdru.notes.sort; import java.util.Comparator; /** * Defines contract for Sorter algorithm implementations */ public interface Sorter<T> { /** * sorts {@code items}i in an array by comparing them using {@code comparator} * @param items items to be sorted * @param comparator comparison assistant */ public void sort(T[] items, Comparator<T> comparator); /** * swaps a pair of elements in array * @param array - array of items * @param pos1 position of an item to be swapped to/with * @param pos2 position of another item to be swapped to/with */ public default void swap(T[] array, int pos1, int pos2){ T tmp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = tmp; } }
package cs195n; import java.awt.Graphics2D; import java.awt.event.*; public abstract class CS195NFrontEnd { /** * Called at a regular interval set by {@link #setTickFrequency(long)}. Use to update any state * that changes over time. * * @param nanosSincePreviousTick approximate number of nanoseconds since the previous call * to onTick */ protected abstract void onTick(long nanosSincePreviousTick); /** * Called when the screen needs to be redrawn. This is at least once per tick, but possibly * more frequently (for example, when the window is resizing). * <br><br> * Note that the entire drawing area is cleared before each call to this method. Furthermore, * {@link #onResize} is guaranteed to be called before the first invocation of onDraw. * * @param g a {@link Graphics2D} object used for drawing. */ protected abstract void onDraw(Graphics2D g); /** * @param e an AWT {@link KeyEvent} representing the input event. * @see KeyListener#keyTyped(KeyEvent) */ protected abstract void onKeyTyped(KeyEvent e); /** * @param e an AWT {@link KeyEvent} representing the input event. * @see KeyListener#keyPressed(KeyEvent) */ protected abstract void onKeyPressed(KeyEvent e); /** * @param e an AWT {@link KeyEvent} representing the input event. * @see KeyListener#keyReleased(KeyEvent) */ protected abstract void onKeyReleased(KeyEvent e); /** * @param e an AWT {@link MouseEvent} representing the input event. * @see MouseListener#mouseClicked(MouseEvent) */ protected abstract void onMouseClicked(MouseEvent e); /** * @param e an AWT {@link MouseEvent} representing the input event. * @see MouseListener#mousePressed(MouseEvent) */ protected abstract void onMousePressed(MouseEvent e); /** * @param e an AWT {@link MouseEvent} representing the input event. * @see MouseListener#mouseReleased(MouseEvent) */ protected abstract void onMouseReleased(MouseEvent e); /** * @param e an AWT {@link MouseEvent} representing the input event. * @see MouseMotionListener#mouseDragged(MouseEvent) */ protected abstract void onMouseDragged(MouseEvent e); /** * @param e an AWT {@link MouseEvent} representing the input event. * @see MouseMotionListener#mouseMoved(MouseEvent) */ protected abstract void onMouseMoved(MouseEvent e); /** * @param e an AWT {@link MouseWheelEvent} representing the input event. * @see MouseWheelListener#mouseWheelMoved(MouseWheelEvent) */ protected abstract void onMouseWheelMoved(MouseWheelEvent e); /** * Called when the size of the drawing area changes. Any subsequent calls to onDraw should note * the new size and be sure to fill the entire area appropriately. Guaranteed to be called * before the first call to onDraw. * * @param newSize the new size of the drawing area. */ protected abstract void onResize(Vec2i newSize); public final void startup() { if (!running) { running = true; doStartup(); } } public final void shutdown() { if (running) { doShutdown(); running = false; } } /** * Returns whether or not events are currently being processed (specifically, if {@link #startup()} * has been called without a corresponding call to {@link #shutdown()}). * * @return true if the front-end is running, false if not */ public final boolean isRunning() { return running; } /** * Switches the front-end between fullscreen and windowed. * * @param fullscreen true for fullscreen, false for windowed */ public final void setFullscreen(boolean fullscreen) { if (fullscreen != this.fullscreen) { this.fullscreen = fullscreen; doSetFullscreen(); } } /** * Gets whether the front-end is currently fullscreen or windowed. * @return true if the fullscreen is currently set, false if windowed */ public final boolean isFullscreen() { return fullscreen; } /** * Enable or disable debug mode. When debug mode is enabled, the current size of the draw area * and aspect ratio is displayed in the title of the window along with the current FPS count, * and pressing F12 will bring up a dialog to resize the window. * @param debug true to enable debug mode, false to disable */ public final void setDebugMode(boolean debug) { if (debug != this.debug) { this.debug = debug; doSetDebugMode(); } } /** * Gets whether debug mode is currently set. * @return true if the debug mode is currently on, false if not */ public final boolean isDebugMode() { return debug; } /** * Controls the frequency of {@link #onTick(long) onTick()} calls. Ticks will occur approximately * once every <code>nanoDelay</code> nanoseconds, but <b>no specific accuracy guarantees can be * made</b>. Always use the argument of onTick to determine the actual amount of time passed. * * @param nanoDelay the number of nanoseconds between the start of each ticks. For example, * for 50 FPS, this value would be 1000000000/50 (20000000). Must be >= 0. */ public final void setTickFrequency(long nanoDelay) { if (nanoDelay < 0) throw new IllegalArgumentException("nanoDelay must be >= 0"); doSetTickFrequency(nanoDelay); } /** * Actually set the tick frequency. <code>nanoDelay</code> is guaranteed to be valid (>= 0). */ abstract void doSetTickFrequency(long nanoDelay); /** * Actually run code to go fullscreen or windowed. The <code>fullscreen</code> field will hold * the value of the desired new state. When returning from fullscreen back to windowed, it's * nice if the subclass remembers the old window size and position, but this behavior is not * strictly required. */ abstract void doSetFullscreen(); /** * Actually run code to enable or disable debug mode. The <code>debug</code> field will hold the * value of the desired new state. */ abstract void doSetDebugMode(); /** * Actually run code to start up. NO EVENTS SHOULD BE DELIVERED BEFORE THIS IS CALLED IN CASE * THE USER WANTS TO DO SETUP. */ abstract void doStartup(); /** * Actually run code to shut down. */ abstract void doShutdown(); /** * The default window size; should be passed to the constructor if the user does not specify a * window size. */ protected static final Vec2i DEFAULT_WINDOW_SIZE = new Vec2i(960, 540); /** * The minimum window size. Games are expected to work with resolutions at least this small; * smaller resolutions will not be tested or graded, and the window should not allow itself to * be resized any smaller than this. */ static final Vec2i MINIMUM_WINDOW_SIZE = new Vec2i(960, 540); // default access is intentional boolean fullscreen; Vec2i windowedSize; volatile boolean running = false; boolean debug = true; /** * Constructor. Note that this currently just stores the values; subclasses should actually create * a window or go fullscreen after this based on the values of <code>fullscreen</code> and * <code>windowSize</code>. * * @param fullscreen true for starting in fullscreen, false for starting in a window * @param windowSize the starting window size */ CS195NFrontEnd(boolean fullscreen, Vec2i windowSize) { this.fullscreen = fullscreen; this.windowedSize = windowSize; } }
package org.helioviewer.jhv; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import org.helioviewer.jhv.base.logging.Log; import org.helioviewer.jhv.threads.JHVExecutor; /** * Intended to be a class for static functions and fields relevant to the * application as a whole. * * @author caplins */ public class JHVGlobals { public static final String TEMP_FILENAME_DELETE_PLUGIN_FILES = "delete-plugins.tmp"; private static final String name = "ESA JHelioviewer"; private static String version = ""; private static String revision = ""; private static String agent = "JHV/SWHV-"; private JHVGlobals() {} public static final boolean GoForTheBroke = true; public static final int hiDpiCutoff = 1024; private static ExecutorService executorService; public static ExecutorService getExecutorService() { if (executorService == null) { executorService = JHVExecutor.getJHVWorkersExecutorService("MAIN", 10); } return executorService; } /** * @return standard read timeout */ public static int getStdReadTimeout() { return Integer.parseInt(Settings.getSingletonInstance().getProperty("connection.read.timeout")); } /** * @return standard connect timeout */ public static int getStdConnectTimeout() { return Integer.parseInt(Settings.getSingletonInstance().getProperty("connection.connect.timeout")); } /** * This function must be called prior to the first call to getJhvVersion and * getJhvRevision */ public static void determineVersionAndRevision() { File jarPath; try { jarPath = new File(JHVGlobals.class.getProtectionDomain().getCodeSource().getLocation().toURI()); Log.info(">> JHVGlobals.determineVersionAndRevision() > Look for jar file: " + jarPath.getAbsolutePath()); } catch (URISyntaxException e1) { Log.error(">> JHVGlobals.determineVersionAndRevision() > Could not open code source location: " + JHVGlobals.class.getProtectionDomain().getCodeSource().getLocation().toString()); Log.warn(">> JHVGlobals.determineVersionAndRevision() > Set version and revision to null."); return; } JarFile jarFile = null; if (jarPath.isFile()) { try { jarFile = new JarFile(jarPath); Manifest manifest = jarFile.getManifest(); Attributes mainAttributes = manifest.getMainAttributes(); version = mainAttributes.getValue("version"); revision = mainAttributes.getValue("revision"); agent += version + "." + revision; System.setProperty("jhv.version", version); System.setProperty("jhv.revision", revision); } catch (IOException e) { Log.error(">> JHVGlobals.determineVersionAndRevision() > Error while reading version and revision from manifest in jar file: " + jarFile.getName(), e); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { Log.error(">> JHVGlobals.determineVersionAndRevision() > Error while closing stream to jar file: " + jarFile.getName(), e); } } } } else { Log.warn(">> JHVGlobals.determineVersionAndRevision() > Classes are not within a jar file. Set version and revision to null."); } } /** * Returns the version of JHelioviewer as found in the manifest file of the * jar archive * * @return the version or empty string if the classes are not within a jar archive * or the manifest does not contain the version */ public static String getJhvVersion() { return version; } /** * Returns the revision of JHelioviewer as found in the manifest file of the * jar archive * * @return the revision or empty string if the classes are not within a jar archive * or the manifest does not contain the revision */ public static String getJhvRevision() { return revision; } public static String getUserAgent() { return agent; } public static String getProgramName() { return name; } /** * Attempts to create the necessary directories if they do not exist. It * gets its list of directories to create from the JHVDirectory class. * * @throws SecurityException */ public static void createDirs() { JHVDirectory[] dirs = JHVDirectory.values(); for (JHVDirectory dir : dirs) { File f = dir.getFile(); if (!f.exists()) { f.mkdirs(); } } } public static void openURL(String url) { try { Desktop.getDesktop().browse(new URI(url)); } catch (Exception e) { e.printStackTrace(); } } public static void displayNotification(String msg, String openURL) { if (System.getProperty("jhv.os").equals("mac")) { try { File jarPath = new File(JHVGlobals.class.getProtectionDomain().getCodeSource().getLocation().toURI()); String[] cmd = new String[] { jarPath.getCanonicalFile().getParentFile().getParent() + "/Helpers/terminal-notifier.app/Contents/MacOS/terminal-notifier", "-message", "\"" + msg + "\"", "-execute", "open " + "\"" + openURL + "\"", "-title", "JHelioviewer" }; Log.info(">> displayNotification " + Arrays.toString(cmd)); Runtime.getRuntime().exec(cmd); } catch (Exception e) { StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); Log.error(">> displayNotification " + errors.toString()); } } } }
package net.java.sip.communicator.impl.neomedia.codec.audio.speex; import javax.media.*; import javax.media.format.*; import net.java.sip.communicator.impl.neomedia.codec.*; /** * @author Lubomir Marinov */ public class SpeexResampler extends AbstractCodecExt { /** * The list of <tt>Format</tt>s of audio data supported as input and output * by <tt>SpeexResampler</tt> instances. */ private static final Format[] SUPPORTED_FORMATS; /** * The list of sample rates of audio data supported as input and output by * <tt>SpeexResampler</tt> instances. */ private static final double[] SUPPORTED_SAMPLE_RATES = new double[] { 8000, 11025, 16000, 22050, 32000, 44100, 48000, Format.NOT_SPECIFIED }; static { Speex.assertSpeexIsFunctional(); int count = SUPPORTED_SAMPLE_RATES.length; SUPPORTED_FORMATS = new Format[count]; for (int i = 0; i < count; i++) { SUPPORTED_FORMATS[i] = new AudioFormat( AudioFormat.LINEAR, SUPPORTED_SAMPLE_RATES[i], 16 /* sampleSizeInBits */, 1 /* channels */, AudioFormat.LITTLE_ENDIAN, AudioFormat.SIGNED, 16, SUPPORTED_SAMPLE_RATES[i], Format.byteArray); } } /** * The input sample rate configured in {@link #resampler}. */ private int inputSampleRate; /** * The output sample rate configured in {@link #resampler}. */ private int outputSampleRate; /** * The pointer to the native <tt>SpeexResamplerState</tt> which is * represented by this instance. */ private long resampler; /** * Initializes a new <tt>SpeexResampler</tt> instance. */ public SpeexResampler() { super("Speex Resampler", AudioFormat.class, SUPPORTED_FORMATS); inputFormats = SUPPORTED_FORMATS; } /** * @see AbstractCodecExt#doClose() */ protected void doClose() { if (resampler != 0) { Speex.speex_resampler_destroy(resampler); resampler = 0; } } /** * @throws ResourceUnavailableException * @see AbstractCodecExt#doOpen() */ protected void doOpen() throws ResourceUnavailableException { } /** * @param inputBuffer * @param outputBuffer * @return * @see AbstractCodecExt#doProcess(Buffer, Buffer) */ protected int doProcess(Buffer inputBuffer, Buffer outputBuffer) { Format inputFormat = inputBuffer.getFormat(); if ((inputFormat != null) && (inputFormat != this.inputFormat) && !inputFormat.equals(this.inputFormat)) { if (null == setInputFormat(inputFormat)) return BUFFER_PROCESSED_FAILED; } inputFormat = this.inputFormat; AudioFormat inputAudioFormat = (AudioFormat) inputFormat; int inputSampleRate = (int) inputAudioFormat.getSampleRate(); AudioFormat outputAudioFormat = (AudioFormat) getOutputFormat(); int outputSampleRate = (int) outputAudioFormat.getSampleRate(); if (inputSampleRate == outputSampleRate) { // passthrough byte[] input = (byte[]) inputBuffer.getData(); int size = (input == null) ? 0 : input.length; byte[] output = validateByteArraySize(outputBuffer, size); if ((input != null) && (output != null)) System.arraycopy(input, 0, output, 0, size); outputBuffer.setFormat(inputBuffer.getFormat()); outputBuffer.setLength(inputBuffer.getLength()); outputBuffer.setOffset(inputBuffer.getOffset()); } else { if ((this.inputSampleRate != inputSampleRate) || (this.outputSampleRate != outputSampleRate)) { if (resampler == 0) { resampler = Speex.speex_resampler_init( 1, inputSampleRate, outputSampleRate, Speex.SPEEX_RESAMPLER_QUALITY_VOIP, 0); } else { Speex.speex_resampler_set_rate( resampler, inputSampleRate, outputSampleRate); } if (resampler != 0) { this.inputSampleRate = inputSampleRate; this.outputSampleRate = outputSampleRate; } } if (resampler == 0) return BUFFER_PROCESSED_FAILED; byte[] input = (byte[]) inputBuffer.getData(); int inputLength = inputBuffer.getLength(); int sampleSizeInBytes = inputAudioFormat.getSampleSizeInBits() / 8; int inputSampleCount = inputLength / sampleSizeInBytes; int outputLength = (inputLength * outputSampleRate) / inputSampleRate; byte[] output = validateByteArraySize(outputBuffer, outputLength); int outputSampleCount = outputLength / sampleSizeInBytes; outputSampleCount = Speex.speex_resampler_process_interleaved_int( resampler, input, inputBuffer.getOffset(), inputSampleCount, output, 0, outputSampleCount); outputBuffer.setFormat(outputAudioFormat); outputBuffer.setLength(outputSampleCount * sampleSizeInBytes); outputBuffer.setOffset(0); } outputBuffer.setDuration(inputBuffer.getDuration()); outputBuffer.setEOM(inputBuffer.isEOM()); outputBuffer.setFlags(inputBuffer.getFlags()); outputBuffer.setHeader(inputBuffer.getHeader()); outputBuffer.setSequenceNumber(inputBuffer.getSequenceNumber()); outputBuffer.setTimeStamp(inputBuffer.getTimeStamp()); return BUFFER_PROCESSED_OK; } /** * @param format * @return * @see AbstractCodecExt#setInputFormat(Format) */ @Override public Format setInputFormat(Format format) { AudioFormat inputFormat = (AudioFormat) super.setInputFormat(format); if (inputFormat != null) { double outputSampleRate = (outputFormat == null) ? inputFormat.getSampleRate() : ((AudioFormat) outputFormat).getSampleRate(); setOutputFormat( new AudioFormat( inputFormat.getEncoding(), outputSampleRate, inputFormat.getSampleSizeInBits(), inputFormat.getChannels(), inputFormat.getEndian(), inputFormat.getSigned(), Format.NOT_SPECIFIED, inputFormat.getFrameSizeInBits(), inputFormat.getDataType())); } return inputFormat; } }
package net.java.sip.communicator.plugin.generalconfig; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import net.java.sip.communicator.plugin.generalconfig.autoaway.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.systray.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.swing.*; import org.osgi.framework.*; /** * The general configuration form. * * @author Yana Stamcheva */ public class GeneralConfigurationPanel extends TransparentPanel { /** * The <tt>Logger</tt> used by this <tt>GeneralConfigurationPanel</tt> for * logging output. */ private final Logger logger = Logger.getLogger(GeneralConfigurationPanel.class); /** * Creates the general configuration panel. */ public GeneralConfigurationPanel() { super(new BorderLayout()); TransparentPanel mainPanel = new TransparentPanel(); BoxLayout boxLayout = new BoxLayout(mainPanel, BoxLayout.Y_AXIS); mainPanel.setLayout(boxLayout); this.add(mainPanel, BorderLayout.NORTH); Component startupConfigPanel = createStartupConfigPanel(); if (startupConfigPanel != null) { mainPanel.add(startupConfigPanel); mainPanel.add(Box.createVerticalStrut(10)); mainPanel.add(new JSeparator()); } mainPanel.add(createMessageConfigPanel()); mainPanel.add(new JSeparator()); mainPanel.add(new AutoAwayConfigurationPanel()); mainPanel.add(new JSeparator()); mainPanel.add(Box.createVerticalStrut(10)); Component notifConfigPanel = createNotificationConfigPanel(); if (notifConfigPanel != null) { mainPanel.add(notifConfigPanel); mainPanel.add(Box.createVerticalStrut(4)); mainPanel.add(new JSeparator()); mainPanel.add(Box.createVerticalStrut(10)); } mainPanel.add(createLocaleConfigPanel()); mainPanel.add(Box.createVerticalStrut(4)); mainPanel.add(new JSeparator()); mainPanel.add(Box.createVerticalStrut(10)); mainPanel.add(createSipConfigPanel()); mainPanel.add(Box.createVerticalStrut(10)); } /** * Returns the application name. * @return the application name */ private String getApplicationName() { return Resources.getSettingsString("service.gui.APPLICATION_NAME"); } /** * Initializes the auto start checkbox. Used only on windows. * @return the created auto start check box */ private Component createAutoStartCheckBox() { final JCheckBox autoStartCheckBox = new SIPCommCheckBox(); autoStartCheckBox.setAlignmentX(JCheckBox.LEFT_ALIGNMENT); String label = Resources.getString( "plugin.generalconfig.AUTO_START", new String[]{getApplicationName()}); autoStartCheckBox.setText(label); autoStartCheckBox.setToolTipText(label); autoStartCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { setAutostart(autoStartCheckBox.isSelected()); } catch (Exception ex) { logger.error("Cannot create/delete startup shortcut", ex); } } }); try { if(WindowsStartup.isStartupEnabled(getApplicationName())) autoStartCheckBox.setSelected(true); else autoStartCheckBox.setSelected(false); } catch (Exception e) { logger.error(e); } return autoStartCheckBox; } /** * Creates the message configuration panel. * @return the created panel */ private Component createMessageConfigPanel() { JPanel messagePanel = new TransparentPanel(new BorderLayout()); Component messageLabel = GeneralConfigPluginActivator.createConfigSectionComponent( Resources.getString("service.gui.MESSAGE")); JPanel configPanel = new TransparentPanel(); configPanel.setLayout(new BoxLayout(configPanel, BoxLayout.Y_AXIS)); configPanel.add(createGroupMessagesCheckbox()); configPanel.add(Box.createVerticalStrut(10)); configPanel.add(createHistoryPanel()); configPanel.add(Box.createVerticalStrut(10)); configPanel.add(createSendMessagePanel()); configPanel.add(Box.createVerticalStrut(10)); configPanel.add(createTypingNitificationsCheckBox()); configPanel.add(Box.createVerticalStrut(10)); configPanel.add(createBringToFrontCheckBox()); configPanel.add(Box.createVerticalStrut(10)); configPanel.add(createMultichatCheckbox()); configPanel.add(Box.createVerticalStrut(10)); messagePanel.add(messageLabel, BorderLayout.WEST); messagePanel.add(configPanel); return messagePanel; } /** * Initializes the group messages check box. * @return the created check box */ private Component createGroupMessagesCheckbox() { final JCheckBox groupMessagesCheckBox = new SIPCommCheckBox(); groupMessagesCheckBox.setText( Resources.getString( "plugin.generalconfig.GROUP_CHAT_MESSAGES")); groupMessagesCheckBox.setAlignmentX(JCheckBox.LEFT_ALIGNMENT); groupMessagesCheckBox.setSelected( ConfigurationManager.isMultiChatWindowEnabled()); groupMessagesCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ConfigurationManager.setMultiChatWindowEnabled( groupMessagesCheckBox.isSelected()); } }); return groupMessagesCheckBox; } /** * Initializes the group messages check box. * @return the created check box */ private Component createMultichatCheckbox() { final JCheckBox leaveChatroomCheckBox = new SIPCommCheckBox(); leaveChatroomCheckBox.setText( Resources.getString( "plugin.generalconfig.LEAVE_CHATROOM_ON_WINDOW_CLOSE")); leaveChatroomCheckBox.setAlignmentX(JCheckBox.LEFT_ALIGNMENT); leaveChatroomCheckBox.setSelected( ConfigurationManager.isLeaveChatRoomOnWindowCloseEnabled()); leaveChatroomCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ConfigurationManager.setLeaveChatRoomOnWindowClose( leaveChatroomCheckBox.isSelected()); } }); return leaveChatroomCheckBox; } /** * Initializes the history panel. * @return the created history panel */ private Component createHistoryPanel() { JPanel logHistoryPanel = new TransparentPanel(); logHistoryPanel.setLayout(new BorderLayout()); logHistoryPanel.setAlignmentX(JCheckBox.LEFT_ALIGNMENT); // Log history check box. final JCheckBox logHistoryCheckBox = new SIPCommCheckBox(); logHistoryPanel.add(logHistoryCheckBox, BorderLayout.NORTH); logHistoryCheckBox.setText( Resources.getString("plugin.generalconfig.LOG_HISTORY")); logHistoryCheckBox.setSelected( ConfigurationManager.isHistoryLoggingEnabled()); logHistoryCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ConfigurationManager.setHistoryLoggingEnabled( logHistoryCheckBox.isSelected()); } }); // Show history check box. JPanel showHistoryPanel = new TransparentPanel(); showHistoryPanel.setBorder( BorderFactory.createEmptyBorder(0, 10, 0, 0)); logHistoryPanel.add(showHistoryPanel, BorderLayout.SOUTH); final JCheckBox showHistoryCheckBox = new SIPCommCheckBox(); showHistoryPanel.add(showHistoryCheckBox); showHistoryCheckBox.setText( Resources.getString("plugin.generalconfig.SHOW_HISTORY")); showHistoryCheckBox.setSelected( ConfigurationManager.isHistoryShown()); showHistoryCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ConfigurationManager.setHistoryShown( showHistoryCheckBox.isSelected()); } }); // History size. SpinnerNumberModel historySizeSpinnerModel = new SpinnerNumberModel(0, 0, 140, 1); final JSpinner historySizeSpinner = new JSpinner(); showHistoryPanel.add(historySizeSpinner); historySizeSpinner.setModel(historySizeSpinnerModel); historySizeSpinner.setValue( ConfigurationManager.getChatHistorySize()); logHistoryCheckBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { showHistoryCheckBox.setEnabled( logHistoryCheckBox.isSelected()); historySizeSpinner.setEnabled( logHistoryCheckBox.isSelected()); } }); showHistoryCheckBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { historySizeSpinner.setEnabled( showHistoryCheckBox.isSelected()); } }); historySizeSpinnerModel.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { ConfigurationManager.setChatHistorySize( ((Integer) historySizeSpinner .getValue()).intValue()); } }); JLabel historySizeLabel = new JLabel(); showHistoryPanel.add(historySizeLabel); historySizeLabel.setText( Resources.getString("plugin.generalconfig.HISTORY_SIZE")); if (!ConfigurationManager.isHistoryLoggingEnabled()) { showHistoryCheckBox.setEnabled(false); historySizeSpinner.setEnabled(false); } if (!ConfigurationManager.isHistoryShown()) { historySizeSpinner.setEnabled(false); } return logHistoryPanel; } /** * Initializes the send message configuration panel. * @return the created message config panel */ private Component createSendMessagePanel() { TransparentPanel sendMessagePanel = new TransparentPanel(new BorderLayout(5, 5)); sendMessagePanel.setAlignmentX(JCheckBox.LEFT_ALIGNMENT); JLabel sendMessageLabel = new JLabel(); sendMessagePanel.add(sendMessageLabel, BorderLayout.WEST); sendMessageLabel.setText( Resources.getString("plugin.generalconfig.SEND_MESSAGES_WITH")); ComboBoxModel sendMessageComboBoxModel = new DefaultComboBoxModel( new String[] { ConfigurationManager.ENTER_COMMAND, ConfigurationManager.CTRL_ENTER_COMMAND }); final JComboBox sendMessageComboBox = new JComboBox(); sendMessagePanel.add(sendMessageComboBox); sendMessageComboBox.setModel(sendMessageComboBoxModel); sendMessageComboBox.setSelectedItem( ConfigurationManager.getSendMessageCommand()); sendMessageComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { ConfigurationManager.setSendMessageCommand( (String)sendMessageComboBox.getSelectedItem()); } }); return sendMessagePanel; } /** * Initializes typing notifications panel. * @return the created check box */ private Component createTypingNitificationsCheckBox() { final JCheckBox enableTypingNotifiCheckBox = new SIPCommCheckBox(); enableTypingNotifiCheckBox.setLayout(null); enableTypingNotifiCheckBox.setAlignmentX(JCheckBox.LEFT_ALIGNMENT); enableTypingNotifiCheckBox.setText( Resources.getString("service.gui.ENABLE_TYPING_NOTIFICATIONS")); enableTypingNotifiCheckBox.setPreferredSize( new Dimension(253, 20)); enableTypingNotifiCheckBox.setSelected( ConfigurationManager.isSendTypingNotifications()); enableTypingNotifiCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ConfigurationManager.setSendTypingNotifications( enableTypingNotifiCheckBox.isSelected()); } }); return enableTypingNotifiCheckBox; } /** * Initializes the bring to front check box. * @return the created check box */ private Component createBringToFrontCheckBox() { final JCheckBox bringToFrontCheckBox = new SIPCommCheckBox(); bringToFrontCheckBox.setText( Resources.getString("plugin.generalconfig.BRING_WINDOW_TO_FRONT")); bringToFrontCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); bringToFrontCheckBox.setSelected( ConfigurationManager.isAutoPopupNewMessage()); bringToFrontCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ConfigurationManager.setAutoPopupNewMessage( bringToFrontCheckBox.isSelected()); } }); return bringToFrontCheckBox; } /** * Initializes the notification configuration panel. * @return the created panel */ private Component createNotificationConfigPanel() { ServiceReference[] handlerRefs = null; BundleContext bc = GeneralConfigPluginActivator.bundleContext; try { handlerRefs = bc.getServiceReferences( PopupMessageHandler.class.getName(), null); } catch (InvalidSyntaxException ex) { logger.warn("Error while retrieving service refs", ex); } if (handlerRefs == null) return null; JPanel notifConfigPanel = new TransparentPanel(new BorderLayout()); notifConfigPanel.add( GeneralConfigPluginActivator.createConfigSectionComponent( Resources.getString( "plugin.notificationconfig.POPUP_NOTIF_HANDLER")), BorderLayout.WEST); final JComboBox notifConfigComboBox = new JComboBox(); String configuredHandler = (String) GeneralConfigPluginActivator .getConfigurationService().getProperty("systray.POPUP_HANDLER"); for (ServiceReference ref : handlerRefs) { PopupMessageHandler handler = (PopupMessageHandler) bc.getService(ref); notifConfigComboBox.addItem(handler); if (configuredHandler != null && configuredHandler.equals(handler.getClass().getName())) { notifConfigComboBox.setSelectedItem(handler); } } // We need an entry in combo box that represents automatic // popup handler selection in systray service. It is selected // only if there is no user preference regarding which popup // handler to use. String auto = "Auto"; notifConfigComboBox.addItem(auto); if (configuredHandler == null) { notifConfigComboBox.setSelectedItem(auto); } notifConfigComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent evt) { if (notifConfigComboBox.getSelectedItem() instanceof String) { // "Auto" selected. Delete the user's preference and // select the best available handler. ConfigurationManager.setPopupHandlerConfig(null); GeneralConfigPluginActivator.getSystrayService() .selectBestPopupMessageHandler(); } else { PopupMessageHandler handler = (PopupMessageHandler) notifConfigComboBox.getSelectedItem(); ConfigurationManager.setPopupHandlerConfig( handler.getClass().getName()); GeneralConfigPluginActivator.getSystrayService() .setActivePopupMessageHandler(handler); } } }); notifConfigPanel.add(notifConfigComboBox); return notifConfigPanel; } /** * Initializes the local configuration panel. * @return the created component */ private Component createLocaleConfigPanel() { JPanel localeConfigPanel = new TransparentPanel(new BorderLayout()); localeConfigPanel.add( GeneralConfigPluginActivator.createConfigSectionComponent( Resources.getString( "plugin.generalconfig.DEFAULT_LANGUAGE") + ":"), BorderLayout.WEST); final JComboBox localesConfigComboBox = new JComboBox(); Iterator<Locale> iter = Resources.getResources().getAvailableLocales(); while (iter.hasNext()) { Locale locale = iter.next(); localesConfigComboBox.addItem( locale.getDisplayLanguage(locale)); } Locale currLocale = ConfigurationManager.getCurrentLanguage(); localesConfigComboBox.setSelectedItem(currLocale .getDisplayLanguage(currLocale)); localesConfigComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GeneralConfigPluginActivator.getUIService().getPopupDialog(). showMessagePopupDialog(Resources.getString( "plugin.generalconfig.DEFAULT_LANGUAGE_RESTART_WARN")); String language = (String)localesConfigComboBox.getSelectedItem(); Iterator<Locale> iter = Resources.getResources().getAvailableLocales(); while (iter.hasNext()) { Locale locale = iter.next(); if(locale.getDisplayLanguage(locale) .equals(language)) { ConfigurationManager.setLanguage(locale); break; } } } }); localeConfigPanel.add(localesConfigComboBox, BorderLayout.CENTER); String label = "* " + Resources.getString( "plugin.generalconfig.DEFAULT_LANGUAGE_RESTART_WARN"); JLabel warnLabel = new JLabel(label); warnLabel.setToolTipText(label); warnLabel.setForeground(Color.GRAY); warnLabel.setFont(warnLabel.getFont().deriveFont(8)); warnLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 8, 0)); warnLabel.setHorizontalAlignment(JLabel.RIGHT); localeConfigPanel.add(warnLabel, BorderLayout.SOUTH); return localeConfigPanel; } /** * Initializes the sip port configuration panel. * @return the created panel */ private Component createSipConfigPanel() { JPanel callConfigPanel = new TransparentPanel(new BorderLayout()); callConfigPanel.add( GeneralConfigPluginActivator.createConfigSectionComponent( Resources.getString("service.gui.CALL") + ":"), BorderLayout.WEST); TransparentPanel sipClientPortConfigPanel = new TransparentPanel(); sipClientPortConfigPanel.setLayout(new BorderLayout(10, 10)); sipClientPortConfigPanel.setPreferredSize(new Dimension(250, 72)); callConfigPanel.add(sipClientPortConfigPanel); TransparentPanel labelPanel = new TransparentPanel(new GridLayout(0, 1, 2, 2)); TransparentPanel valuePanel = new TransparentPanel(new GridLayout(0, 1, 2, 2)); sipClientPortConfigPanel.add(labelPanel, BorderLayout.WEST); sipClientPortConfigPanel.add(valuePanel, BorderLayout.CENTER); labelPanel.add(new JLabel( Resources.getString( "plugin.generalconfig.SIP_CLIENT_PORT"))); labelPanel.add(new JLabel( Resources.getString( "plugin.generalconfig.SIP_CLIENT_SECURE_PORT"))); TransparentPanel emptyPanel = new TransparentPanel(); emptyPanel.setMaximumSize(new Dimension(40, 35)); labelPanel.add(emptyPanel); final JTextField clientPortField = new JTextField(6); clientPortField.setText( String.valueOf(ConfigurationManager.getClientPort())); valuePanel.add(clientPortField); clientPortField.addFocusListener(new FocusListener() { private String oldValue = null; public void focusLost(FocusEvent e) { try { int port = Integer.valueOf(clientPortField.getText()); if(port <= 0 || port > 65535) throw new NumberFormatException( "Not a port number"); ConfigurationManager.setClientPort(port); } catch (NumberFormatException ex) { // not a number for port String error = Resources.getString( "plugin.generalconfig.ERROR_PORT_NUMBER"); GeneralConfigPluginActivator.getUIService(). getPopupDialog().showMessagePopupDialog( error, error, PopupDialog.ERROR_MESSAGE); clientPortField.setText(oldValue); } } public void focusGained(FocusEvent e) { oldValue = clientPortField.getText(); } }); final JTextField clientSecurePortField = new JTextField(6); clientSecurePortField.setText( String.valueOf(ConfigurationManager.getClientSecurePort())); valuePanel.add(clientSecurePortField); clientSecurePortField.addFocusListener(new FocusListener() { private String oldValue = null; public void focusLost(FocusEvent e) { try { int port = Integer.valueOf(clientSecurePortField.getText()); if(port <= 0 || port > 65535) throw new NumberFormatException( "Not a port number"); ConfigurationManager.setClientSecurePort(port); } catch (NumberFormatException ex) { // not a number for port String error = Resources.getString( "plugin.generalconfig.ERROR_PORT_NUMBER"); GeneralConfigPluginActivator.getUIService(). getPopupDialog().showMessagePopupDialog( error, error, PopupDialog.ERROR_MESSAGE); clientSecurePortField.setText(oldValue); } } public void focusGained(FocusEvent e) { oldValue = clientSecurePortField.getText(); } }); return callConfigPanel; } /** * Initializes the startup config panel. * @return the created component */ public Component createStartupConfigPanel() { Component updateCheckBox = null; Component autoStartCheckBox = null; if (OSUtils.IS_WINDOWS) { autoStartCheckBox = createAutoStartCheckBox(); updateCheckBox = createUpdateCheckBox(); } JPanel updateConfigPanel = null; if ((updateCheckBox != null) || (autoStartCheckBox != null)) { updateConfigPanel = new TransparentPanel(new BorderLayout()); updateConfigPanel.add( GeneralConfigPluginActivator.createConfigSectionComponent( Resources.getString( "plugin.generalconfig.STARTUP_CONFIG") + ":"), BorderLayout.WEST); if ((updateCheckBox != null) && (autoStartCheckBox != null)) { JPanel checkBoxPanel = new TransparentPanel(new GridLayout(0, 1)); checkBoxPanel.add(autoStartCheckBox); checkBoxPanel.add(updateCheckBox); updateConfigPanel.add(checkBoxPanel); } else if (updateCheckBox != null) updateConfigPanel.add(updateCheckBox); else if (autoStartCheckBox != null) updateConfigPanel.add(autoStartCheckBox); } return updateConfigPanel; } /** * Initializes the update check panel. * @return the created component */ public Component createUpdateCheckBox() { JCheckBox updateCheckBox = new SIPCommCheckBox(); updateCheckBox.setText( Resources.getString("plugin.generalconfig.CHECK_FOR_UPDATES")); updateCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GeneralConfigPluginActivator.getConfigurationService() .setProperty( "net.java.sip.communicator.plugin.updatechecker.ENABLED", Boolean.toString( ((JCheckBox)e.getSource()).isSelected())); } }); updateCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); updateCheckBox.setSelected( GeneralConfigPluginActivator.getConfigurationService().getBoolean(( "net.java.sip.communicator.plugin.updatechecker.ENABLED"), true)); return updateCheckBox; } /** * Sets the auto start. * @param isAutoStart indicates if the auto start property is set to true or * false * @throws Exception if something goes wrong when obtaining the canonical * path or when creating or saving the shortcut */ private void setAutostart(boolean isAutoStart) throws Exception { String workingDir = new File(".").getCanonicalPath(); WindowsStartup.setAutostart( getApplicationName(), workingDir, isAutoStart); } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.services.registry.impl; import org.gridlab.gridsphere.portlet.PortletLog; import org.gridlab.gridsphere.portlet.User; import org.gridlab.gridsphere.portlet.service.PortletServiceUnavailableException; import org.gridlab.gridsphere.portlet.service.spi.PortletServiceConfig; import org.gridlab.gridsphere.portlet.service.spi.PortletServiceProvider; import org.gridlab.gridsphere.portletcontainer.ApplicationPortlet; import org.gridlab.gridsphere.portletcontainer.PortletWebApplication; import org.gridlab.gridsphere.portletcontainer.PortletRegistryManager; import org.gridlab.gridsphere.services.registry.PortletRegistryService; import org.gridlab.gridsphere.layout.PortletLayoutEngine; import javax.servlet.ServletContext; import java.util.*; /** * The PortletRegistryService acts as a repository for portlets and makes them available to the portlet * container, layout manager and any other services that require an active portlet. * The PortletInfo base class is responsible for reading in the associated portlet.xml file and * creating a ConcretePortlet object which represents the portlet. The PortletRegistryService maintains * a Set of RegisteredPortlets and provides operations for the registration, unregistration and querying * of ConcretePortlet objects. */ public class PortletRegistryServiceImpl implements PortletRegistryService, PortletServiceProvider { public final static String CORE_CONTEXT = "coreContext"; private static PortletLog log = org.gridlab.gridsphere.portlet.impl.SportletLog.getInstance(PortletRegistryServiceImpl.class); private static org.gridlab.gridsphere.services.registry.PortletRegistryService registryService = null; private ServletContext context = null; private PortletLayoutEngine layoutEngine = PortletLayoutEngine.getInstance(); private PortletRegistryManager manager = PortletRegistryManager.getInstance(); // A multi-valued hashtable with a webapp key and a List value containing portletAppID's private Map webapps = new Hashtable(); /** * The init method is responsible for parsing portlet.xml and creating ConcretePortlet objects based on the * entries. The RegisteredPortlets are managed by the PortletRegistryService. */ public void init(PortletServiceConfig config) throws PortletServiceUnavailableException { log.info("in init()"); this.context = config.getServletConfig().getServletContext(); String webapp = config.getInitParameter(CORE_CONTEXT); addWebApp(webapp); } public void destroy() { log.info("in destroy()"); } /** * Adds a portlet web application to the registry * * @param the web application name */ public void addPortletWebApplication(User user, String webApplicationName) { addWebApp(webApplicationName); } protected void addWebApp(String webApplicationName) { PortletWebApplication portletWebApp = new PortletWebApplication(webApplicationName, context); Collection appPortlets = portletWebApp.getAllApplicationPortlets(); Iterator it = appPortlets.iterator(); while (it.hasNext()) { ApplicationPortlet appPortlet = (ApplicationPortlet)it.next(); webapps.put(webApplicationName, appPortlet); manager.addApplicationPortlet(appPortlet); } layoutEngine.addApplicationTab(webApplicationName, portletWebApp.getApplicationTab()); } /** * Removes a portlet web application from the registry * * @param the web application name */ public void removePortletWebApplication(User user, String webApplicationName) { ApplicationPortlet appPortlet = (ApplicationPortlet)webapps.get(webApplicationName); manager.removeApplicationPortlet((String)appPortlet.getPortletAppID()); webapps.remove(webApplicationName); } /** * Reloads a portlet web application from the registry * * @param the web application name */ public void reloadPortletWebApplication(User user, String webApplicationName) { removePortletWebApplication(user, webApplicationName); addPortletWebApplication(user, webApplicationName); } /** * Lists all the portlet web applications in the registry * * @return the list of web application names */ public List listPortletWebApplications() { List l = new ArrayList(); Set set = webapps.keySet(); Iterator it = set.iterator(); while (it.hasNext()) { l.add((String)it.next()); } return l; } }
package org.uct.cs.simplify.splitter.memberships; import gnu.trove.map.TIntObjectMap; import org.uct.cs.simplify.ply.reader.MemoryMappedVertexReader; import org.uct.cs.simplify.ply.reader.PLYReader; import org.uct.cs.simplify.ply.reader.Vertex; import org.uct.cs.simplify.splitter.SplittingAxis; import org.uct.cs.simplify.util.CompactBitArray; import org.uct.cs.simplify.util.XBoundingBox; import java.io.IOException; public class VariableKDTreeMembershipBuilder implements IMembershipBuilder { private static final double APPROXIMATION_THRESHOLD = 0.05; @Override public MembershipBuilderResult build(PLYReader reader, XBoundingBox boundingBox) throws IOException { try (MemoryMappedVertexReader vr = new MemoryMappedVertexReader(reader)) { SplittingAxis longest = SplittingAxis.getLongestAxis(boundingBox); double splitPoint = calculateMedianInRegion(vr, boundingBox, longest, APPROXIMATION_THRESHOLD); TIntObjectMap<XBoundingBox> subNodes = SplittingAxis.splitBBIntoSubnodes(boundingBox, longest, splitPoint); int c = vr.getCount(); CompactBitArray memberships = new CompactBitArray(1, c); switch (longest) { case X: for (int i = 0; i < c; i++) { if (vr.get(i).x > splitPoint) memberships.set(i, 1); } break; case Y: for (int i = 0; i < c; i++) { if (vr.get(i).y > splitPoint) memberships.set(i, 1); } break; case Z: for (int i = 0; i < c; i++) { if (vr.get(i).z > splitPoint) memberships.set(i, 1); } break; } return new MembershipBuilderResult(subNodes, memberships); } } private static double calculateMedianInRegion(MemoryMappedVertexReader vr, XBoundingBox bb, SplittingAxis axis, double approximationThreshold) { double min, max, approximate, ratio; switch (axis) { case X: min = bb.getMinX(); max = bb.getMaxX(); break; case Y: min = bb.getMinY(); max = bb.getMaxY(); break; default: min = bb.getMinZ(); max = bb.getMaxZ(); } float nv = vr.getCount(); approximate = (min + max) / 2; ratio = countValuesLessThan(vr, axis, approximate) / nv; double minR = 0.5 - approximationThreshold; double maxR = 0.5 + approximationThreshold; while (ratio < minR || ratio > maxR) { if (ratio > 0.5) { max = approximate; } else { min = approximate; } approximate = (min + max) / 2; ratio = countValuesLessThan(vr, axis, approximate) / nv; } return approximate; } private static int countValuesLessThan(MemoryMappedVertexReader vr, SplittingAxis axis, double value) { int c = vr.getCount(); int count = 0; for (int i = 0; i < c; i++) { if (getValueFromVertex(vr.get(i), axis) < value) count++; } return count; } private static double getValueFromVertex(Vertex v, SplittingAxis a) { if (a == SplittingAxis.X) return v.x; if (a == SplittingAxis.Y) return v.y; return v.z; } }
package com.psliusar.layers; import android.animation.Animator; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.psliusar.layers.binder.Binder; import com.psliusar.layers.binder.BinderHolder; import com.psliusar.layers.binder.ObjectBinder; public abstract class Layer<P extends Presenter> implements LayersHost, View.OnClickListener, BinderHolder { private static final String SAVED_STATE_CHILD_LAYERS = "LAYER.SAVED_STATE_CHILD_LAYERS"; private static final String SAVED_STATE_CUSTOM = "LAYER.SAVED_STATE_CUSTOM"; private LayersHost host; @Nullable private Layers layers; @Nullable private P presenter; View view; @Nullable private String name; @Nullable private Bundle arguments; boolean attached; private boolean fromSavedState; private boolean finishing; private ObjectBinder layerBinder; public Layer() { // Default constructor } public final P getPresenter() { if (presenter == null) { presenter = onCreatePresenter(); if (presenter != null) { //noinspection unchecked presenter.create(host, this); } } return presenter; } protected abstract P onCreatePresenter(); public boolean onBackPressed() { if (layers != null && layers.getStackSize() > 1) { final Layer<?> topLayer = layers.peek(); if (topLayer != null && topLayer.onBackPressed()) { return true; } } return false; } void create(@NonNull LayersHost host, @Nullable Bundle arguments, @Nullable String name, @Nullable Bundle savedState) { this.host = host; this.arguments = arguments; this.name = name; fromSavedState = savedState != null; if (savedState != null) { final Bundle layersState = savedState.getBundle(SAVED_STATE_CHILD_LAYERS); if (layersState != null) { layers = new Layers(this, layersState); } } onCreate(savedState == null ? null : savedState.getBundle(SAVED_STATE_CUSTOM)); } protected void onCreate(@Nullable Bundle savedState) { if (savedState != null) { Binder.restore(this, savedState); } } @Nullable protected abstract View onCreateView(@Nullable ViewGroup parent); protected void onBindView(@NonNull View view) { Binder.bind(this, view); final P p = getPresenter(); if (p != null) { p.onStart(); } } void restoreLayerState() { if (layers != null) { layers.restoreState(); } } void restoreViewState(@Nullable SparseArray<Parcelable> inState) { if (inState != null) { view.restoreHierarchyState(inState); } if (layers != null) { layers.resumeView(); } } /** * After attach */ protected void onAttach() { } /** * Before detach */ protected void onDetach() { } void saveViewState(@NonNull SparseArray<Parcelable> outState) { view.saveHierarchyState(outState); } void saveLayerState(@NonNull Bundle outState) { if (layers != null) { final Bundle layersState = layers.saveState(); if (layersState != null) { outState.putBundle(SAVED_STATE_CHILD_LAYERS, layersState); } } final Bundle customState = new Bundle(); onSaveLayerState(customState); if (customState.size() > 0) { outState.putBundle(SAVED_STATE_CUSTOM, customState); } } protected void onSaveLayerState(@NonNull Bundle outState) { Binder.save(this, outState); } void destroyView() { final P p = getPresenter(); if (p != null) { p.onStop(); } if (layers != null) { layers.destroy(); } onDestroyView(); Binder.unbind(this); } protected void onDestroyView() { } void destroy(boolean finish) { finishing = finish; onDestroy(); if (presenter != null) { presenter.destroy(); presenter = null; } } protected void onDestroy() { } public boolean isAttached() { return attached; } public boolean isViewInLayout() { return true; } public boolean isFromSavedState() { return fromSavedState; } public boolean isFinishing() { return finishing; } @Nullable public Bundle getArguments() { return arguments; } @Nullable public String getName() { return name; } @NonNull public Context getContext() { return host.getActivity().getApplicationContext(); } @NonNull public LayersHost getHost() { return host; } @NonNull protected LayoutInflater getLayoutInflater() { return host.getActivity().getLayoutInflater(); } @NonNull protected <V extends View> V inflate(@LayoutRes int layoutRes, @Nullable ViewGroup parent) { //noinspection unchecked return (V) getLayoutInflater().inflate(layoutRes, parent, false); } @Nullable public View getView() { return view; } @NonNull public <T extends View> T getView(@IdRes int id) { final T view = findView(id); if (view == null) { throw new IllegalArgumentException("Failed to find View with ID 0x" + Integer.toHexString(id)); } return view; } @Nullable public <T extends View> T findView(@IdRes int id) { if (view == null) { return null; } //noinspection unchecked return (T) view.findViewById(id); } @NonNull public ViewGroup getDefaultContainer() { return (ViewGroup) view; } @NonNull public Layers getLayers() { if (layers == null) { layers = new Layers(this, null); } return layers; } @NonNull @Override public Activity getActivity() { return host.getActivity(); } @Nullable public Layer<?> getParentLayer() { return (host instanceof Layer) ? (Layer) host : null; } @Nullable public <T> T getParent(@NonNull Class<T> parentClass) { final Layer<?> parent = getParentLayer(); if (parent == null) { final Activity activity = host.getActivity(); return parentClass.isInstance(activity) ? parentClass.cast(activity) : null; } else if (parentClass.isInstance(parent)) { return parentClass.cast(parent); } else { return parent.getParent(parentClass); } } protected void bindClickListener(@NonNull View.OnClickListener listener, View... views) { final int size = views.length; for (int i = 0; i < size; i++) { views[i].setOnClickListener(listener); } } protected void bindClickListener(@NonNull View.OnClickListener listener, @IdRes int... ids) { final int size = ids.length; for (int i = 0; i < size; i++) { getView(ids[i]).setOnClickListener(listener); } } @Override public void onClick(View v) { } @Nullable public Animator getAnimation(@AnimationType int animationType) { return null; } @Nullable public ObjectBinder getObjectBinder() { return layerBinder; } public void setObjectBinder(@NonNull ObjectBinder objectBinder) { layerBinder = objectBinder; } @Override public String toString() { return "Layer{" + "name='" + name + '\'' + ", arguments=" + arguments + ", attached=" + attached + ", fromSavedState=" + fromSavedState + ", finishing=" + finishing + '}'; } }
package com.infm.readit.essential; import android.util.Pair; import com.infm.readit.readable.Readable; import com.infm.readit.util.SettingsBundle; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TextParser implements Serializable { public static final String LOGTAG = "TextParser"; public static final Map<String, Integer> PRIORITIES; static{ Map<String, Integer> priorityMap = new HashMap<String, Integer>(); /** a b c d e f g h i j k l m n o p q r s t u v w x y z */ final String englishAlpha = "abcdefghijklmnoprstuvwxyz"; final int[] englishPriorities = {10, 4, 4, 4, 9, 12, 10, 12, 8, 10, 8, 6, 6, 5, 8, 6, 12, 5, 15, 12, 14, 12, 14, 13, 14, 12}; int i = 0; for (char c : englishAlpha.toCharArray()) priorityMap.put(Character.toString(c), englishPriorities[i++]); final String russianAlpha = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; final int[] russianPriorities = {10, 4, 4, 7, 4, 7, 14, 9, 9, 6, 7, 5, 4, 4, 4, 10, 8, 10, 12, 5, 9, 15, 14, 14, 13, 10, 10, 0, 10, 0, 10, 12, 11}; i = 0; for (char c : russianAlpha.toCharArray()) priorityMap.put(Character.toString(c), russianPriorities[i++]); final String uniqueUkrainianChars = "ґіїє"; final int[] ukrainianPriorities = {15, 14, 18, 12}; i = 0; for (char c : uniqueUkrainianChars.toCharArray()) priorityMap.put(Character.toString(c), ukrainianPriorities[i++]); PRIORITIES = Collections.unmodifiableMap(priorityMap); } public static final String makeMeSpecial = " " + "." + "!" + "?" + "-" + "—" + ":" + ";" + "," + '\"' + "(" + ")"; private Readable readable; private int lengthPreference; private List<Integer> delayCoefficients; /** * stackOverFlow guys told about it */ public TextParser(){} public TextParser(Readable readable){ this.readable = readable; lengthPreference = 13; //TODO:implement it optional } /** * Need it to get rid of Context, which isn't Serializable * * @param readable : Readable instance to process * @param settingsBundle : settingsBundle to get some settings. * @return TextParser instance */ public static TextParser newInstance(Readable readable, SettingsBundle settingsBundle){ TextParser textParser = new TextParser(readable); textParser.setDelayCoefficients(settingsBundle.getDelayCoefficients()); textParser.process(); return textParser; } public static String findLink(Pattern pattern, String text){ if (!text.isEmpty()){ Matcher matcher = pattern.matcher(text); if (matcher.find()) return matcher.group(); } return null; } /** * @return pattern to detect links in text */ public static Pattern compilePattern(){ return Pattern.compile( "\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" + "(\\w+:\\w+@)?(([-\\w]+\\.)+(com|org|net|gov" + "|mil|biz|info|mobi|name|aero|jobs|museum" + "|travel|edu|[a-z]{2}))(:[\\d]{1,5})?" + "(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?| "((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" + "(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" + "(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b" ); } /** * Read the object from Base64 string. * @param s : serialized TextParser instance * @return : decoded TextParser instance * @throws IOException * @throws ClassNotFoundException */ public static TextParser fromString(String s) throws IOException, ClassNotFoundException{ byte[] data = Base64Coder.decode(s); ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream(data)); TextParser o = (TextParser) ois.readObject(); ois.close(); return o; } /** * @return serialized instance */ @Override public String toString(){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(this); oos.close(); return new String(Base64Coder.encode(baos.toByteArray())); } catch (IOException e) { e.printStackTrace(); } return null; } public void process(){ normalize(readable); cutLongWords(readable); buildDelayList(readable); cleanFromHyphens(readable); buildEmphasis(readable); } public void setDelayCoefficients(List<Integer> delayCoefficients){ this.delayCoefficients = delayCoefficients; } public Readable getReadable(){ return readable; } public void setReadable(Readable readable){ this.readable = readable; } protected void normalize(Readable readable){ readable.setText( handleSpecialCases( insertSpacesAfterPunctuation( removeSpacesBeforePunctuation( clearFromRepetitions( readable.getText().replaceAll("\\s+", " ") ) ) ) ) ); } /* normalize() auxiliary methods */ protected String clearFromRepetitions(String text){ StringBuilder result = new StringBuilder(); int previousPosition = -1; for (Character ch : text.toCharArray()){ int position = makeMeSpecial.indexOf(ch); if (position > -1 && position != previousPosition){ previousPosition = position; result.append(ch); } else if (position < 0){ previousPosition = -1; result.append(ch); } } return result.toString(); } protected String removeSpacesBeforePunctuation(String text){ StringBuilder res = new StringBuilder(); String madeMeSpecial = makeMeSpecial.substring(1, 9) + ")"; for (Character ch : text.toCharArray()){ if (madeMeSpecial.indexOf(ch) > -1 && res.length() > 0 && " ".equals(res.substring(res.length() - 1))) res.deleteCharAt(res.length() - 1); res.append(ch); } return res.toString(); } protected String insertSpacesAfterPunctuation(String text){ StringBuilder res = new StringBuilder(); String madeMeSpecial = makeMeSpecial.substring(1, 9) + ")"; for (Character ch : text.toCharArray()){ res.append(ch); if (madeMeSpecial.indexOf(ch) > -1) res.append(" "); } return res.toString(); } protected String handleSpecialCases(String text){ return handleAbbreviations(text); //TODO: implement more cases } protected String handleAbbreviations(String text){ StringBuilder res = new StringBuilder(); for (int i = 0; i < text.length(); ++i){ if (i > 0 && text.charAt(i - 1) == '.'){ if (!(i + 2 < text.length() && text.charAt(i + 2) == '.')) res.append(text.charAt(i)); } else res.append(text.charAt(i)); } return res.toString(); } protected void cutLongWords(Readable readable){ String text = readable.getText(); List<String> res = new ArrayList<String>(); for (String word : text.split(" ")){ boolean isComplex = false; while (word.length() - 1 > lengthPreference){ isComplex = true; String toAppend; int pos = word.length() - 3; while (pos > 1 && !Character.isLetter(word.charAt(pos))) --pos; toAppend = word.substring(0, pos); word = word.substring(pos); res.add("-" + toAppend + "-"); } if (isComplex) res.add("-" + word); else res.add(word); } StringBuilder sb = new StringBuilder(); for (String s : res) sb.append(s).append(" "); readable.setText(sb.toString()); } protected void cleanFromHyphens(Readable readable){ List<String> words = new ArrayList<String>(Arrays.asList(readable.getText().split(" "))); List<String> res = new ArrayList<String>(); for (String word : words) if (word.length() == 0) continue; else if (word.charAt(0) == '-') res.add(word.substring(1, word.length())); else res.add(word); readable.setWordList(res); } protected int measureWord(String word){ if (word.length() == 0) return delayCoefficients.get(0); int res = 0; for (char ch : word.toCharArray()){ int tempRes = delayCoefficients.get(0); if (ch == '-') tempRes = delayCoefficients.get(1); if (ch == '\t') tempRes = delayCoefficients.get(4); switch (ch){ case ',': tempRes = delayCoefficients.get(1); break; case '.': tempRes = delayCoefficients.get(2); break; case '!': tempRes = delayCoefficients.get(2); break; case '?': tempRes = delayCoefficients.get(2); break; case '-': tempRes = delayCoefficients.get(3); break; case '—': tempRes = delayCoefficients.get(3); break; case ':': tempRes = delayCoefficients.get(3); break; case ';': tempRes = delayCoefficients.get(3); break; case '\n': tempRes = delayCoefficients.get(4); } res = Math.max(res, tempRes); } return res; } protected void buildDelayList(Readable readable){ String text = readable.getText(); List<Integer> res = new ArrayList<Integer>(); String[] words = text.split(" "); for (String word : words) res.add(measureWord(word)); readable.setDelayList(res); } protected void buildEmphasis(Readable readable){ List<String> words = readable.getWordList(); List<Integer> res = new ArrayList<Integer>(); for (String word : words){ /* some kind of experiment, huh? */ Map<String, Pair<Integer, Integer>> priorities = new HashMap<String, Pair<Integer, Integer>>(); int len = word.length(); for (int i = 0; i < len; ++i){ if (!Character.isLetter(word.charAt(i))) continue; String ch = word.substring(i, i + 1).toLowerCase(); if (PRIORITIES.get(ch) != null && (priorities.get(ch) == null || priorities.get(ch).first < PRIORITIES.get(ch) * 100 / Math.max(1, Math.abs(len / 2 - i)))){ priorities.put(ch, new Pair<Integer, Integer>(PRIORITIES.get(ch) * 100 / Math.max(1, Math.abs(len / 2 - i)), i) ); } else priorities.put(ch, new Pair<Integer, Integer>(0, i)); if (i + 1 < word.length() && word.charAt(i) == word.charAt(i + 1)){ priorities.put(ch, new Pair<Integer, Integer>(priorities.get(ch).first * 4, i)); } } int resInd = word.length() / 2, mmax = 0; for (Map.Entry<String, Pair<Integer, Integer>> entry : priorities.entrySet()){ if (mmax < entry.getValue().first){ mmax = entry.getValue().first; resInd = entry.getValue().second; } } res.add(resInd); } readable.setEmphasisList(res); } }
package grammar; import java.io.IOException; import java.util.*; import helper.SyntaxHelper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import token.*; public class Grammar { // Logger private Logger l = LogManager.getFormatterLogger(getClass()); // Variables private Map<String, List<List<AbstractSyntaxToken>>> productions; private Map<String, Set<String>> firstSetMap, followSetMap; private String start; private Set<String> terminals; /** * Create grammar from file * @param file */ public Grammar(String file) { try { // Init variables productions = new LinkedHashMap<>(); firstSetMap = new HashMap<>(); followSetMap = new HashMap<>(); terminals = new HashSet<>(); start = null; // Add EOS to terminal terminals.add(SyntaxHelper.END_OF_STACK); // Parse file parse(file); // Computer first computeFirst(); l.info("First sets: %s", firstSetMap.toString()); // Computer follow computeFollow(); l.info("Follow sets: %s", followSetMap.toString()); } catch (IOException e) { l.error(e.getMessage()); } } /** * Get terminals * @return set of terminals */ public Set<String> getTerminals() { return terminals; } /** * Get non terminals * @return set of non-terminals */ public Set<String> getNonTerminals() { return productions.keySet(); } /** * Get productions * @return productions map */ public Map<String, List<List<AbstractSyntaxToken>>> getProductions() { return this.productions; } /** * Get first set map * @return first set map */ public Map<String, Set<String>> getFirstSetMap() { return this.firstSetMap; } /** * Get follow set map * @return follow set map */ public Map<String, Set<String>> getFollowSetMap() { return this.followSetMap; } /** * Compute the First set of all Non-Terminals */ private void computeFirst() { // Rules iterator Iterator<Map.Entry<String, List<List<AbstractSyntaxToken>>>> it = productions.entrySet().iterator(); // While more rules while (it.hasNext()) { computeFirst(SyntaxTokenFactory.createNonTerminalToken(it.next().getKey())); } } /** * Compute the first set of a non terminal recursively * @param token * @return first set of a non-terminal */ private Set<String> computeFirst(AbstractSyntaxToken token) { // Optimize if(token instanceof NonTerminalToken && firstSetMap.containsKey(token.getValue())) return firstSetMap.get(token.getValue()); // Prepare set Set<String> firstSet = new HashSet<>(); firstSetMap.put(token.getValue(), firstSet); // Get RHS List<List<AbstractSyntaxToken>> RHS = productions.get(token.getValue()); // Loop on all productions for(List<AbstractSyntaxToken> production : RHS) { // Loop on production tokens for(AbstractSyntaxToken syntaxToken : production) { // If terminal or epsilon if(syntaxToken instanceof TerminalToken || syntaxToken instanceof EpsilonToken) { firstSet.add(syntaxToken.getValue()); break; } else if(syntaxToken instanceof NonTerminalToken) { // Get first of token Set<String> syntaxTokenFirstSet = computeFirst(syntaxToken); // If doesn't have epsilon, or last token in the production if(!syntaxTokenFirstSet.contains(SyntaxHelper.EPSILON) || syntaxToken == production.get(production.size()-1)) { // Superset firstSet.addAll(syntaxTokenFirstSet); // Don't try next token break; } else { // Superset minus epsilon for(String str : syntaxTokenFirstSet) { if (!str.equals(SyntaxHelper.EPSILON)) { firstSet.add(str); } } } } } } // Get first set return firstSet; } /** * Compute the Follow set of all Non-Terminals */ private void computeFollow() { // Loop on non terminals and init empty sets for(String nonTerminal : productions.keySet()) { followSetMap.put(nonTerminal, new HashSet<>()); } // Add EOS to follow set of start token followSetMap.get(start).add(SyntaxHelper.END_OF_STACK); // Repeat the computation multiple times for (int repeatX = 0; repeatX < productions.size(); ++repeatX) { // Rules iterator Iterator<Map.Entry<String, List<List<AbstractSyntaxToken>>>> it = productions.entrySet().iterator(); // While more productions while (it.hasNext()) { // Store current pair Map.Entry<String, List<List<AbstractSyntaxToken>>> current = it.next(); // Loop on productions for the same key for(List<AbstractSyntaxToken> production : current.getValue()) { // Loop on production syntax tokens for(int i = 0; i < production.size(); ++i) { // Current AbstractSyntaxToken syntaxToken = production.get(i); // If non terminal if(syntaxToken instanceof NonTerminalToken) { // While more tokens int j = i; while(++j < production.size()) { // Get next token AbstractSyntaxToken nextToken = production.get(j); // Get the first set Set<String> firstSet = getFirstSetOf(nextToken); // If first set is defined if(firstSet != null) { // Copy into follow set for (String str : firstSet) { if (!str.equals(SyntaxHelper.EPSILON)) { followSetMap.get(syntaxToken.getValue()).add(str); } } // If first set doesn't contain epsilon stop if (!firstSet.contains(SyntaxHelper.EPSILON)) break; } } // If no more next tokens and ended with epsilon if(j == production.size()) { // Include follow set of LHS into target followSetMap.get(syntaxToken.getValue()).addAll(followSetMap.get(current.getKey())); } } } } } } } /** * Get first set of a token * @param syntaxToken * @return first set */ public Set<String> getFirstSetOf(AbstractSyntaxToken syntaxToken) { if(syntaxToken instanceof TerminalToken) { Set<String> firstSet = new HashSet<>(); firstSet.add(syntaxToken.getValue()); return firstSet; } if(syntaxToken instanceof NonTerminalToken) { return firstSetMap.get(syntaxToken.getValue()); } return null; } /** * Get follow set of a non terminal * @param syntaxToken * @return follow set of a non terminal */ public Set<String> getFollowSetOf(AbstractSyntaxToken syntaxToken) { if(syntaxToken instanceof NonTerminalToken) { return this.followSetMap.get(syntaxToken.getValue()); } return null; } /** * Get starting non terminal * @return starting non terminal */ public String getStart() { return this.start; } /** * Parse grammar file * @param file * @throws IOException */ private void parse(String file) throws IOException { // Scan file Scanner scanGrammar = new Scanner(this.getClass().getResource(file).openStream()); // LHS String LHS = null; // While more lines to scan while(scanGrammar.hasNext()) { // Scan line String line = scanGrammar.nextLine(); // Scan line Scanner scanLine = new Scanner(line); // Production List<AbstractSyntaxToken> production = new ArrayList<>(); // If line is not empty if(scanLine.hasNext()) { // First String first = scanLine.next(); if(first.equals("|")) { // Nothing } else if(first.startsWith("%")) { // Skip line because it's a comment continue; } else { // Update LHS LHS = first; // Start if(start == null) start = LHS; // If first time create list productions.putIfAbsent(LHS, new LinkedList<>()); // If next string is not -> String insteadValue; if(!(insteadValue = scanLine.next()).equals("->")){ scanLine.close(); throw new IOException("Wrong file format! Expecting -> instead of " + insteadValue); } } } // While more words while(scanLine.hasNext()) { // Current word String current = scanLine.next(); if(current.equals("|")) { // Add to rule productions.get(LHS).add(production); // Create new array production = new ArrayList<>(); } else { AbstractSyntaxToken token; if(current.equals(SyntaxHelper.EPSILON)) { token = SyntaxTokenFactory.createEpsilonToken(); } else if(current.equals(SyntaxHelper.END_OF_STACK)) { token = SyntaxTokenFactory.createEndOfStackToken(); } else if(current.charAt(0) == '\'' && current.charAt(current.length()-1) == '\'') { token = SyntaxTokenFactory.createTerminalToken(current); terminals.add(token.getValue()); } else if(current.charAt(0) == '#' && current.charAt(current.length()-1) == '#') { token = SyntaxTokenFactory.createActionToken(current); } else { token = SyntaxTokenFactory.createNonTerminalToken(current); } production.add(token); } } // Close scanner scanLine.close(); // Add to rule if(LHS != null && production.size() > 0) productions.get(LHS).add(production); } // Close grammar scanner scanGrammar.close(); } }
package com.dumbster.smtp; import com.dumbster.smtp.action.*; import org.junit.*; import java.util.Iterator; import com.dumbster.smtp.MailMessage; import com.dumbster.smtp.mailstores.EMLMailStore; import com.dumbster.smtp.mailstores.RollingMailStore; import com.dumbster.smtp.Response; import static org.junit.Assert.*; public class NewTestCasesTest { private MailMessage message; private ServerOptions options; @Before public void setup() { this.message = new MailMessageImpl(); } /* Message Formatting Utests */ @Test public void testMaxHeaders() { message.addHeader("header1", "value1"); message.addHeader("header2", "value2"); message.addHeader("header3", "value3"); message.addHeader("header4", "value4"); message.addHeader("header5", "value5"); message.addHeader("header6", "value6"); message.addHeader("header7", "value7"); message.addHeader("header8", "value8"); message.addHeader("header9", "value9"); message.addHeader("header10", "value10"); Iterator<String> it = message.getHeaderNames(); int i = 0; while(it.hasNext()) { i++; it.next(); } assertEquals(10, i); } @Test public void testMaxHeadersPlus1() { message.addHeader("header1", "value1"); message.addHeader("header2", "value2"); message.addHeader("header3", "value3"); message.addHeader("header4", "value4"); message.addHeader("header5", "value5"); message.addHeader("header6", "value6"); message.addHeader("header7", "value7"); message.addHeader("header8", "value8"); message.addHeader("header9", "value9"); message.addHeader("header10", "value10"); message.addHeader("header11", "value11"); Iterator<String> it = message.getHeaderNames(); int i = 0; while(it.hasNext()) { i++; it.next(); } assertEquals(11, i); } /* Server Options Utests */ @Test public void testNegativePort() { String[] args = new String[]{"-1"}; options = new ServerOptions(args); assertEquals(-1, options.port); assertEquals(true, options.threaded); assertEquals(true, options.valid); assertEquals(RollingMailStore.class, options.mailStore.getClass()); } /* Request Utests*/ @Test public void testDataBodyState() { Request request = Request.createRequest(SmtpState.DATA_BODY, "."); assertEquals(".", request.getClientAction().toString()); } @Test public void testDataFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "DATA"); assertEquals("DATA", request.getClientAction().toString()); } @Test public void testQuitFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "QUIT"); assertEquals("QUIT", request.getClientAction().toString()); } @Test public void testHeloInvalidMessage() { Request request = Request.createRequest(null, "HELO"); assertEquals("EHLO", request.getClientAction().toString()); } // This test increases branch coverage @Test public void testListFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "LIST"); assertEquals("LIST", request.getClientAction().toString()); } /* Action Tests */ // This test increases branch coverage @Test public void testListIndexNegative() { List l = new List("-1"); //This Test passes if there is no exception //messageIndex is private, no public method to check its value } @Test public void testListIndexNegative() { List l = new List("-1"); Response r = l.response(null, null, null); assertEquals("There are 0 message(s).", r.message); } }
package com.dumbster.smtp; import com.dumbster.smtp.SmtpServer; import com.dumbster.smtp.action.*; import com.dumbster.smtp.eml.*; import org.junit.*; import java.util.Iterator; import com.dumbster.smtp.MailMessage; import com.dumbster.smtp.mailstores.EMLMailStore; import com.dumbster.smtp.mailstores.RollingMailStore; import com.dumbster.smtp.Response; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; import java.util.Date; import java.io.IOException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Random; import static org.junit.Assert.*; public class NewTestCasesTest { private static final int SMTP_PORT = 1081; private final String SERVER = "localhost"; private final String FROM = "sender@here.com"; private final String TO = "baker32@illinois.edu"; private final String SUBJECT = "Test Dumbster"; private final String BODY = "Test Body"; private final int WAIT_TICKS = 10000; private final String text = "From: \"John\" <baker32@illinois.edu>\n" + "To: \"PeterShmenos\" <petershmenos@gmail.com>\n" + "Date: Fri, 8 May 2015 12:16:43 -0500\n" + "Subject: Test\n" + "\n" + "Hello Peter,\n" + "This is only a test.\n" + "Sincerely,\n" + "Baker\n"; private MailMessage message; private EMLMailMessage emlMessage; private ServerOptions options; private MailStore mailStore; private MailStore mailStore2; private EMLMailStore emlMailStore; private SmtpServer server; @Before public void setup() { this.message = new MailMessageImpl(); mailStore = new RollingMailStore(); } /* Message Formatting Utests */ @Test public void testMaxHeaders() { message.addHeader("header1", "value1"); message.addHeader("header2", "value2"); message.addHeader("header3", "value3"); message.addHeader("header4", "value4"); message.addHeader("header5", "value5"); message.addHeader("header6", "value6"); message.addHeader("header7", "value7"); message.addHeader("header8", "value8"); message.addHeader("header9", "value9"); message.addHeader("header10", "value10"); Iterator<String> it = message.getHeaderNames(); int i = 0; while(it.hasNext()) { i++; it.next(); } assertEquals(10, i); } @Test public void testMaxHeadersPlus1() { message.addHeader("header1", "value1"); message.addHeader("header2", "value2"); message.addHeader("header3", "value3"); message.addHeader("header4", "value4"); message.addHeader("header5", "value5"); message.addHeader("header6", "value6"); message.addHeader("header7", "value7"); message.addHeader("header8", "value8"); message.addHeader("header9", "value9"); message.addHeader("header10", "value10"); message.addHeader("header11", "value11"); Iterator<String> it = message.getHeaderNames(); int i = 0; while(it.hasNext()) { i++; it.next(); } assertEquals(11, i); } @Test public void testAppendBadHeader() { message.addHeader("foo", "bar"); message.addHeader("tim", "tam"); message.addHeader("zing", "zang"); message.appendHeader("tim", " tum"); assertEquals("tam tum", message.getFirstHeaderValue("tim")); } /* Server Options Utests */ @Test public void testNegativePort() { String[] args = new String[]{"-1"}; options = new ServerOptions(args); assertEquals(-1, options.port); assertEquals(true, options.threaded); assertEquals(true, options.valid); assertEquals(RollingMailStore.class, options.mailStore.getClass()); } /* Request Utests*/ @Test public void testDataBodyState() { Request request = Request.createRequest(SmtpState.DATA_BODY, "."); assertEquals(".", request.getClientAction().toString()); } @Test public void testDataFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "DATA"); assertEquals("DATA", request.getClientAction().toString()); } @Test public void testQuitFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "QUIT"); assertEquals("QUIT", request.getClientAction().toString()); } @Test public void testHeloInvalidMessage() { Request request = Request.createRequest(null, "HELO"); assertEquals("EHLO", request.getClientAction().toString()); } // This test increases branch coverage @Test public void testListFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "LIST"); assertEquals("LIST", request.getClientAction().toString()); } /* Action Tests */ // This test increases branch coverage @Test public void testListIndexNegative() { List l = new List("-1"); //This Test passes if there is no exception //messageIndex is private, no public method to check its value } //These two tests increase coverage @Test public void testResponseInvalidIndex() { List l = new List("-1"); Response r = l.response(null, mailStore, null); assertEquals("There are 0 message(s).", r.getMessage()); } @Test public void testResponseValidNoMessages() { List l = new List("0"); Response r = l.response(null, mailStore, null); assertEquals("There are 0 message(s).", r.getMessage()); } /* SMTP Server Tests */ //This test increases coverage @Test public void getMessageTest() { MailMessage[] mm = new MailMessage[10]; ServerOptions options = new ServerOptions(); options.port = SMTP_PORT; server = SmtpServerFactory.startServer(options); server.getMessages(); assertEquals(0, server.getEmailCount()); server.stop(); } /* Advanced Test Cases */ @Test public void testUniqueMessagesWithClear() { ServerOptions options = new ServerOptions(); options.port = SMTP_PORT; server = SmtpServerFactory.startServer(options); // Message 1 sendMessage(SMTP_PORT, FROM, SUBJECT, BODY, TO); server.anticipateMessageCountFor(1, WAIT_TICKS); assertTrue(server.getEmailCount() == 1); MailMessage mm = server.getMessage(0); assertEquals("Test Dumbster", mm.getFirstHeaderValue("Subject")); // Message 2 sendMessage(SMTP_PORT, FROM, SUBJECT, "HELLO!", TO); server.anticipateMessageCountFor(1, WAIT_TICKS); assertTrue(server.getEmailCount() == 2); mm = server.getMessage(1); assertEquals("HELLO!", mm.getBody()); // Messages 3-10 int i; for (i = 3; i <= 10; i++) { sendMessage(SMTP_PORT, FROM, null, Integer.toString(i), TO); assertTrue(server.getEmailCount() == i); } server.clearMessages(); sendMessage(SMTP_PORT, FROM, SUBJECT, BODY, TO); assertTrue(server.getEmailCount() == 1); server.stop(); } @Test public void testUniqueMessagesMultipleMailStores() { ServerOptions options = new ServerOptions(); options.port = SMTP_PORT; server = SmtpServerFactory.startServer(options); mailStore2 = new RollingMailStore(); // First rolling Mail Store Message MailMessage fm = new MailMessageImpl(); mailStore2.addMessage(fm); // Messages 1-10 int i; for (i = 1; i <= 10; i++) { sendMessage(SMTP_PORT, FROM, null, Integer.toString(i), TO); addAMessage(); assertTrue(server.getEmailCount() == i); } server.clearMessages(); sendMessage(SMTP_PORT, FROM, SUBJECT, BODY, TO); assertTrue(server.getEmailCount() == 1); server.stop(); } /* Final Report Tests */ /* Increase Method Coverage */ @Test public void startServerNoInputs() { try { server = SmtpServerFactory.startServer(); server.getMessages(); assertEquals(0, server.getEmailCount()); } catch (Exception e) {} } @Test public void startServerThrowException() { ServerOptions options = new ServerOptions(); options.port = SMTP_PORT; server = SmtpServerFactory.startServer(options); try { throw new IOException(); } catch(Exception e) {} } @Test public void appendHeaderEMLmessage(){ emlMessage = new EMLMailMessage(new ByteArrayInputStream(text.getBytes())); emlMessage.appendHeader("From", " Baker"); assertEquals(" Baker", emlMessage.getFirstHeaderValue("From")); } @Test public void emlMessageFileNotFound(){ File f = new File("X:\\doesNotExist.txt"); try { emlMessage = new EMLMailMessage(f); } catch(RuntimeException e) { return; } assertEquals(1,2); } @Test public void emlMailStoreSetDirectory() { emlMailStore = new EMLMailStore(); String emlStoreDir = "build/test/eml_store_test" + String.valueOf(new Random().nextInt(1000000)); emlMailStore.setDirectory(emlStoreDir); assertTrue(true); } @Test public void emlMailStoreAddMessageNoDirectory() { emlMailStore = new EMLMailStore(); File f = null; emlMailStore.setDirectory(f); try { emlMailStore.addMessage(message); } catch (Exception e) { return; } assertEquals(1,2); } /* Helpers */ private Properties getMailProperties(int port) { Properties mailProps = new Properties(); mailProps.setProperty("mail.smtp.host", "localhost"); mailProps.setProperty("mail.smtp.port", "" + port); mailProps.setProperty("mail.smtp.sendpartial", "true"); return mailProps; } private void sendMessage(int port, String from, String subject, String body, String to) { try { Properties mailProps = getMailProperties(port); Session session = Session.getInstance(mailProps, null); MimeMessage msg = createMessage(session, from, to, subject, body); Transport.send(msg); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception: " + e); } } private MimeMessage createMessage(Session session, String from, String to, String subject, String body) throws MessagingException { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(body); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); return msg; } private void addAMessage() { MailMessage message = new MailMessageImpl(); mailStore2.addMessage(message); } }
package VASSAL.counters; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Component; import java.awt.Composite; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.util.Arrays; import java.util.List; import java.util.Objects; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.build.module.map.boardPicker.board.GeometricGrid; import VASSAL.build.module.map.boardPicker.board.MapGrid; import VASSAL.command.ChangeTracker; import VASSAL.command.Command; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.ChooseComponentDialog; import VASSAL.configure.ColorConfigurer; import VASSAL.configure.IntConfigurer; import VASSAL.configure.NamedHotKeyConfigurer; import VASSAL.configure.StringConfigurer; import VASSAL.i18n.PieceI18nData; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslatablePiece; import VASSAL.tools.NamedKeyStroke; import VASSAL.tools.SequenceEncoder; import net.miginfocom.swing.MigLayout; /** * @author Scott Giese sgiese@sprintmail.com * * Displays a transparency surrounding the GamePiece which represents the Area of Effect of the GamePiece */ public class AreaOfEffect extends Decorator implements TranslatablePiece, MapShader.ShadedPiece { public static final String ID = "AreaOfEffect;"; // NON-NLS protected static final Color defaultTransparencyColor = Color.GRAY; protected static final float defaultTransparencyLevel = 0.3F; protected static final int defaultRadius = 1; protected Color transparencyColor; protected float transparencyLevel; protected int radius; protected boolean alwaysActive; protected boolean active; protected String activateCommand = ""; protected NamedKeyStroke activateKey; protected KeyCommand[] commands; protected String mapShaderName; protected MapShader shader; protected KeyCommand keyCommand; protected boolean fixedRadius = true; protected String radiusMarker = ""; protected String description = ""; public AreaOfEffect() { this(ID + ColorConfigurer.colorToString(defaultTransparencyColor), null); } public AreaOfEffect(String type, GamePiece inner) { mySetType(type); setInner(inner); } @Override public String getDescription() { return buildDescription("Editor.AreaOfEffect.trait_description", description); } @Override public String getBaseDescription() { return Resources.getString("Editor.AreaOfEffect.trait_description"); } @Override public String getDescriptionField() { return description; } @Override public String myGetType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(transparencyColor); se.append((int) (transparencyLevel * 100)); se.append(radius); se.append(alwaysActive); se.append(activateCommand); se.append(activateKey); se.append(mapShaderName == null ? "" : mapShaderName); se.append(fixedRadius); se.append(radiusMarker); se.append(description); return ID + se.getValue(); } @Override public void mySetType(String type) { final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';'); st.nextToken(); // Discard ID transparencyColor = st.nextColor(defaultTransparencyColor); transparencyLevel = st.nextInt((int) (defaultTransparencyLevel * 100)) / 100.0F; radius = st.nextInt(defaultRadius); alwaysActive = st.nextBoolean(true); activateCommand = st.nextToken(Resources.getString("Editor.AreaOfEffect.show_area")); activateKey = st.nextNamedKeyStroke(null); keyCommand = new KeyCommand(activateCommand, activateKey, Decorator.getOutermost(this), this); mapShaderName = st.nextToken(""); if (mapShaderName.length() == 0) { mapShaderName = null; } fixedRadius = st.nextBoolean(true); radiusMarker = st.nextToken(""); description = st.nextToken(""); shader = null; commands = null; } // State does not change during the game @Override public String myGetState() { return alwaysActive ? "false" : String.valueOf(active); // NON-NLS } // State does not change during the game @Override public void mySetState(String newState) { if (!alwaysActive) { active = "true".equals(newState); // NON-NLS } } @Override public Rectangle boundingBox() { final Rectangle r = piece.boundingBox(); final Area a = getArea(); if (a != null) { final Rectangle aoeBounds = getArea().getBounds(); final Point mapPosition = getPosition(); aoeBounds.translate(-mapPosition.x, -mapPosition.y); r.add(aoeBounds); } return r; } @Override public Shape getShape() { return piece.getShape(); } @Override public String getName() { return piece.getName(); } /** * @return a list of any Named KeyStrokes referenced in the Decorator, if any (for search) */ @Override public List<NamedKeyStroke> getNamedKeyStrokeList() { return Arrays.asList(activateKey); } /** * @return a list of any Menu Text strings referenced in the Decorator, if any (for search) */ @Override public List<String> getMenuTextList() { return List.of(activateCommand); } @Override public void draw(Graphics g, int x, int y, Component obs, double zoom) { if ((alwaysActive || active) && mapShaderName == null) { // The transparency is only drawn on a Map.View component. Only the // GamePiece is drawn within other windows (Counter Palette, etc.). if (obs instanceof Map.View && getMap() != null) { Area a = getArea(); if (a != null) { final Graphics2D g2d = (Graphics2D) g; final Color oldColor = g2d.getColor(); g2d.setColor(transparencyColor); final Composite oldComposite = g2d.getComposite(); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparencyLevel)); if (zoom != 1.0) { a = new Area(AffineTransform.getScaleInstance(zoom, zoom).createTransformedShape(a)); } g2d.fill(a); g2d.setColor(oldColor); g2d.setComposite(oldComposite); } } } // Draw the GamePiece piece.draw(g, x, y, obs, zoom); } protected Area getArea() { final Map map = getMap(); if (map == null) { return null; } // Always draw the area centered on the piece's current position // (For instance, don't draw it at an offset if it's in an expanded stack) final Point mapPosition = getPosition(); final int myRadius = getRadius(); final Board board = map.findBoard(mapPosition); final MapGrid grid = board == null ? null : board.getGrid(); Area a; if (grid instanceof GeometricGrid) { final GeometricGrid gGrid = (GeometricGrid) grid; final Rectangle boardBounds = board.bounds(); final Point boardPosition = new Point( mapPosition.x - boardBounds.x, mapPosition.y - boardBounds.y); a = gGrid.getGridShape(boardPosition, myRadius); // In board co-ords final AffineTransform t = AffineTransform.getTranslateInstance( boardBounds.x, boardBounds.y); // Translate back to map co-ords final double mag = board.getMagnification(); if (mag != 1.0) { t.translate(boardPosition.x, boardPosition.y); t.scale(mag, mag); t.translate(-boardPosition.x, -boardPosition.y); } a = a.createTransformedArea(t); } else { a = new Area( new Ellipse2D.Double(mapPosition.x - myRadius, mapPosition.y - myRadius, myRadius * 2, myRadius * 2)); } return a; } protected int getRadius() { if (fixedRadius) { return radius; } else { final String r = (String) Decorator.getOutermost(this).getProperty(radiusMarker); try { return Integer.parseInt(r); } catch (NumberFormatException e) { reportDataError(this, Resources.getString("Error.non_number_error"), "radius[" + radiusMarker + "]=" + r, e); // NON-NLS return 0; } } } // No hot-keys @Override protected KeyCommand[] myGetKeyCommands() { if (commands == null) { if (alwaysActive || activateCommand.length() == 0) { commands = KeyCommand.NONE; } else { commands = new KeyCommand[]{keyCommand}; } } return commands; } // No hot-keys @Override public Command myKeyEvent(KeyStroke stroke) { Command c = null; myGetKeyCommands(); if (!alwaysActive && keyCommand.matches(stroke)) { final ChangeTracker t = new ChangeTracker(this); active = !active; c = t.getChangeCommand(); } return c; } @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("AreaOfEffect.html"); // NON-NLS } @Override public PieceEditor getEditor() { return new TraitEditor(this); } @Override public Area getArea(MapShader shader) { Area a = null; final MapShader.ShadedPiece shaded = (MapShader.ShadedPiece) Decorator.getDecorator(piece, MapShader.ShadedPiece.class); if (shaded != null) { a = shaded.getArea(shader); } if (alwaysActive || active) { if (shader.getConfigureName().equals(mapShaderName)) { final Area myArea = getArea(); if (a == null) { a = myArea; } else { a.add(myArea); } } } return a; } @Override public boolean testEquals(Object o) { if (! (o instanceof AreaOfEffect)) return false; final AreaOfEffect c = (AreaOfEffect) o; if (! Objects.equals(transparencyColor, c.transparencyColor)) return false; if (! Objects.equals(transparencyLevel, c.transparencyLevel)) return false; if (! Objects.equals(radius, c.radius)) return false; if (! Objects.equals(alwaysActive, c.alwaysActive)) return false; if (! Objects.equals(activateCommand, c.activateCommand)) return false; if (! Objects.equals(activateKey, c.activateKey)) return false; if (! Objects.equals(mapShaderName, c.mapShaderName)) return false; if (! Objects.equals(fixedRadius, c.fixedRadius)) return false; if (! Objects.equals(radiusMarker, c.radiusMarker)) return false; if (alwaysActive) { if (!Objects.equals(active, c.active)) return false; } return Objects.equals(description, c.description); } protected static class TraitEditor implements PieceEditor { protected TraitConfigPanel panel; protected final JLabel transparencyColorLabel; protected ColorConfigurer transparencyColorValue; protected final JLabel transparencyLabel; protected IntConfigurer transparencyValue; protected IntConfigurer radiusValue; protected JLabel radiusValueLabel; protected BooleanConfigurer alwaysActive; protected StringConfigurer activateCommand; protected JLabel activateCommandLabel; protected NamedHotKeyConfigurer activateKey; protected JLabel activateKeyLabel; protected BooleanConfigurer useMapShader; protected BooleanConfigurer fixedRadius; protected StringConfigurer radiusMarker; protected JLabel radiusMarkerLabel; protected StringConfigurer descConfig; protected JLabel selectShaderLabel; protected JPanel selectShader; protected String mapShaderId; protected TraitEditor(AreaOfEffect trait) { panel = new TraitConfigPanel(); descConfig = new StringConfigurer(trait.description); descConfig.setHintKey("Editor.description_hint"); panel.add("Editor.description_label", descConfig); useMapShader = new BooleanConfigurer(trait.mapShaderName != null); panel.add("Editor.AreaOfEffect.use_map_shading", useMapShader); mapShaderId = trait.mapShaderName; selectShader = new JPanel(new MigLayout("ins 0", "[fill, grow]0[]")); // NON-NLS final JTextField tf = new JTextField(); tf.setEditable(false); selectShader.add(tf, "growx"); // NON-NLS tf.setText(trait.mapShaderName); final JButton b = new JButton(Resources.getString("Editor.AreaOfEffect.select")); selectShader.add(b); b.addActionListener(e -> { final ChooseComponentDialog d = new ChooseComponentDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, panel), MapShader.class); d.setVisible(true); if (d.getTarget() != null) { mapShaderId = d.getTarget().getConfigureName(); tf.setText(mapShaderId); } else { mapShaderId = null; tf.setText(""); } }); selectShaderLabel = new JLabel(Resources.getString("Editor.AreaOfEffect.map_shading")); panel.add(selectShaderLabel, selectShader); transparencyColorLabel = new JLabel(Resources.getString("Editor.AreaOfEffect.fill_color")); transparencyColorValue = new ColorConfigurer(trait.transparencyColor); panel.add(transparencyColorLabel, transparencyColorValue); transparencyLabel = new JLabel(Resources.getString("Editor.AreaOfEffect.opacity")); transparencyValue = new IntConfigurer((int) (trait.transparencyLevel * 100)); transparencyValue.setHint("0-100"); panel.add(transparencyLabel, transparencyValue); fixedRadius = new BooleanConfigurer(Boolean.valueOf(trait.fixedRadius)); fixedRadius.addPropertyChangeListener(evt -> updateRangeVisibility()); panel.add("Editor.AreaOfEffect.fixed_radius", fixedRadius); radiusValueLabel = new JLabel(Resources.getString("Editor.AreaOfEffect.radius")); radiusValue = new IntConfigurer(trait.radius); panel.add(radiusValueLabel, radiusValue); radiusMarkerLabel = new JLabel(Resources.getString("Editor.AreaOfEffect.radius_marker")); radiusMarker = new StringConfigurer(trait.radiusMarker); panel.add(radiusMarkerLabel, radiusMarker); alwaysActive = new BooleanConfigurer(trait.alwaysActive ? Boolean.TRUE : Boolean.FALSE); activateCommand = new StringConfigurer(trait.activateCommand); activateCommandLabel = new JLabel(Resources.getString("Editor.AreaOfEffect.toggle_visible_command")); activateKey = new NamedHotKeyConfigurer(trait.activateKey); activateKeyLabel = new JLabel(Resources.getString("Editor.AreaOfEffect.toggle_visible_keyboard_shortcut")); updateRangeVisibility(); alwaysActive.addPropertyChangeListener(evt -> updateCommandVisibility()); updateCommandVisibility(); useMapShader.addPropertyChangeListener(evt -> updateFillVisibility()); updateFillVisibility(); panel.add("Editor.AreaOfEffect.always_visible", alwaysActive); panel.add(activateCommandLabel, activateCommand); panel.add(activateKeyLabel, activateKey); } protected void updateFillVisibility() { final boolean useShader = Boolean.TRUE.equals(useMapShader.getValue()); transparencyColorLabel.setVisible(!useShader); transparencyColorValue.getControls().setVisible(!useShader); transparencyLabel.setVisible(!useShader); transparencyValue.getControls().setVisible(!useShader); selectShader.setVisible(useShader); selectShaderLabel.setVisible(useShader); repack(); } protected void updateRangeVisibility() { final boolean fixedRange = fixedRadius.booleanValue(); radiusValue.getControls().setVisible(fixedRange); radiusMarker.getControls().setVisible(!fixedRange); radiusValueLabel.setVisible(fixedRange); radiusMarkerLabel.setVisible(!fixedRange); repack(); } protected void updateCommandVisibility() { final boolean alwaysActiveSelected = Boolean.TRUE.equals(alwaysActive.getValue()); activateCommand.getControls().setVisible(!alwaysActiveSelected); activateKey.getControls().setVisible(!alwaysActiveSelected); activateCommandLabel.setVisible(!alwaysActiveSelected); activateKeyLabel.setVisible(!alwaysActiveSelected); repack(); } protected void repack() { Decorator.repack(panel); } @Override public Component getControls() { return panel; } @Override public String getState() { return "false"; // NON-NLS } @Override public String getType() { final boolean alwaysActiveSelected = Boolean.TRUE.equals(alwaysActive.getValue()); final SequenceEncoder se = new SequenceEncoder(';'); se.append(transparencyColorValue.getValueString()); se.append(transparencyValue.getValueString()); se.append(radiusValue.getValueString()); se.append(alwaysActiveSelected); se.append(activateCommand.getValueString()); se.append(activateKey.getValueString()); if (Boolean.TRUE.equals(useMapShader.getValue()) && mapShaderId != null) { se.append(mapShaderId); } else { se.append(""); } se.append(fixedRadius.getValueString()); se.append(radiusMarker.getValueString()); se.append(descConfig.getValueString()); return AreaOfEffect.ID + se.getValue(); } } @Override public PieceI18nData getI18nData() { return getI18nData(activateCommand, getCommandDescription(description, Resources.getString("Editor.AreaOfEffect.toggle_visible_command_name"))); } }
package ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.ArrayList; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import core.Application; import core.History.HistoryInfo; import util.FileTools; import util.IChangedListener; import util.StringTools; import util.UiTools; public class HistoryPanel extends JPanel implements IChangedListener { private static final long serialVersionUID = 1L; private Application application; private JTable historyTable; private DefaultTableModel tableModel; private JTextArea historyOutput; private JButton deleteAllHistory; private JButton deleteHistory; private JButton filterHistory; private ArrayList<HistoryInfo> entries; private String filter; public HistoryPanel(){ application = Application.getInstance(); entries = new ArrayList<HistoryInfo>(); filter = ""; tableModel = new DefaultTableModel(){ private static final long serialVersionUID = 1L; public Object getValueAt(int row, int column){ try{ return super.getValueAt(row, column); }catch(Exception e){ return null; } } }; tableModel.addColumn("Launch"); tableModel.addColumn("Trigger"); tableModel.addColumn("Start"); tableModel.addColumn("Time"); tableModel.addColumn("Status"); historyTable = new JTable(tableModel){ private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int col){ return false; } }; historyTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); historyTable.setRowSelectionAllowed(true); historyTable.setColumnSelectionAllowed(false); TableColumnModel columnModel = historyTable.getColumnModel(); columnModel.getColumn(0).setMinWidth(150); columnModel.getColumn(1).setMinWidth(200); columnModel.getColumn(2).setMinWidth(150); columnModel.getColumn(2).setMaxWidth(150); columnModel.getColumn(3).setMinWidth(100); columnModel.getColumn(3).setMaxWidth(100); columnModel.getColumn(4).setMinWidth(150); columnModel.getColumn(4).setMaxWidth(150); deleteAllHistory = new JButton(" Clear "); deleteAllHistory.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ deleteAllHistory(); } }); deleteHistory = new JButton(" Delete "); deleteHistory.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ deleteHistory(); } }); filterHistory = new JButton(" Filter "); filterHistory.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ filterHistory(); } }); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); buttonPanel.add(deleteAllHistory); buttonPanel.add(deleteHistory); buttonPanel.add(filterHistory); JPanel topPanel = new JPanel(new BorderLayout()); topPanel.add(new JScrollPane(historyTable), BorderLayout.CENTER); topPanel.add(buttonPanel, BorderLayout.EAST); historyOutput = new JTextArea(); historyOutput.setEditable(false); JSplitPane centerPanel = new JSplitPane( JSplitPane.VERTICAL_SPLIT, topPanel, new JScrollPane(historyOutput)); centerPanel.setDividerLocation(150); setLayout(new BorderLayout()); add(centerPanel, BorderLayout.CENTER); historyTable.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ adjustSelection(); } }); historyTable.addKeyListener(new KeyListener(){ @Override public void keyPressed(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) { adjustSelection(); } @Override public void keyTyped(KeyEvent e) {} }); application.getHistory().addListener(this); } public void init() { entries = application.getHistory().getHistoryInfo(); initUI(); adjustSelection(); } private void clearUI() { historyTable.clearSelection(); for(int i=tableModel.getRowCount()-1; i>=0; i tableModel.removeRow(i); } } private void initUI() { for(HistoryInfo entry : entries){ if(matchesFilter(entry)){ Object[] rowData = { entry.name, entry.trigger, entry.start != null ? StringTools.getTextDate(entry.start) : "", (entry.start != null && entry.end != null) ? StringTools.getTimeDiff(entry.start, entry.end)+ " '" : "", entry.status.toString() }; tableModel.addRow(rowData); } } historyTable.setToolTipText("History: "+tableModel.getRowCount()+"/"+entries.size()+" items"); if(filter.isEmpty()){ filterHistory.setForeground(Color.BLACK); }else{ filterHistory.setForeground(Color.RED); } } private boolean matchesFilter(HistoryInfo entry) { if(!filter.isEmpty()){ if(!entry.name.toLowerCase().startsWith(filter.toLowerCase())){ return false; } } return true; } private void refreshUI(HistoryInfo selected) { clearUI(); initUI(); if(selected != null){ for(int i=0; i<entries.size(); i++){ HistoryInfo entry = entries.get(i); if( entry.historyId.equals(selected.historyId) && matchesFilter(entry) ){ historyTable.changeSelection(i, -1, false, false); break; } } } adjustSelection(); } private void adjustSelection() { HistoryInfo entry = getSelectedHistory(); if(entry != null){ File logfile = new File(entry.logfile); if(logfile.isFile()){ try{ historyOutput.setText(FileTools.readFile(logfile.getAbsolutePath())); historyOutput.setCaretPosition(0); }catch(Exception e){ application.getLogger().error(e); } }else{ historyOutput.setText(""); } deleteHistory.setEnabled(true); }else{ historyOutput.setText(""); deleteHistory.setEnabled(false); } } @Override public void changed(Object object) { if(object == application.getHistory()){ HistoryInfo selected = getSelectedHistory(); entries = application.getHistory().getHistoryInfo(); refreshUI(selected); } } private HistoryInfo getSelectedHistory() { HistoryInfo selected = null; int index = historyTable.getSelectedRow(); if(index >=0){ selected = entries.get(index); } return selected; } public void deleteAllHistory(){ if(UiTools.confirmDialog("Delete all history ?")){ application.getHistory().clear(); refreshUI(null); } } public void deleteHistory(){ HistoryInfo entry = getSelectedHistory(); if( entry != null && UiTools.confirmDialog("Delete history ["+entry.name+" ("+StringTools.getTextDate(entry.start)+")"+"] ?") ){ application.getHistory().delete(entry.historyId); refreshUI(null); } } public void filterHistory(){ String filter = UiTools.inputDialog("Filter for Launch", this.filter); if(filter != null){ this.filter = filter; } HistoryInfo selected = getSelectedHistory(); refreshUI(selected); } }
package structure.impl; import monitoring.impl.configs.DetConfig; import structure.intf.Binding; import structure.intf.Transition; /** * This class represents a Quantified Event Automaton (QEA) with the following * characteristics: * <ul> * <li>There is one quantified variable * <li>It can contain any number of free variables * <li>The transitions in the function delta consist of a start state, an event * and an end state. Optionally, it can be associated to a guard and/or an * assignment * <li>The QEA is deterministic * <li>Fixed quantified variable optimisation: The array of arguments of an * event always contains the value of the quantified in the first position * </ul> * * @author Helena Cuenca * @author Giles Reger */ public class NonSimpleDetQEA extends NonSimpleQEA { /** * Transition function delta for this QEA. For a given Transition in the * array, the first index corresponds to the start state and the second * index corresponds to the event name */ private Transition[][] delta; /** * Creates a <code>NonSimpleDetQEA</code> for the specified number of * states, number of events, initial state, quantification type and number * of free variables * * @param numStates * Number of states. The states are named: 1, 2,... * <code>numStates</code> * @param numEvents * Number of events. The events are named: 1, 2,... * <code>numEvents</code> * @param initialState * Initial state * @param quantification * Quantification type * @param freeVariablesCount * Number of free variables */ public NonSimpleDetQEA(int numStates, int numEvents, int initialState, Quantification quantification, int freeVariablesCount) { super(numStates, initialState, quantification, freeVariablesCount); delta = new Transition[numStates + 1][numEvents + 1]; } /** * Adds/replace a transition for the transition function delta of this QEA * * @param startState * Start state for this transition * @param event * Name of the event * @param transition * Object containing the rest of the information for this * transition: Parameters for the event, guard, assignment and * end state */ public void addTransition(int startState, int event, Transition transition) { delta[startState][event] = transition; } /** * Computes the next configuration for a given start configuration, event * and arguments, according to the transition function delta of this QEA * * @param config * Start configuration containing the start state and binding * (values of free variables) * @param event * Name of the event * @param args * Array of arguments for the event. The first position contains * the value for the quantified variable, while the values * starting from the second position correspond to free variables * @return End configuration containing the end state and binding (values of * free variables) after the transition */ public DetConfig getNextConfig(DetConfig config, int event, Object[] args) { // TODO Remove cast TransitionImpl transition = (TransitionImpl) delta[config.getState()][event]; // If the event is not defined for the current start state, return the // failing state with an empty binding if (transition == null) { config.setState(0); config.getBinding().setEmpty(); return config; } // Check number of arguments vs. number of parameters of the event checkArgParamLength(args.length, transition.getVariableNames().length); Binding binding = config.getBinding(); Object[] prevBinding = null; if (args.length > 1) { // Update binding for free variables prevBinding = updateBindingFixedQVar(binding, args, transition); } // If there is a guard and is not satisfied, rollback the binding and // return the failing state if (transition.getGuard() != null && !transition.getGuard().check(binding)) { config.setState(0); // Failing state if (prevBinding != null) { rollBackBindingFixedQVar(binding, transition, prevBinding); } return config; } // If there is an assignment, execute it if (transition.getAssignment() != null) { config.setBinding(transition.getAssignment().apply(binding)); } // Set the end state config.setState(transition.getEndState()); return config; } @Override public int[] getEventsAlphabet() { int[] a = new int[delta[0].length - 1]; for (int i = 0; i < a.length; i++) { a[i] = i + 1; } return a; } @Override public boolean isDeterministic() { return true; } }
package com.planet_ink.coffee_mud.commands; import com.planet_ink.coffee_mud.utils.*; import com.planet_ink.coffee_mud.commands.sysop.CreateEdit; import com.planet_ink.coffee_mud.commands.sysop.SysopItemUsage; import com.planet_ink.coffee_mud.interfaces.*; import com.planet_ink.coffee_mud.common.*; import java.util.*; public class Channels { private int numChannelsLoaded=0; private Vector channelNames=new Vector(); public void listChannels(MOB mob) { StringBuffer buf=new StringBuffer("Available channels: \n\r"); int col=0; for(int x=0;x<channelNames.size();x++) { if((++col)>3) { buf.append("\n\r"); col=1; } String channelName=(String)channelNames.elementAt(x); String onoff=""; if(Util.isSet((int)mob.getChannelMask(),x)) onoff=" (OFF)"; buf.append(Util.padRight(channelName+onoff,24)); } if(channelNames.size()==0) buf.append("None!"); mob.tell(buf.toString()); } public int loadChannels(String list, CommandSet cmdSet) { while(list.length()>0) { int x=list.indexOf(","); String item=null; if(x<0) { item=list; list=""; } else { item=list.substring(0,x).trim(); list=list.substring(x+1); } numChannelsLoaded++; channelNames.addElement(item.toUpperCase().trim()); //extraCMDs.addElement(item.toUpperCase().trim()); cmdSet.put(item.toUpperCase().trim(),new Integer(CommandSet.CHANNEL)); //extraCMDs.addElement("NO"+item.toUpperCase().trim()); cmdSet.put("NO"+item.toUpperCase().trim(),new Integer(CommandSet.NOCHANNEL)); } return numChannelsLoaded; } public void channel(MOB mob, Vector commands) { String channelName=((String)commands.elementAt(0)).toUpperCase().trim(); commands.removeElementAt(0); int channelNum=0; int channelInt=0; for(int c=0;c<channelNames.size();c++) { if(((String)channelNames.elementAt(c)).startsWith(channelName)) { channelNum=Math.round(Util.pow(2,c)); channelInt=c; break; } } if(Util.isSet(mob.getChannelMask(),channelInt)) { mob.setChannelMask(mob.getChannelMask()&(mob.getChannelMask()-channelNum)); mob.tell(channelName+" has been turned back on."); return; } if(commands.size()==0) { mob.tell(channelName+" what?"); return; } String str=" "+channelName+"S '"+Util.combine(commands,0)+"'"; FullMsg msg=new FullMsg(mob,null,null,Affect.MSG_OK_ACTION,"You"+str,Affect.NO_EFFECT,null,Affect.MASK_CHANNEL|channelInt,mob.name()+str); if(mob.location().okAffect(msg)) { for(int s=0;s<Sessions.size();s++) { Session ses=(Session)Sessions.elementAt(s); if((!ses.killFlag())&&(ses.mob()!=null) &&(!ses.mob().amDead()) &&(ses.mob().location()!=null) &&(ses.mob().okAffect(msg))) ses.mob().affect(msg); } } } public void nochannel(MOB mob, Vector commands) { String channelName=((String)commands.elementAt(0)).toUpperCase().trim().substring(2); commands.removeElementAt(0); int channelNum=0; for(int c=0;c<channelNames.size();c++) { if(((String)channelNames.elementAt(c)).startsWith(channelName)) channelNum=c; } if(!Util.isSet(mob.getChannelMask(),channelNum)) { mob.setChannelMask(mob.getChannelMask()|(Util.pow(2,channelNum))); mob.tell("The "+channelName+" channel has been turned off."); } else mob.tell("The "+channelName+" channel is already off."); } public void quiet(MOB mob) { boolean turnedoff=false; for(int c=0;c<channelNames.size();c++) { if(!Util.isSet(mob.getChannelMask(),c)) { mob.setChannelMask(mob.getChannelMask()|(Util.pow(2,c))); turnedoff=true; } } if(turnedoff) mob.tell("All channels have been turned off."); else { mob.tell("All channels have been turned back on."); mob.setChannelMask(0); } } }
package org.opencms.ade.configuration; import org.opencms.ade.detailpage.CmsDetailPageInfo; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.CmsUser; import org.opencms.file.CmsVfsResourceAlreadyExistsException; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.file.types.I_CmsResourceType; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.security.I_CmsPrincipal; import org.opencms.test.OpenCmsTestCase; import org.opencms.test.OpenCmsTestProperties; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.xml.containerpage.CmsFormatterBean; import org.opencms.xml.containerpage.CmsFormatterConfiguration; import org.opencms.xml.content.CmsXmlContentProperty; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.ComparisonFailure; import junit.framework.Test; import com.google.common.collect.Lists; /** * Lightweight tests for the ADE configuration mechanism which mostly do not read the configuration data from the VFS.<p> */ public class TestConfig extends OpenCmsTestCase { protected static final List<CmsPropertyConfig> NO_PROPERTIES = Collections.<CmsPropertyConfig> emptyList(); protected static final List<CmsDetailPageInfo> NO_DETAILPAGES = Collections.<CmsDetailPageInfo> emptyList(); protected static final List<CmsModelPageConfig> NO_MODEL_PAGES = Collections.<CmsModelPageConfig> emptyList(); protected static final List<CmsResourceTypeConfig> NO_TYPES = Collections.<CmsResourceTypeConfig> emptyList(); /** * Test constructor.<p> * * @param arg0 */ public TestConfig(String arg0) { super(arg0); } /** * Returns the test suite.<p> * * @return the test suite */ public static Test suite() { OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH); return generateSetupTestWrapper(TestConfig.class, "ade-config", "/"); } public void createFolder(String rootPath, boolean deep) throws CmsException { CmsObject cms = getCmsObject(); cms.getRequestContext().setSiteRoot(""); if (!deep) { cms.createResource(rootPath, CmsResourceTypeFolder.getStaticTypeId()); } else { List<String> parents = new ArrayList<String>(); String currentPath = rootPath; while (currentPath != null) { parents.add(currentPath); currentPath = CmsResource.getParentFolder(currentPath); } parents = Lists.reverse(parents); System.out.println("Creating folders up to " + rootPath + "(" + parents.size() + ")"); for (String parent : parents) { System.out.println("Creating folder: " + parent); try { cms.createResource(parent, CmsResourceTypeFolder.getStaticTypeId()); } catch (CmsVfsResourceAlreadyExistsException e) { // nop } } } } public void testCreatable() throws Exception { String baseDirectory = "/sites/default/testCreatable"; String contentDirectory = baseDirectory + "/.content"; String plain = "plain"; String binary = "binary"; String plainDir = contentDirectory + "/" + plain; String binaryDir = contentDirectory + "/" + binary; createFolder(plainDir, true); createFolder(binaryDir, true); CmsObject cms = rootCms(); String username = "User_testCreatable"; CmsUser dummyUser = cms.createUser(username, "password", "description", Collections.<String, Object> emptyMap()); cms.chacc(plainDir, I_CmsPrincipal.PRINCIPAL_USER, username, "+r+v-w"); cms.chacc(binaryDir, I_CmsPrincipal.PRINCIPAL_USER, username, "+r+v+w"); CmsObject dummyUserCms = rootCms(); cms.addUserToGroup(username, OpenCms.getDefaultUsers().getGroupUsers()); dummyUserCms.loginUser(username, "password"); dummyUserCms.getRequestContext().setCurrentProject(cms.readProject("Offline")); CmsFolderOrName folder = new CmsFolderOrName(baseDirectory + "/.content", "plain"); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("plain", false, folder, "pattern_%(number)", null); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("binary", false, new CmsFolderOrName(baseDirectory + "/.content", "binary"), "binary_%(number).html", null); CmsTestConfigData config1 = new CmsTestConfigData( baseDirectory, list(typeConf1, typeConf2), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); List<CmsResourceTypeConfig> creatableTypes = config1.getCreatableTypes(dummyUserCms); assertEquals(1, creatableTypes.size()); assertEquals(binary, creatableTypes.get(0).getTypeName()); creatableTypes = config1.getCreatableTypes(cms); assertEquals(2, creatableTypes.size()); assertEquals( set("plain", "binary"), set(creatableTypes.get(0).getTypeName(), creatableTypes.get(1).getTypeName())); } public void testCreateContentsLocally() throws Exception { String typename = "plain"; String baseDirectory = "/sites/default"; String contentDirectory = baseDirectory + "/.content"; String baseDirectory2 = "/sites/default/foo"; String contentDirectory2 = baseDirectory2 + "/.content"; CmsFolderOrName folder = new CmsFolderOrName(contentDirectory, typename); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig(typename, false, folder, "file_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( baseDirectory, list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); CmsTestConfigData config2 = new CmsTestConfigData( baseDirectory2, NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config2.setCreateContentsLocally(true); config2.setParent(config1); config2.initialize(rootCms()); String folderPath = config2.getResourceType("plain").getFolderPath(rootCms()); assertPathEquals("/sites/default/foo/.content/plain", folderPath); } public void testCreateContentsLocally2() throws Exception { String typename = "plain"; String baseDirectory = "/sites/default"; String contentDirectory = baseDirectory + "/.content"; String baseDirectory2 = "/sites/default/foo"; String contentDirectory2 = baseDirectory2 + "/.content"; String baseDirectory3 = "/sites/default/foo/bar"; String contentDirectory3 = baseDirectory3 + "/.content"; CmsFolderOrName folder = new CmsFolderOrName(contentDirectory, typename); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig(typename, false, folder, "file_%(number)", null); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("foo", false, new CmsFolderOrName( contentDirectory2, "foo"), "foo_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( baseDirectory, list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); CmsTestConfigData config2 = new CmsTestConfigData( baseDirectory2, list(typeConf2), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config2.setParent(config1); config2.initialize(rootCms()); CmsTestConfigData config3 = new CmsTestConfigData( baseDirectory3, NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config3.setCreateContentsLocally(true); config3.setParent(config2); config3.initialize(rootCms()); String folderPath1 = "/sites/default/foo/bar/.content/foo"; String folderPath2 = "/sites/default/foo/bar/.content/plain"; List<CmsResourceTypeConfig> typeConfigs = config3.getResourceTypes(); assertEquals(2, typeConfigs.size()); assertEquals( set(folderPath1, folderPath2), set(typeConfigs.get(0).getFolderPath(rootCms()), typeConfigs.get(1).getFolderPath(rootCms()))); assertEquals(2, config2.getResourceTypes().size()); assertEquals( set("/sites/default/foo/.content/foo", "/sites/default/.content/plain"), set( config2.getResourceTypes().get(0).getFolderPath(rootCms()), config2.getResourceTypes().get(1).getFolderPath(rootCms()))); } public void testCreateContentsLocally3() throws Exception { String typename = "plain"; String baseDirectory = "/sites/default"; String contentDirectory = baseDirectory + "/.content"; String baseDirectory2 = "/sites/default/foo"; String contentDirectory2 = baseDirectory2 + "/.content"; String baseDirectory3 = "/sites/default/foo/bar"; String contentDirectory3 = baseDirectory3 + "/.content"; CmsFolderOrName folder = new CmsFolderOrName(contentDirectory, typename); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig(typename, false, folder, "file_%(number)", null); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("foo", false, new CmsFolderOrName( contentDirectory2, "foo"), "foo_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( baseDirectory, list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); CmsTestConfigData config2 = new CmsTestConfigData( baseDirectory2, list(typeConf2), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config2.setParent(config1); config2.setCreateContentsLocally(true); config2.initialize(rootCms()); CmsTestConfigData config3 = new CmsTestConfigData( baseDirectory3, NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config3.setParent(config2); config3.initialize(rootCms()); assertPathEquals("/sites/default/foo/.content/plain", config3.getResourceType("plain").getFolderPath(rootCms())); } public void testCreateElements() throws Exception { String typename = "plain"; String baseDirectory = "/sites/default/testCreateElements"; String contentDirectory = baseDirectory + "/.content"; String articleDirectory = contentDirectory + "/" + typename; try { createFolder(articleDirectory, true); } catch (CmsVfsResourceAlreadyExistsException e) { System.out.println("***" + e); } CmsFolderOrName folder = new CmsFolderOrName(baseDirectory + "/.content", typename); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig(typename, false, folder, "file_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( baseDirectory, list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); assertSame(config1.getResourceType(typename), typeConf1); typeConf1.createNewElement(getCmsObject()); CmsObject cms = rootCms(); List<CmsResource> files = cms.getFilesInFolder(articleDirectory); assertEquals(1, files.size()); assertTrue(files.get(0).getName().startsWith("file_")); typeConf1.createNewElement(getCmsObject()); files = cms.getFilesInFolder(articleDirectory); assertEquals(2, files.size()); assertTrue(files.get(0).getName().startsWith("file_")); assertTrue(files.get(1).getName().startsWith("file_")); } public void testDefaultFolderName() throws Exception { CmsFolderOrName folder = null; CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, null, "pattern_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( "/somefolder/somesubfolder", list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.setIsModuleConfig(true); config1.initialize(rootCms()); typeConf1 = config1.getResourceType("foo"); CmsFolderOrName folderOrName = typeConf1.getFolderOrName(); String folderPath = typeConf1.getFolderPath(getCmsObject()); assertPathEquals("/sites/default/.content/foo", folderPath); } public void testDefaultFolderName2() throws Exception { CmsFolderOrName folder = null; CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, null, "pattern_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( "/somefolder/somesubfolder", list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.setIsModuleConfig(true); config1.initialize(rootCms()); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("foo", false, null, "patternx_%(number)", null); CmsTestConfigData config2 = new CmsTestConfigData( "/blah", list(typeConf2), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config2.setParent(config1); config2.initialize(rootCms()); typeConf2 = config2.getResourceType("foo"); String folderPath = typeConf2.getFolderPath(getCmsObject()); assertPathEquals("/sites/default/.content/foo", folderPath); } public void testDetailPages2() throws Exception { CmsDetailPageInfo a1 = new CmsDetailPageInfo(getId("/sites/default/a1"), "/sites/default/a1", "a"); CmsDetailPageInfo a2 = new CmsDetailPageInfo(getId("/sites/default/a2"), "/sites/default/a2", "a"); CmsDetailPageInfo a3 = new CmsDetailPageInfo(getId("/sites/default/a3"), "/sites/default/a3", "a"); CmsDetailPageInfo a4 = new CmsDetailPageInfo(getId("/sites/default/a4"), "/sites/default/a4", "a"); CmsDetailPageInfo b1 = new CmsDetailPageInfo(getId("/sites/default/b1"), "/sites/default/b1", "b"); CmsDetailPageInfo b2 = new CmsDetailPageInfo(getId("/sites/default/b2"), "/sites/default/b2", "b"); List<CmsDetailPageInfo> parentDetailPages = list(a1, a2, b1, b2); List<CmsDetailPageInfo> childDetailPages = list(a3, a4); CmsTestConfigData config1 = new CmsTestConfigData( "/sites/default", NO_TYPES, NO_PROPERTIES, parentDetailPages, NO_MODEL_PAGES); config1.initialize(rootCms()); CmsTestConfigData config2 = new CmsTestConfigData( "/sites/default/foo", NO_TYPES, NO_PROPERTIES, childDetailPages, NO_MODEL_PAGES); config2.initialize(rootCms()); config2.setParent(config1); List<CmsDetailPageInfo> pages = config2.getAllDetailPages(false); //assertEquals(4, pages.size()); assertEquals( set(a3.getUri(), a4.getUri(), b1.getUri(), b2.getUri()), set(pages.get(0).getUri(), pages.get(1).getUri(), pages.get(2).getUri(), pages.get(3).getUri())); assertEquals( list(a3.getUri(), a4.getUri()), list(config2.getDetailPagesForType("a").get(0).getUri(), config2.getDetailPagesForType("a").get(1).getUri())); } public void testDiscardInheritedModelPages() throws Exception { CmsModelPageConfig m1 = new CmsModelPageConfig(rootCms().readResource("/sites/default/a1"), true, false); CmsModelPageConfig m2 = new CmsModelPageConfig(rootCms().readResource("/sites/default/a2"), true, false); CmsModelPageConfig m3 = new CmsModelPageConfig(rootCms().readResource("/sites/default/a3"), true, false); CmsTestConfigData config1 = new CmsTestConfigData( "/", NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, list(m1, m2, m3)); CmsTestConfigData config2 = new CmsTestConfigData( "/blah", NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); config2.initialize(rootCms()); config2.setParent(config1); config2.setDiscardInheritedModelPages(true); assertEquals(0, config2.getModelPages().size()); } public void testDiscardInheritedProperties() throws Exception { CmsPropertyConfig foo = createPropertyConfig("foo", "foo1"); CmsPropertyConfig bar = createPropertyConfig("bar", "bar1"); CmsPropertyConfig baz = createPropertyConfig("baz", "baz1"); CmsTestConfigData config1 = new CmsTestConfigData("/", NO_TYPES, list(foo, bar), NO_DETAILPAGES, NO_MODEL_PAGES); CmsTestConfigData config2 = new CmsTestConfigData("/blah", NO_TYPES, list(baz), NO_DETAILPAGES, NO_MODEL_PAGES); config2.setDiscardInheritedProperties(true); config1.initialize(rootCms()); config2.initialize(rootCms()); config2.setParent(config1); Map<String, CmsXmlContentProperty> result = config2.getPropertyConfigurationAsMap(); assertEquals(1, result.size()); assertNotNull(result.get("baz")); } public void testDiscardInheritedTypes() throws Exception { CmsFolderOrName folder = new CmsFolderOrName("/.content", "foldername"); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, folder, "pattern_%(number)", null); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("bar", false, new CmsFolderOrName( "/.content", "foldername2"), "pattern2_%(number)", null); CmsResourceTypeConfig typeConf3 = new CmsResourceTypeConfig("baz", false, folder, "blah", null); CmsTestConfigData config1 = new CmsTestConfigData( "/", list(typeConf1, typeConf2, typeConf3), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); CmsTestConfigData config2 = new CmsTestConfigData( "/", list(typeConf3.copy()), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config2.setIsDiscardInheritedTypes(true); config1.initialize(rootCms()); config2.initialize(rootCms()); config2.setParent(config1); List<CmsResourceTypeConfig> resourceTypeConfig = config2.getResourceTypes(); assertEquals(1, resourceTypeConfig.size()); assertEquals("baz", resourceTypeConfig.get(0).getTypeName()); } public void testInheritedFolderName1() throws Exception { CmsFolderOrName folder = new CmsFolderOrName("/somefolder/.content", "blah"); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, folder, "pattern_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( "/somefolder", list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); CmsTestConfigData config2 = new CmsTestConfigData( "/somefolder/somesubfolder", NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config2.initialize(rootCms()); config2.setParent(config1); assertPathEquals( "/somefolder/.content/blah", config2.getResourceType(typeConf1.getTypeName()).getFolderPath(getCmsObject())); } public void testInheritedFolderName2() throws Exception { CmsFolderOrName folder = new CmsFolderOrName("/somefolder/.content", "blah"); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, folder, "pattern_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( "/somefolder", list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("foo", false, null, "blah", null); CmsTestConfigData config2 = new CmsTestConfigData( "/somefolder/somesubfolder", list(typeConf2), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config2.initialize(rootCms()); config2.setParent(config1); CmsResourceTypeConfig rtc = config2.getResourceType(typeConf1.getTypeName()); String folderPath = rtc.getFolderPath(getCmsObject()); assertPathEquals("/somefolder/.content/blah", folderPath); } public void testInheritNamePattern() throws Exception { CmsFolderOrName folder = new CmsFolderOrName("/.content", "foldername"); String pattern1 = "pattern1"; CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, folder, pattern1, null); CmsFolderOrName folder2 = new CmsFolderOrName("/sites/default/.content", "foldername2"); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("foo", false, folder, null, null); CmsTestConfigData config1 = new CmsTestConfigData( "/", list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); CmsTestConfigData config2 = new CmsTestConfigData( "/sites/default", list(typeConf2), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config2.initialize(rootCms()); config2.setParent(config1); assertEquals(pattern1, config2.getResourceType("foo").getNamePattern()); } public void testInheritProperties() throws Exception { List<CmsPropertyConfig> propConf1 = list( createPropertyConfig("A", "A1"), createPropertyConfig("B", "B1"), createPropertyConfig("C", "C1"), createPropertyConfig("D", "D1")); CmsTestConfigData config1 = new CmsTestConfigData( "/somefolder", NO_TYPES, propConf1, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); List<CmsPropertyConfig> propConf2 = list( createDisabledPropertyConfig("C"), createPropertyConfig("D", "D2"), createPropertyConfig("A", "A2")); CmsTestConfigData config2 = new CmsTestConfigData( "/somefolder/somesubfolder", NO_TYPES, propConf2, NO_DETAILPAGES, NO_MODEL_PAGES); config2.initialize(rootCms()); config2.setParent(config1); List<CmsPropertyConfig> resultConf = config2.getPropertyConfiguration(); assertEquals(3, resultConf.size()); assertEquals("D", resultConf.get(0).getName()); assertEquals("D2", resultConf.get(0).getPropertyData().getDescription()); assertEquals("A", resultConf.get(1).getName()); assertEquals("A2", resultConf.get(1).getPropertyData().getDescription()); assertEquals("B", resultConf.get(2).getName()); assertEquals("B1", resultConf.get(2).getPropertyData().getDescription()); } public void testInheritResourceTypes1() throws Exception { CmsFolderOrName folder = new CmsFolderOrName("/.content", "foldername"); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, folder, "pattern_%(number)", null); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("bar", false, new CmsFolderOrName( "/.content", "foldername2"), "pattern2_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( "/", list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); CmsTestConfigData config2 = new CmsTestConfigData( "/", list(typeConf2), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); config2.initialize(rootCms()); config2.setParent(config1); List<CmsResourceTypeConfig> resourceTypeConfig = config2.getResourceTypes(); assertEquals(typeConf1.getTypeName(), resourceTypeConfig.get(1).getTypeName()); assertEquals(typeConf2.getTypeName(), resourceTypeConfig.get(0).getTypeName()); } public void testModelPages1() throws Exception { CmsObject cms = getCmsObject(); CmsModelPageConfig a1 = new CmsModelPageConfig(cms.readResource("/a1"), false, false); CmsModelPageConfig a2 = new CmsModelPageConfig(cms.readResource("/a2"), false, false); CmsModelPageConfig b1 = new CmsModelPageConfig(cms.readResource("/b1"), false, false); CmsModelPageConfig b2 = new CmsModelPageConfig(cms.readResource("/b2"), false, false); CmsTestConfigData config1 = new CmsTestConfigData( "/sites/default", NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, list(a1, a2)); config1.initialize(rootCms()); CmsTestConfigData config2 = new CmsTestConfigData( "/sites/default/foo", NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, list(b1, b2)); config2.initialize(rootCms()); config2.setParent(config1); List<CmsModelPageConfig> modelpages = config2.getModelPages(); assertEquals(b1.getResource().getStructureId(), modelpages.get(0).getResource().getStructureId()); assertEquals(b2.getResource().getStructureId(), modelpages.get(1).getResource().getStructureId()); assertEquals(a1.getResource().getStructureId(), modelpages.get(2).getResource().getStructureId()); assertEquals(a2.getResource().getStructureId(), modelpages.get(3).getResource().getStructureId()); assertEquals(b1.getResource().getStructureId(), config2.getDefaultModelPage().getResource().getStructureId()); } public void testModelPages2() throws Exception { CmsObject cms = getCmsObject(); CmsModelPageConfig a1 = new CmsModelPageConfig(cms.readResource("/a1"), false, false); CmsModelPageConfig a2 = new CmsModelPageConfig(cms.readResource("/a2"), false, false); CmsModelPageConfig b1 = new CmsModelPageConfig(cms.readResource("/b1"), false, false); CmsModelPageConfig b2 = new CmsModelPageConfig(cms.readResource("/b2"), true, false); CmsTestConfigData config1 = new CmsTestConfigData( "/sites/default", NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, list(a1, a2)); config1.initialize(rootCms()); CmsTestConfigData config2 = new CmsTestConfigData( "/sites/default/foo", NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, list(b1, b2)); config2.initialize(rootCms()); config2.setParent(config1); List<CmsModelPageConfig> modelpages = config2.getModelPages(); assertEquals(b2.getResource().getStructureId(), config2.getDefaultModelPage().getResource().getStructureId()); } public void testOverrideResourceType() throws Exception { CmsFolderOrName folder = new CmsFolderOrName("/.content", "foldername"); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, folder, "pattern_%(number)", null); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("foo", false, new CmsFolderOrName( "/.content", "foldername2"), "pattern2_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( "/", list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); CmsTestConfigData config2 = new CmsTestConfigData( "/", list(typeConf2), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); config2.initialize(rootCms()); config2.setParent(config1); List<CmsResourceTypeConfig> resourceTypeConfig = config2.getResourceTypes(); assertEquals(1, resourceTypeConfig.size()); assertEquals(typeConf2.getNamePattern(), resourceTypeConfig.get(0).getNamePattern()); } public void testParseConfiguration() throws Exception { CmsObject cms = rootCms(); CmsConfigurationReader configReader = new CmsConfigurationReader(rootCms()); CmsADEConfigData configData = configReader.parseSitemapConfiguration( "/", cms.readResource("/sites/default/test.config")); configData.initialize(rootCms()); assertFalse(configData.isModuleConfiguration()); assertEquals(1, configData.getResourceTypes().size()); CmsResourceTypeConfig v8article = configData.getResourceType("v8article"); assertNotNull(v8article); assertEquals("asdf", v8article.getNamePattern()); CmsFolderOrName folder = v8article.getFolderOrName(); assertTrue(folder.isName()); assertEquals("asdf", folder.getFolderName()); assertEquals(1, configData.getAllDetailPages().size()); assertEquals(1, configData.getModelPages().size()); List<CmsPropertyConfig> props = configData.getPropertyConfiguration(); assertEquals(1, props.size()); CmsPropertyConfig prop1 = configData.getPropertyConfiguration().get(0); assertEquals("prop1", prop1.getName()); assertEquals(false, prop1.isDisabled()); assertEquals("displayname", prop1.getPropertyData().getNiceName()); assertEquals("description", prop1.getPropertyData().getDescription()); assertEquals("string", prop1.getPropertyData().getWidget()); assertEquals("default", prop1.getPropertyData().getDefault()); assertEquals("widgetconfig", prop1.getPropertyData().getWidgetConfiguration()); assertEquals("ruleregex", prop1.getPropertyData().getRuleRegex()); assertEquals("string", prop1.getPropertyData().getType()); assertEquals("ruletype", prop1.getPropertyData().getRuleType()); assertEquals("error", prop1.getPropertyData().getError()); assertEquals(true, prop1.getPropertyData().isPreferFolder()); } public void testParseModuleConfiguration() throws Exception { CmsObject cms = rootCms(); CmsConfigurationReader configReader = new CmsConfigurationReader(rootCms()); CmsADEConfigData configData = configReader.parseSitemapConfiguration( "/", cms.readResource("/sites/default/testmod.config")); configData.initialize(rootCms()); assertTrue(configData.isModuleConfiguration()); assertEquals(1, configData.getResourceTypes().size()); CmsResourceTypeConfig anothertype = configData.getResourceType("anothertype"); assertNotNull(anothertype); assertEquals("abc_%(number)", anothertype.getNamePattern()); CmsFolderOrName folder = anothertype.getFolderOrName(); assertTrue(folder.isFolder()); assertPathEquals("/sites/default", folder.getFolder().getRootPath()); assertEquals(0, configData.getAllDetailPages().size()); assertEquals(0, configData.getModelPages().size()); List<CmsPropertyConfig> props = configData.getPropertyConfiguration(); assertEquals(1, props.size()); CmsPropertyConfig prop1 = configData.getPropertyConfiguration().get(0); assertEquals("propertyname1", prop1.getName()); assertEquals(false, prop1.isDisabled()); assertEquals("displayname1", prop1.getPropertyData().getNiceName()); assertEquals("description1", prop1.getPropertyData().getDescription()); assertEquals("string", prop1.getPropertyData().getWidget()); assertEquals("default1", prop1.getPropertyData().getDefault()); assertEquals("widgetconfig1", prop1.getPropertyData().getWidgetConfiguration()); assertEquals("ruleregex1", prop1.getPropertyData().getRuleRegex()); assertEquals("string", prop1.getPropertyData().getType()); assertEquals("ruletype1", prop1.getPropertyData().getRuleType()); assertEquals("error1", prop1.getPropertyData().getError()); assertEquals(true, prop1.getPropertyData().isPreferFolder()); } public void testRemoveResourceType() throws Exception { CmsFolderOrName folder = new CmsFolderOrName("/.content", "foldername"); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, folder, "pattern_%(number)", null); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("bar", false, new CmsFolderOrName( "/.content", "foldername2"), "pattern2_%(number)", null); CmsResourceTypeConfig typeConf3 = new CmsResourceTypeConfig("baz", false, folder, "blah", null); CmsTestConfigData config1 = new CmsTestConfigData( "/", list(typeConf1, typeConf2, typeConf3), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); CmsResourceTypeConfig removeType = new CmsResourceTypeConfig("bar", true, null, null, null); CmsTestConfigData config2 = new CmsTestConfigData( "/", list(removeType), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); config2.initialize(rootCms()); config2.setParent(config1); List<CmsResourceTypeConfig> resourceTypeConfig = config2.getResourceTypes(); assertEquals(2, resourceTypeConfig.size()); assertEquals(typeConf1.getTypeName(), resourceTypeConfig.get(0).getTypeName()); assertEquals(typeConf3.getTypeName(), resourceTypeConfig.get(1).getTypeName()); } public void testReorderResourceTypes() throws Exception { CmsFolderOrName folder = new CmsFolderOrName("/.content", "foldername"); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, folder, "pattern_%(number)", null); CmsResourceTypeConfig typeConf2 = new CmsResourceTypeConfig("bar", false, new CmsFolderOrName( "/.content", "foldername2"), "pattern2_%(number)", null); CmsResourceTypeConfig typeConf3 = new CmsResourceTypeConfig("baz", false, folder, "blah", null); CmsTestConfigData config1 = new CmsTestConfigData( "/", list(typeConf1, typeConf2, typeConf3), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); CmsTestConfigData config2 = new CmsTestConfigData( "/", list(typeConf3.copy(), typeConf1.copy()), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); config2.initialize(rootCms()); config2.setParent(config1); List<CmsResourceTypeConfig> resourceTypeConfig = config2.getResourceTypes(); assertEquals(3, resourceTypeConfig.size()); assertEquals(typeConf3.getTypeName(), resourceTypeConfig.get(0).getTypeName()); assertEquals(typeConf1.getTypeName(), resourceTypeConfig.get(1).getTypeName()); assertEquals(typeConf2.getTypeName(), resourceTypeConfig.get(2).getTypeName()); } public void testResolveFolderName1() throws Exception { CmsFolderOrName folder = new CmsFolderOrName("/somefolder/somesubfolder/.content", "blah"); CmsResourceTypeConfig typeConf1 = new CmsResourceTypeConfig("foo", false, folder, "pattern_%(number)", null); CmsTestConfigData config1 = new CmsTestConfigData( "/somefolder/somesubfolder", list(typeConf1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); assertPathEquals( "/somefolder/somesubfolder/.content/blah", config1.getResourceType(typeConf1.getTypeName()).getFolderPath(getCmsObject())); } public void testResourceTypeConfigObjectsNotSame() throws Exception { CmsResourceTypeConfig c1 = new CmsResourceTypeConfig("c", false, null, "foo", null); CmsTestConfigData t1 = new CmsTestConfigData("/", list(c1), NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); CmsTestConfigData t2 = new CmsTestConfigData("/", NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); t1.initialize(rootCms()); t2.initialize(rootCms()); t2.setParent(t1); assertNotNull(t2.getResourceType("c")); assertNotSame(t1.getResourceType("c"), t2.getResourceType("c")); } public void testXsdFormatters1() throws Exception { CmsFolderOrName folder = null; CmsTestConfigData config1 = new CmsTestConfigData("/", NO_TYPES, NO_PROPERTIES, NO_DETAILPAGES, NO_MODEL_PAGES); config1.initialize(rootCms()); CmsFormatterConfiguration formatterConfig = config1.getFormatters("article1"); List<CmsFormatterBean> formatters = formatterConfig.getAllFormatters(); assertEquals(2, formatters.size()); CmsFormatterBean formatter1 = formatters.get(0); CmsFormatterBean formatter2 = formatters.get(1); assertEquals(1, formatter1.getMinWidth()); assertEquals(2, formatter1.getMaxWidth()); assertEquals(3, formatter2.getMinWidth()); assertEquals(4, formatter2.getMaxWidth()); } protected void assertPathEquals(String path1, String path2) { if ((path1 == null) && (path2 == null)) { return; } if ((path1 == null) || (path2 == null)) { throw new ComparisonFailure("comparison failure", path1, path2); } assertEquals(CmsStringUtil.joinPaths("/", path1, "/"), CmsStringUtil.joinPaths("/", path2, "/")); } protected CmsPropertyConfig createDisabledPropertyConfig(String name) { CmsXmlContentProperty prop = createXmlContentProperty(name, null); return new CmsPropertyConfig(prop, true); } protected CmsPropertyConfig createPropertyConfig(String name, String description) { CmsXmlContentProperty prop = createXmlContentProperty(name, description); return new CmsPropertyConfig(prop, false); } protected CmsXmlContentProperty createXmlContentProperty(String name, String description) { return new CmsXmlContentProperty(name, "string", "string", "", "", "", "", "", description, null, null); } protected void dumpTree() throws CmsException { CmsObject cms = rootCms(); CmsResource root = cms.readResource("/"); dumpTree(cms, root, 0); } protected void dumpTree(CmsObject cms, CmsResource res, int indentation) throws CmsException { writeIndentation(indentation); System.out.println(res.getName()); I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(res); if (resType.isFolder()) { List<CmsResource> children = cms.getResourcesInFolder(res.getRootPath(), CmsResourceFilter.ALL); for (CmsResource child : children) { dumpTree(cms, child, indentation + 6); } } } protected CmsUUID getId(String rootPath) throws CmsException { CmsObject cms = rootCms(); return cms.readResource(rootPath).getStructureId(); } protected <X> List<X> list(X... elems) { List<X> result = new ArrayList<X>(); for (X x : elems) { result.add(x); } return result; } protected CmsObject rootCms() throws CmsException { CmsObject cms = getCmsObject(); cms.getRequestContext().setSiteRoot(""); return cms; } protected <X> Set<X> set(X... elems) { Set<X> result = new HashSet<X>(); for (X x : elems) { result.add(x); } return result; } protected void writeIndentation(int indent) { for (int i = 0; i < indent; i++) { System.out.print(" "); } } }
package pt.fccn.sobre.arquivo.tests; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.Test; import pt.fccn.saw.selenium.Retry; import pt.fccn.saw.selenium.WebDriverTestBaseParalell; import pt.fccn.sobre.arquivo.pages.CommonQuestionsPage; import pt.fccn.sobre.arquivo.pages.ExamplesPage; import pt.fccn.sobre.arquivo.pages.IndexSobrePage; public class ExamplesTest extends WebDriverTestBaseParalell { public ExamplesTest(String os, String version, String browser, String deviceName, String deviceOrientation) { super( os, version, browser, deviceName, deviceOrientation ); } @Test public void examplesTest( ) { System.out.print( "Running examples Test. \n"); IndexSobrePage index = null; try{ index = new IndexSobrePage( driver ); } catch( IOException e ) { fail("IOException -> IndexSobrePage"); } System.out.println( "Going to the ExamplePage" ); ExamplesPage examplePage = index.goToExamplePage( ); assertTrue("Failed The Example Page Test in Portuguese", examplePage.checkLinksExamples( "PT" ) ); //TODO english version missing } }
package de.eightbitboy.ecorealms.map; public class Map { private int sizeX; private int sizeY; private MapEntity[] entities; public Map(int sizeX, int sizeY) { this.sizeX = sizeX; this.sizeY = sizeY; initialize(); } public int getSizeX() { return this.sizeX; } public int getSizeY() { return this.sizeY; } MapEntity[] getEntities() { return this.entities; } private void initialize() { entities = new MapEntity[sizeX * sizeY]; } public void put(MapEntity entity) { if (!hasValidPosition(entity)) { throw new InvalidMapAccessException( "The entity has an invalid position: " + entity.getPosition()); } else { insert(entity); } } private void insert(MapEntity entity) { MapPoint position = entity.getPosition(); if (positionIsFree(position)) { int index = (position.x % sizeX) + position.y; entities[index] = entity; } else { throw new InvalidMapAccessException( "The position is already occupied: " + entity.getPosition()); } } public void remove(MapEntity entity) { } private boolean hasValidPosition(MapEntity entity) { MapPoint position = entity.getPosition(); return !(position.x < 0 || position.y < 0 || position.x >= this.sizeX || position.y >= this.sizeY); } private boolean positionIsFree(MapPoint point) { //TODO return true; } public MapEntity get(MapPoint position) { //TODO return new MapEntity() { @Override public MapPoint getPosition() { return null; } @Override public int getSizeX() { return 0; } @Override public int getSizeY() { return 0; } }; } }
package com.epam.ta.reportportal.core.project; import com.epam.ta.reportportal.auth.AuthConstants; import com.epam.ta.reportportal.database.dao.UserRepository; import com.epam.ta.reportportal.database.entity.user.User; import com.epam.ta.reportportal.database.entity.user.UserType; import com.epam.ta.reportportal.database.personal.PersonalProjectUtils; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.model.project.UnassignUsersRQ; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.beans.factory.annotation.Autowired; import com.epam.ta.BaseTest; import com.epam.ta.reportportal.core.project.impl.UpdateProjectHandler; import com.epam.ta.reportportal.database.dao.ProjectRepository; import com.epam.ta.reportportal.database.entity.Project; import com.epam.ta.reportportal.database.fixture.SpringFixture; import com.epam.ta.reportportal.database.fixture.SpringFixtureRule; import com.epam.ta.reportportal.ws.model.project.ProjectConfiguration; import com.epam.ta.reportportal.ws.model.project.UpdateProjectRQ; import com.epam.ta.reportportal.ws.model.project.email.ProjectEmailConfig; import java.util.Arrays; import java.util.Collections; import static java.util.Collections.singletonList; import static org.hamcrest.Matchers.containsString; /** * @author Dzmitry_Kavalets */ @SpringFixture("unitTestsProjectTriggers") public class UpdateProjectHandlerTest extends BaseTest { @Rule @Autowired public SpringFixtureRule dfRule; @Rule public ExpectedException exception = ExpectedException.none(); @Autowired private UpdateProjectHandler updateProjectHandler; @Autowired private ProjectRepository projectRepository; @Autowired private UserRepository userRepository; @Test public void checkEmptyEmailOptions() { String userName = "user1"; UpdateProjectRQ updateProjectRQ = new UpdateProjectRQ(); ProjectConfiguration configuration = new ProjectConfiguration(); configuration.setEntry("INTERNAL"); configuration.setStatisticCalculationStrategy("TEST_BASED"); configuration.setProjectSpecific("DEFAULT"); configuration.setEmailConfig(new ProjectEmailConfig()); updateProjectRQ.setConfiguration(configuration); String project1 = "project1"; updateProjectHandler.updateProject(project1, updateProjectRQ, userName); Project one = projectRepository.findOne(project1); Assert.assertNotNull(one.getConfiguration().getEmailConfig()); } @Test public void checkUnassignFromPersonal() { User user = new User(); user.setEmail("checkUnassignFromPersonal@gmail.com"); user.setLogin("checkUnassignFromPersonal"); user.setType(UserType.INTERNAL); Project project = PersonalProjectUtils.generatePersonalProject(user); userRepository.save(user); projectRepository.save(project); UnassignUsersRQ rq = new UnassignUsersRQ(); rq.setUsernames(singletonList(user.getLogin())); exception.expect(ReportPortalException.class); exception.expectMessage(containsString("Unable to unassign user from his personal project")); updateProjectHandler.unassignUsers(project.getName(), AuthConstants.ADMINISTRATOR.getName(), rq); } }
package com.salesforce.storm.spout.sideline.kafka; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.salesforce.storm.spout.sideline.persistence.InMemoryPersistenceManager; import com.salesforce.storm.spout.sideline.persistence.PersistenceManager; import com.salesforce.storm.spout.sideline.utils.KafkaTestUtils; import com.salesforce.storm.spout.sideline.utils.ProducedKafkaRecord; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.Node; import org.apache.kafka.common.PartitionInfo; import org.apache.kafka.common.TopicPartition; import org.apache.storm.shade.com.google.common.base.Charsets; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.InOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyCollection; import static org.mockito.Matchers.anyList; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Validates that our SidelineConsumer works as we expect under various scenarios. */ public class SidelineConsumerTest { private static final Logger logger = LoggerFactory.getLogger(SidelineConsumerTest.class); private static KafkaTestServer kafkaTestServer; private String topicName; /** * Here we stand up an internal test kafka and zookeeper service. * Once for all methods in this class. */ @BeforeClass public static void setupKafkaServer() throws Exception { // Setup kafka test server kafkaTestServer = new KafkaTestServer(); kafkaTestServer.start(); } /** * This happens once before every test method. * Create a new empty topic with randomly generated name. */ @Before public void beforeTest() { // Generate topic name topicName = SidelineConsumerTest.class.getSimpleName() + Clock.systemUTC().millis(); // Create topic kafkaTestServer.createTopic(topicName); } /** * Here we shut down the internal test kafka and zookeeper services. */ @AfterClass public static void destroyKafkaServer() { // Close out kafka test server if needed if (kafkaTestServer == null) { return; } try { kafkaTestServer.shutdown(); } catch (Exception e) { throw new RuntimeException(e); } kafkaTestServer = null; } /** * Tests the constructor saves off instances of things passed into it properly. */ @Test public void testConstructor() { // Create config final SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(topicName); // Create instance of a StateConsumer, we'll just use a dummy instance. PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Call constructor SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); // Validate our instances got set assertNotNull("Config is not null", sidelineConsumer.getConsumerConfig()); assertEquals(config, sidelineConsumer.getConsumerConfig()); assertNotNull("PersistenceManager is not null", sidelineConsumer.getPersistenceManager()); assertEquals(persistenceManager, sidelineConsumer.getPersistenceManager()); } // TODO: these test cases // test calling connect twice throws exception. // test calling connect w/ a starting state. /** * Tests that our logic for flushing consumer state works if auto commit is enabled. * This is kind of a weak test for this. */ @Test public void testTimedFlushConsumerState() throws InterruptedException { final String expectedConsumerId = "MyConsumerId"; // Setup our config List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); final SidelineConsumerConfig config = new SidelineConsumerConfig(brokerHosts, expectedConsumerId, topicName); // Enable auto commit and Set timeout to 1 second. config.setConsumerStateAutoCommit(true); config.setConsumerStateAutoCommitIntervalMs(1000); // Create mock persistence manager so we can determine if it was called PersistenceManager mockPersistenceManager = mock(PersistenceManager.class); // Create a mock clock so we can control time (bwahaha) Instant instant = Clock.systemUTC().instant(); Clock mockClock = Clock.fixed(instant, ZoneId.systemDefault()); // Call constructor SidelineConsumer sidelineConsumer = new SidelineConsumer(config, mockPersistenceManager); sidelineConsumer.setClock(mockClock); // Call our method once sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer was not hit verify(mockPersistenceManager, never()).persistConsumerState(anyString(), anyObject()); // Sleep for 1.5 seconds Thread.sleep(1500); // Call our method again sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer was not hit because we're using a mocked clock that has not changed :p verify(mockPersistenceManager, never()).persistConsumerState(anyString(), anyObject()); // Now lets adjust our mock clock up by 2 seconds. instant = instant.plus(2000, ChronoUnit.MILLIS); mockClock = Clock.fixed(instant, ZoneId.systemDefault()); sidelineConsumer.setClock(mockClock); // Call our method again, it should have triggered this time. sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer WAS hit because we adjust our mock clock ahead 2 secs verify(mockPersistenceManager, times(1)).persistConsumerState(eq(expectedConsumerId), anyObject()); // Call our method again, it shouldn't fire. sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer was not hit again because we're using a mocked clock that has not changed since the last call :p verify(mockPersistenceManager, times(1)).persistConsumerState(anyString(), anyObject()); // Now lets adjust our mock clock up by 1.5 seconds. instant = instant.plus(1500, ChronoUnit.MILLIS); mockClock = Clock.fixed(instant, ZoneId.systemDefault()); sidelineConsumer.setClock(mockClock); // Call our method again, it should have triggered this time. sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer WAS hit a 2nd time because we adjust our mock clock ahead verify(mockPersistenceManager, times(2)).persistConsumerState(eq(expectedConsumerId), anyObject()); } /** * Tests that our logic for flushing consumer state is disabled if auto commit is disabled. * This is kind of a weak test for this. */ @Test public void testTimedFlushConsumerStateWhenAutoCommitIsDisabled() throws InterruptedException { // Create config final SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(topicName); // Disable and set interval to 1 second. config.setConsumerStateAutoCommit(false); config.setConsumerStateAutoCommitIntervalMs(1000); // Create mock persistence manager so we can determine if it was called PersistenceManager mockPersistenceManager = mock(PersistenceManager.class); // Create a mock clock so we can control time (bwahaha) Instant instant = Clock.systemUTC().instant(); Clock mockClock = Clock.fixed(instant, ZoneId.systemDefault()); // Call constructor SidelineConsumer sidelineConsumer = new SidelineConsumer(config, mockPersistenceManager); sidelineConsumer.setClock(mockClock); // Call our method once sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer was not hit verify(mockPersistenceManager, never()).persistConsumerState(anyString(), anyObject()); // Sleep for 1.5 seconds Thread.sleep(1500); // Call our method again sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer was not hit because we're using a mocked clock that has not changed :p verify(mockPersistenceManager, never()).persistConsumerState(anyString(), anyObject()); // Now lets adjust our mock clock up by 2 seconds. instant = instant.plus(2000, ChronoUnit.MILLIS); mockClock = Clock.fixed(instant, ZoneId.systemDefault()); sidelineConsumer.setClock(mockClock); // Call our method again, it should have triggered this time. sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer was not hit verify(mockPersistenceManager, never()).persistConsumerState(anyString(), anyObject()); // Call our method again, it shouldn't fire. sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer was not hit verify(mockPersistenceManager, never()).persistConsumerState(anyString(), anyObject()); // Now lets adjust our mock clock up by 1.5 seconds. instant = instant.plus(1500, ChronoUnit.MILLIS); mockClock = Clock.fixed(instant, ZoneId.systemDefault()); sidelineConsumer.setClock(mockClock); // Call our method again, it should have triggered this time. sidelineConsumer.timedFlushConsumerState(); // Make sure persistence layer was not hit verify(mockPersistenceManager, never()).persistConsumerState(anyString(), anyObject()); } /** * Verifies that when we call connect that it makes the appropriate calls * to ConsumerStateManager to initialize. * * This test has the ConsumerStateManager (a mock) return an empty ConsumerState. * We verify that our internal kafka client then knows to start reading every partition from * the earliest available offset. */ @Test public void testConnectWithSinglePartitionOnTopicWithNoStateSaved() { // Define our ConsumerId final String consumerId = "MyConsumerId"; // Create re-usable TopicPartition instance final TopicPartition partition0 = new TopicPartition(topicName, 0); // Define partition 0's earliest position at 1000L final long earliestPosition = 1000L; // Setup our config List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); final SidelineConsumerConfig config = new SidelineConsumerConfig(brokerHosts, consumerId, topicName); // Create mock KafkaConsumer instance KafkaConsumer<byte[], byte[]> mockKafkaConsumer = mock(KafkaConsumer.class); // When we call partitionsFor(), we should return a single partition number 0 for our topic. List<PartitionInfo> mockPartitionInfos = Lists.newArrayList(new PartitionInfo(topicName, 0, new Node(0, "localhost", 9092), new Node[0], new Node[0])); when(mockKafkaConsumer.partitionsFor(eq(topicName))).thenReturn(mockPartitionInfos); // When we ask for the position of partition 0, we should return 1000L when(mockKafkaConsumer.position(partition0)).thenReturn(earliestPosition); // Create instance of a StateConsumer, we'll just use a dummy instance. PersistenceManager mockPersistenceManager = mock(PersistenceManager.class); // When getState is called, return the following state final ConsumerState emptyConsumerState = ConsumerState.builder().build(); when(mockPersistenceManager.retrieveConsumerState(eq(consumerId))).thenReturn(emptyConsumerState); // Call constructor injecting our mocks SidelineConsumer sidelineConsumer = new SidelineConsumer(config, mockPersistenceManager, mockKafkaConsumer); // Now call open sidelineConsumer.open(null); // For every partition returned by mockKafkaConsumer.partitionsFor(), we should subscribe to them via the mockKafkaConsumer.assign() call verify(mockKafkaConsumer, times(1)).assign(eq(Lists.newArrayList(partition0))); // Since ConsumerStateManager has no state for partition 0, we should call seekToBeginning on that partition verify(mockKafkaConsumer, times(1)).seekToBeginning(eq(Lists.newArrayList(partition0))); // Verify position was asked for verify(mockKafkaConsumer, times(1)).position(partition0); // Verify ConsumerStateManager returns the correct values final ConsumerState currentState = sidelineConsumer.getCurrentState(); assertNotNull("Should be non-null", currentState); // State should have one entry assertEquals("Should have 1 entry", 1, currentState.size()); // Offset should have offset 1000L - 1 for completed offset. assertEquals("Expected value should be 999", (earliestPosition - 1), (long) currentState.getOffsetForTopicAndPartition(partition0)); } /** * Verifies that when we call connect that it makes the appropriate calls * to ConsumerStateManager to initialize. * * This test has the ConsumerStateManager (a mock) return an empty ConsumerState. * We verify that our internal kafka client then knows to start reading every partition from * the earliest available offset. */ @Test public void testConnectWithMultiplePartitionsOnTopicWithNoStateSaved() { // Define our ConsumerId final String consumerId = "MyConsumerId"; // Some re-usable TopicPartition objects final TopicPartition partition0 = new TopicPartition(topicName, 0); final TopicPartition partition1 = new TopicPartition(topicName, 1); final TopicPartition partition2 = new TopicPartition(topicName, 2); // Define earliest positions for each partition final long earliestPositionPartition0 = 1000L; final long earliestPositionPartition1 = 0L; final long earliestPositionPartition2 = 2324L; // Setup our config List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); final SidelineConsumerConfig config = new SidelineConsumerConfig(brokerHosts, consumerId, topicName); // Create mock KafkaConsumer instance KafkaConsumer<byte[], byte[]> mockKafkaConsumer = mock(KafkaConsumer.class); // When we call partitionsFor(), We return partitions 0,1, and 2. List<PartitionInfo> mockPartitionInfos = Lists.newArrayList( new PartitionInfo(topicName, 0, new Node(0, "localhost", 9092), new Node[0], new Node[0]), new PartitionInfo(topicName, 1, new Node(0, "localhost", 9092), new Node[0], new Node[0]), new PartitionInfo(topicName, 2, new Node(0, "localhost", 9092), new Node[0], new Node[0]) ); when(mockKafkaConsumer.partitionsFor(eq(topicName))).thenReturn(mockPartitionInfos); // Create instance of a PersistenceManager, we'll just use a dummy instance. PersistenceManager mockPersistenceManager = mock(PersistenceManager.class); // When getState is called, return the following state ConsumerState emptyConsumerState = ConsumerState.builder().build(); when(mockPersistenceManager.retrieveConsumerState(eq(consumerId))).thenReturn(emptyConsumerState); // When we ask for the positions for each partition return mocked values when(mockKafkaConsumer.position(partition0)).thenReturn(earliestPositionPartition0); when(mockKafkaConsumer.position(partition1)).thenReturn(earliestPositionPartition1); when(mockKafkaConsumer.position(partition2)).thenReturn(earliestPositionPartition2); // Call constructor injecting our mocks SidelineConsumer sidelineConsumer = new SidelineConsumer(config, mockPersistenceManager, mockKafkaConsumer); // Now call open sidelineConsumer.open(null); // For every partition returned by mockKafkaConsumer.partitionsFor(), we should subscribe to them via the mockKafkaConsumer.assign() call verify(mockKafkaConsumer, times(1)).assign(eq(Lists.newArrayList( new TopicPartition(topicName, 0), new TopicPartition(topicName, 1), new TopicPartition(topicName, 2)))); // Since ConsumerStateManager has no state for partition 0, we should call seekToBeginning on that partition verify(mockKafkaConsumer, times(1)).seekToBeginning(eq(Lists.newArrayList( new TopicPartition(topicName, 0), new TopicPartition(topicName, 1), new TopicPartition(topicName, 2)))); // Validate we got our calls for the current position verify(mockKafkaConsumer, times(1)).position(partition0); verify(mockKafkaConsumer, times(1)).position(partition1); verify(mockKafkaConsumer, times(1)).position(partition2); // Verify ConsumerStateManager returns the correct values final ConsumerState currentState = sidelineConsumer.getCurrentState(); assertNotNull("Should be non-null", currentState); // State should have one entry assertEquals("Should have 3 entries", 3, currentState.size()); // Offsets should be the earliest position - 1 assertEquals("Expected value for partition0", (earliestPositionPartition0 - 1), (long) currentState.getOffsetForTopicAndPartition(partition0)); assertEquals("Expected value for partition1", (earliestPositionPartition1 - 1), (long) currentState.getOffsetForTopicAndPartition(partition1)); assertEquals("Expected value for partition2", (earliestPositionPartition2 - 1), (long) currentState.getOffsetForTopicAndPartition(partition2)); } /** * Verifies that when we call connect that it makes the appropriate calls * to ConsumerStateManager to initialize. * * This test has the ConsumerStateManager (a mock) return ConsumerState. * We verify that our internal kafka client then knows to start reading its partition from the previously saved off * consumer state returned from ConsumerStateManager. */ @Test public void testConnectWithSinglePartitionOnTopicWithStateSaved() { // Define our ConsumerId and expected offset. final String consumerId = "MyConsumerId"; // Some re-usable TopicPartition objects final TopicPartition partition0 = new TopicPartition(topicName, 0); // This defines the last offset that was committed. final long lastCommittedOffset = 12345L; // This defines what offset we're expected to start consuming from, which should be the lastCommittedOffset + 1. final long expectedOffsetToStartConsumeFrom = lastCommittedOffset + 1; // Setup our config List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); final SidelineConsumerConfig config = new SidelineConsumerConfig(brokerHosts, consumerId, topicName); // Create mock KafkaConsumer instance KafkaConsumer<byte[], byte[]> mockKafkaConsumer = mock(KafkaConsumer.class); // When we call partitionsFor(), we should return a single partition number 0 for our topic. List<PartitionInfo> mockPartitionInfos = Lists.newArrayList(new PartitionInfo(topicName, 0, new Node(0, "localhost", 9092), new Node[0], new Node[0])); when(mockKafkaConsumer.partitionsFor(eq(topicName))).thenReturn(mockPartitionInfos); // Create instance of a StateConsumer, we'll just use a dummy instance. PersistenceManager mockPersistenceManager = mock(PersistenceManager.class); // When getState is called, return the following state final ConsumerState consumerState = ConsumerState .builder() .withPartition(new TopicPartition(topicName, 0), lastCommittedOffset) .build(); when(mockPersistenceManager.retrieveConsumerState(eq(consumerId))).thenReturn(consumerState); // Call constructor injecting our mocks SidelineConsumer sidelineConsumer = new SidelineConsumer(config, mockPersistenceManager, mockKafkaConsumer); // Now call open sidelineConsumer.open(null); // For every partition returned by mockKafkaConsumer.partitionsFor(), we should subscribe to them via the mockKafkaConsumer.assign() call verify(mockKafkaConsumer, times(1)).assign(eq(Lists.newArrayList(partition0))); // Since ConsumerStateManager has state for partition 0, we should NEVER call seekToBeginning on that partition // Or any partition really. verify(mockKafkaConsumer, never()).seekToBeginning(anyCollection()); // Instead since there is state, we should call seek on that partition verify(mockKafkaConsumer, times(1)).seek(eq(new TopicPartition(topicName, 0)), eq(expectedOffsetToStartConsumeFrom)); } /** * Verifies that when we call connect that it makes the appropriate calls * to ConsumerStateManager to initialize. * * This test has the ConsumerStateManager (a mock) return ConsumerState for every partition on the topic. * We verify that our internal kafka client then knows to start reading from the previously saved consumer state * offsets */ @Test public void testConnectWithMultiplePartitionsOnTopicWithAllPreviouslySavedState() { // Define our ConsumerId final String consumerId = "MyConsumerId"; // Define partitionTopics so we can re-use em final TopicPartition partition0 = new TopicPartition(topicName, 0); final TopicPartition partition1 = new TopicPartition(topicName, 1); final TopicPartition partition2 = new TopicPartition(topicName, 2); // Define last committed offsets per partition final long lastCommittedOffsetPartition0 = 1234L; final long lastCommittedOffsetPartition1 = 4321L; final long lastCommittedOffsetPartition2 = 1337L; // Define the offsets for each partition we expect the consumer to start consuming from, which should // be last committed offset + 1 final long expectedPartition0Offset = lastCommittedOffsetPartition0 + 1; final long expectedPartition1Offset = lastCommittedOffsetPartition1 + 1; final long expectedPartition2Offset = lastCommittedOffsetPartition2 + 1; // Setup our config List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); final SidelineConsumerConfig config = new SidelineConsumerConfig(brokerHosts, consumerId, topicName); // Create mock KafkaConsumer instance KafkaConsumer<byte[], byte[]> mockKafkaConsumer = mock(KafkaConsumer.class); // When we call partitionsFor(), We return partitions 0,1, and 2. List<PartitionInfo> mockPartitionInfos = Lists.newArrayList( new PartitionInfo(topicName, 0, new Node(0, "localhost", 9092), new Node[0], new Node[0]), new PartitionInfo(topicName, 1, new Node(0, "localhost", 9092), new Node[0], new Node[0]), new PartitionInfo(topicName, 2, new Node(0, "localhost", 9092), new Node[0], new Node[0]) ); when(mockKafkaConsumer.partitionsFor(eq(topicName))).thenReturn(mockPartitionInfos); // Create instance of a StateConsumer, we'll just use a dummy instance. PersistenceManager mockPersistenceManager = mock(PersistenceManager.class); // When getState is called, return the following state final ConsumerState consumerState = ConsumerState .builder() .withPartition(partition0, lastCommittedOffsetPartition0) .withPartition(partition1, lastCommittedOffsetPartition1) .withPartition(partition2, lastCommittedOffsetPartition2) .build(); when(mockPersistenceManager.retrieveConsumerState(eq(consumerId))).thenReturn(consumerState); // Call constructor injecting our mocks SidelineConsumer sidelineConsumer = new SidelineConsumer(config, mockPersistenceManager, mockKafkaConsumer); // Now call open sidelineConsumer.open(null); // For every partition returned by mockKafkaConsumer.partitionsFor(), we should subscribe to them via the mockKafkaConsumer.assign() call verify(mockKafkaConsumer, times(1)).assign(eq(Lists.newArrayList( partition0, partition1, partition2))); // Since ConsumerStateManager has state for all partitions, we should never call seekToBeginning on any partitions verify(mockKafkaConsumer, never()).seekToBeginning(anyList()); // Instead since there is state, we should call seek on each partition InOrder inOrderVerification = inOrder(mockKafkaConsumer); inOrderVerification.verify(mockKafkaConsumer, times(1)).seek(eq(partition0), eq(expectedPartition0Offset)); inOrderVerification.verify(mockKafkaConsumer, times(1)).seek(eq(partition1), eq(expectedPartition1Offset)); inOrderVerification.verify(mockKafkaConsumer, times(1)).seek(eq(partition2), eq(expectedPartition2Offset)); } /** * Verifies that when we call connect that it makes the appropriate calls * to ConsumerStateManager to initialize. * * This test has the ConsumerStateManager (a mock) return ConsumerState for every partition on the topic. * We verify that our internal kafka client then knows to start reading from the previously saved consumer state * offsets */ @Test public void testConnectWithMultiplePartitionsOnTopicWithSomePreviouslySavedState() { // Define our ConsumerId final String consumerId = "MyConsumerId"; // Define partitionTopics so we can re-use em final TopicPartition partition0 = new TopicPartition(topicName, 0); final TopicPartition partition1 = new TopicPartition(topicName, 1); final TopicPartition partition2 = new TopicPartition(topicName, 2); final TopicPartition partition3 = new TopicPartition(topicName, 3); // Define last committed offsets per partition, partitions 1 and 3 have no previously saved state. final long lastCommittedOffsetPartition0 = 1234L; final long lastCommittedOffsetPartition2 = 1337L; // Define what offsets we expect to start consuming from, which should be our last committed offset + 1 final long expectedPartition0Offset = lastCommittedOffsetPartition0 + 1; final long expectedPartition2Offset = lastCommittedOffsetPartition2 + 1; // Define earliest positions for partitions 1 and 3 final long earliestOffsetPartition1 = 444L; final long earliestOffsetPartition3 = 0L; // And the offsets we expect to see in our consumerState final long expectedStateOffsetPartition0 = lastCommittedOffsetPartition0; final long expectedStateOffsetPartition1 = earliestOffsetPartition1 - 1; final long expectedStateOffsetPartition2 = lastCommittedOffsetPartition2; final long expectedStateOffsetPartition3 = earliestOffsetPartition3 - 1; // Setup our config List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); final SidelineConsumerConfig config = new SidelineConsumerConfig(brokerHosts, consumerId, topicName); // Create mock KafkaConsumer instance KafkaConsumer<byte[], byte[]> mockKafkaConsumer = mock(KafkaConsumer.class); // When we call partitionsFor(), We return partitions 0,1,2,3 List<PartitionInfo> mockPartitionInfos = Lists.newArrayList( new PartitionInfo(topicName, 0, new Node(0, "localhost", 9092), new Node[0], new Node[0]), new PartitionInfo(topicName, 1, new Node(0, "localhost", 9092), new Node[0], new Node[0]), new PartitionInfo(topicName, 2, new Node(0, "localhost", 9092), new Node[0], new Node[0]), new PartitionInfo(topicName, 3, new Node(0, "localhost", 9092), new Node[0], new Node[0]) ); when(mockKafkaConsumer.partitionsFor(eq(topicName))).thenReturn(mockPartitionInfos); // Create instance of a StateConsumer, we'll just use a dummy instance. PersistenceManager mockPersistenceManager = mock(PersistenceManager.class); // When getState is called, return the following state for partitions 0 and 2. final ConsumerState consumerState = ConsumerState .builder() .withPartition(partition0, lastCommittedOffsetPartition0) .withPartition(partition2, lastCommittedOffsetPartition2) .build(); when(mockPersistenceManager.retrieveConsumerState(eq(consumerId))).thenReturn(consumerState); // Define values returned for partitions without state when(mockKafkaConsumer.position(partition1)).thenReturn(earliestOffsetPartition1); when(mockKafkaConsumer.position(partition3)).thenReturn(earliestOffsetPartition3); // Call constructor injecting our mocks SidelineConsumer sidelineConsumer = new SidelineConsumer(config, mockPersistenceManager, mockKafkaConsumer); // Now call open sidelineConsumer.open(null); // For every partition returned by mockKafkaConsumer.partitionsFor(), we should subscribe to them via the mockKafkaConsumer.assign() call verify(mockKafkaConsumer, times(1)).assign(eq(Lists.newArrayList( partition0, partition1, partition2, partition3))); // Since ConsumerStateManager has state for only 2 partitions, we should call seekToBeginning on partitions 1 and 3. verify(mockKafkaConsumer, times(1)).seekToBeginning(eq(Lists.newArrayList( partition1, partition3 ))); // Verify we asked for the positions for 2 unknown state partitions verify(mockKafkaConsumer, times(1)).position(partition1); verify(mockKafkaConsumer, times(1)).position(partition3); // For the partitions with state, we should call seek on each partition InOrder inOrderVerification = inOrder(mockKafkaConsumer); inOrderVerification.verify(mockKafkaConsumer, times(1)).seek(eq(partition0), eq(expectedPartition0Offset)); inOrderVerification.verify(mockKafkaConsumer, times(1)).seek(eq(partition2), eq(expectedPartition2Offset)); // Never seeked for partitions without any state verify(mockKafkaConsumer, never()).seek(eq(partition1), anyLong()); verify(mockKafkaConsumer, never()).seek(eq(partition3), anyLong()); // Now validate the consumer state final ConsumerState resultingConsumerState = sidelineConsumer.getCurrentState(); assertNotNull("Should be non-null", resultingConsumerState); // State should have one entry assertEquals("Should have 4 entries", 4, resultingConsumerState.size()); // Offsets should be set to what we expected. assertEquals("Expected value for partition0", expectedStateOffsetPartition0, (long) resultingConsumerState.getOffsetForTopicAndPartition(partition0)); assertEquals("Expected value for partition1", expectedStateOffsetPartition1, (long) resultingConsumerState.getOffsetForTopicAndPartition(partition1)); assertEquals("Expected value for partition2", expectedStateOffsetPartition2, (long) resultingConsumerState.getOffsetForTopicAndPartition(partition2)); assertEquals("Expected value for partition2", expectedStateOffsetPartition3, (long) resultingConsumerState.getOffsetForTopicAndPartition(partition3)); } /** * Tests that the getAssignedPartitions() works as we expect. * This test uses a topic with a single partition that we are subscribed to. */ @Test public void testGetAssignedPartitionsWithSinglePartition() { final int expectedPartitionId = 0; // Setup our config SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Ask the underlying consumer for our assigned partitions. Set<TopicPartition> assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate it assertNotNull("Should be non-null", assignedPartitions); assertFalse("Should not be empty", assignedPartitions.isEmpty()); assertEquals("Should contain 1 entry", 1, assignedPartitions.size()); assertTrue("Should contain our expected topic/partition", assignedPartitions.contains(new TopicPartition(topicName, expectedPartitionId))); } /** * Tests that the getAssignedPartitions() works as we expect. * This test uses a topic with a single partition that we are subscribed to. */ @Test public void testGetAssignedPartitionsWithMultiplePartitions() { // Define and create our topic final String expectedTopicName = "testGetAssignedPartitionsWithMultiplePartitions" + System.currentTimeMillis(); final int expectedNumberOfPartitions = 5; kafkaTestServer.createTopic(expectedTopicName, expectedNumberOfPartitions); // Setup our config SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(expectedTopicName); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Ask the underlying consumer for our assigned partitions. Set<TopicPartition> assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate it assertNotNull("Should be non-null", assignedPartitions); assertFalse("Should not be empty", assignedPartitions.isEmpty()); assertEquals("Should contain 5 entries", expectedNumberOfPartitions, assignedPartitions.size()); for (int x=0; x<expectedNumberOfPartitions; x++) { assertTrue("Should contain our expected topic/partition " + x, assignedPartitions.contains(new TopicPartition(expectedTopicName, x))); } } /** * Tests that the unsubscribeTopicPartition() works as we expect. * This test uses a topic with a single partition that we are subscribed to. */ @Test public void testUnsubscribeTopicPartitionSinglePartition() { // Define our expected topic/partition final TopicPartition expectedTopicPartition = new TopicPartition(topicName, 0); // Setup our config SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Ask the underlying consumer for our assigned partitions. Set<TopicPartition> assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate setup assertNotNull("Should be non-null", assignedPartitions); assertFalse("Should not be empty", assignedPartitions.isEmpty()); assertEquals("Should contain 1 entries", 1, assignedPartitions.size()); assertTrue("Should contain our expected topic/partition 0", assignedPartitions.contains(expectedTopicPartition)); // Now unsub from our topic partition final boolean result = sidelineConsumer.unsubscribeTopicPartition(expectedTopicPartition); assertTrue("Should have returned true", result); // Now ask for assigned partitions, should have none // Ask the underlying consumer for our assigned partitions. assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate setup assertNotNull("Should be non-null", assignedPartitions); assertTrue("Should be empty", assignedPartitions.isEmpty()); assertEquals("Should contain 0 entries", 0, assignedPartitions.size()); assertFalse("Should NOT contain our expected topic/partition 0", assignedPartitions.contains(expectedTopicPartition)); } /** * Tests that the unsubscribeTopicPartition() works as we expect. * This test uses a topic with multiple partitions that we are subscribed to. */ @Test public void testUnsubscribeTopicPartitionMultiplePartitions() { // Define and create our topic final String expectedTopicName = "testUnsubscribeTopicPartitionMultiplePartitions" + System.currentTimeMillis(); final int expectedNumberOfPartitions = 5; kafkaTestServer.createTopic(expectedTopicName, expectedNumberOfPartitions); // Setup our config SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(expectedTopicName); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Ask the underlying consumer for our assigned partitions. Set<TopicPartition> assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate setup assertNotNull("Should be non-null", assignedPartitions); assertFalse("Should not be empty", assignedPartitions.isEmpty()); assertEquals("Should contain entries", expectedNumberOfPartitions, assignedPartitions.size()); for (int x=0; x<expectedNumberOfPartitions; x++) { assertTrue("Should contain our expected topic/partition " + x, assignedPartitions.contains(new TopicPartition(expectedTopicName, x))); } // Now unsub from our topic partition final int expectedRemovePartition = 2; final TopicPartition toRemoveTopicPartition = new TopicPartition(expectedTopicName, expectedRemovePartition); final boolean result = sidelineConsumer.unsubscribeTopicPartition(toRemoveTopicPartition); assertTrue("Should have returned true", result); // Now ask for assigned partitions, should have none // Ask the underlying consumer for our assigned partitions. assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate setup assertNotNull("Should be non-null", assignedPartitions); assertFalse("Should be not empty", assignedPartitions.isEmpty()); assertEquals("Should contain entries", (expectedNumberOfPartitions - 1), assignedPartitions.size()); assertFalse("Should NOT contain our removed topic/partition 0", assignedPartitions.contains(toRemoveTopicPartition)); // Attempt to remove the same topicPartitionAgain, it should return false final boolean result2 = sidelineConsumer.unsubscribeTopicPartition(toRemoveTopicPartition); assertFalse("Should return false the second time", result2); // Now remove another topic/partition final int expectedRemovePartition2 = 4; final TopicPartition toRemoveTopicPartition2 = new TopicPartition(expectedTopicName, expectedRemovePartition2); final boolean result3 = sidelineConsumer.unsubscribeTopicPartition(toRemoveTopicPartition2); assertTrue("Should have returned true", result3); // Now ask for assigned partitions, should have none // Ask the underlying consumer for our assigned partitions. assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate setup assertNotNull("Should be non-null", assignedPartitions); assertFalse("Should be not empty", assignedPartitions.isEmpty()); assertEquals("Should contain entries", (expectedNumberOfPartitions - 2), assignedPartitions.size()); assertFalse("Should NOT contain our removed topic/partition 1", assignedPartitions.contains(toRemoveTopicPartition)); assertFalse("Should NOT contain our removed topic/partition 2", assignedPartitions.contains(toRemoveTopicPartition2)); } /** * We attempt to consume from the topic and get our expected messages. * We will NOT acknowledge any of the messages as being processed, so it should have no state saved. */ @Test public void testSimpleConsumeFromTopicWithNoStateSaved() { // Define how many records to produce final int numberOfRecordsToProduce = 5; // Produce 5 entries to the topic. final List<ProducedKafkaRecord<byte[], byte[]>> producedRecords = produceRecords(numberOfRecordsToProduce, 0); // Setup our config SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Read from topic, verify we get what we expect for (int x=0; x<numberOfRecordsToProduce; x++) { ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNotNull(foundRecord); // Compare to what we expected ProducedKafkaRecord<byte[], byte[]> expectedRecord = producedRecords.get(x); assertEquals("Found expected key", new String(expectedRecord.getKey(), Charsets.UTF_8), new String(foundRecord.key(), Charsets.UTF_8)); assertEquals("Found expected value", new String(expectedRecord.getValue(), Charsets.UTF_8), new String(foundRecord.value(), Charsets.UTF_8)); } // Next one should return null ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNull("Should have nothing new to consume and be null", foundRecord); // Close out consumer sidelineConsumer.close(); } /** * We attempt to consume from the topic and get our expected messages. * We ack the messages each as we get it, in order, one by one. */ @Test public void testSimpleConsumeFromTopicWithAckingInOrderOneByOne() { // Define how many records to produce final int numberOfRecordsToProduce = 5; // Define our topicPartition final TopicPartition partition0 = new TopicPartition(topicName, 0); // Produce 5 entries to the topic. final List<ProducedKafkaRecord<byte[], byte[]>> producedRecords = produceRecords(numberOfRecordsToProduce, 0); // Setup our config List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); SidelineConsumerConfig config = new SidelineConsumerConfig(brokerHosts, "MyConsumerId", topicName); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Read from topic, verify we get what we expect for (int x=0; x<numberOfRecordsToProduce; x++) { ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNotNull(foundRecord); // Compare to what we expected ProducedKafkaRecord<byte[], byte[]> expectedRecord = producedRecords.get(x); assertEquals("Found expected key", new String(expectedRecord.getKey(), Charsets.UTF_8), new String(foundRecord.key(), Charsets.UTF_8)); assertEquals("Found expected value", new String(expectedRecord.getValue(), Charsets.UTF_8), new String(foundRecord.value(), Charsets.UTF_8)); // Ack this message sidelineConsumer.commitOffset(foundRecord); // Verify it got updated to our current offset validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, foundRecord.offset()); } logger.info("Consumer State {}", sidelineConsumer.flushConsumerState()); // Close out consumer sidelineConsumer.close(); } /** * We attempt to consume from the topic and get our expected messages. * We ack the messages each as we get it, in order, one by one. */ @Test public void testSimpleConsumeFromTopicWithAckingInOrderAllAtTheEnd() { // Define how many records to produce final int numberOfRecordsToProduce = 5; // Define our topicPartition final TopicPartition partition0 = new TopicPartition(topicName, 0); // Produce 5 entries to the topic. final List<ProducedKafkaRecord<byte[], byte[]>> producedRecords = produceRecords(numberOfRecordsToProduce, 0); // Setup our config List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); SidelineConsumerConfig config = new SidelineConsumerConfig(brokerHosts, "MyConsumerId", topicName); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Read from topic, verify we get what we expect List<ConsumerRecord> foundRecords = Lists.newArrayList(); for (int x=0; x<numberOfRecordsToProduce; x++) { ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNotNull(foundRecord); foundRecords.add(foundRecord); // Compare to what we expected ProducedKafkaRecord<byte[], byte[]> expectedRecord = producedRecords.get(x); assertEquals("Found expected key", new String(expectedRecord.getKey(), Charsets.UTF_8), new String(foundRecord.key(), Charsets.UTF_8)); assertEquals("Found expected value", new String(expectedRecord.getValue(), Charsets.UTF_8), new String(foundRecord.value(), Charsets.UTF_8)); } logger.info("Consumer State {}", sidelineConsumer.flushConsumerState()); // Verify state is still -1 (meaning it hasn't acked/completed ANY offsets yet) validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, -1L); // Now ack them one by one for (ConsumerRecord foundRecord : foundRecords) { sidelineConsumer.commitOffset(foundRecord); } // Now validate state. ConsumerState consumerState = sidelineConsumer.flushConsumerState(); // Verify it got updated to our current offset validateConsumerState(consumerState, partition0, (numberOfRecordsToProduce - 1)); logger.info("Consumer State {}", sidelineConsumer.flushConsumerState()); // Close out consumer sidelineConsumer.close(); } /** * We attempt to consume from the topic and get our expected messages. * We ack the messages each as we get it, in order, one by one. */ @Test public void testSimpleConsumeFromTopicWithAckingOutOfOrderAllAtTheEnd() { // Define how many records to produce final int numberOfRecordsToProduce = 9; // Define our topic/partition. final TopicPartition partition0 = new TopicPartition(topicName, 0); // Produce 5 entries to the topic. final List<ProducedKafkaRecord<byte[], byte[]>> producedRecords = produceRecords(numberOfRecordsToProduce, 0); // Setup our config List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); SidelineConsumerConfig config = new SidelineConsumerConfig(brokerHosts, "MyConsumerId", topicName); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Read from topic, verify we get what we expect List<ConsumerRecord> foundRecords = Lists.newArrayList(); for (int x=0; x<numberOfRecordsToProduce; x++) { ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNotNull(foundRecord); foundRecords.add(foundRecord); // Compare to what we expected ProducedKafkaRecord<byte[], byte[]> expectedRecord = producedRecords.get(x); assertEquals("Found expected key", new String(expectedRecord.getKey(), Charsets.UTF_8), new String(foundRecord.key(), Charsets.UTF_8)); assertEquals("Found expected value", new String(expectedRecord.getValue(), Charsets.UTF_8), new String(foundRecord.value(), Charsets.UTF_8)); } logger.info("Consumer State {}", sidelineConsumer.flushConsumerState()); // Verify state is still -1 (meaning it hasn't acked/completed ANY offsets yet) validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, -1L); // Now ack in the following order: // commit offset 2 => offset should be 0 still sidelineConsumer.commitOffset(partition0, 2L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, -1L); // commit offset 1 => offset should be 0 still sidelineConsumer.commitOffset(partition0, 1L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, -1L); // commit offset 0 => offset should be 2 now sidelineConsumer.commitOffset(partition0, 0L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 2L); // commit offset 3 => offset should be 3 now sidelineConsumer.commitOffset(partition0, 3L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 3L); // commit offset 4 => offset should be 4 now sidelineConsumer.commitOffset(partition0, 4L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 4L); // commit offset 5 => offset should be 5 now sidelineConsumer.commitOffset(partition0, 5L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 5L); // commit offset 7 => offset should be 5 still sidelineConsumer.commitOffset(partition0, 7L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 5L); // commit offset 8 => offset should be 5 still sidelineConsumer.commitOffset(partition0, 8L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 5L); // commit offset 6 => offset should be 8 now sidelineConsumer.commitOffset(partition0, 6L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 8L); // Now validate state. logger.info("Consumer State {}", sidelineConsumer.flushConsumerState()); // Close out consumer sidelineConsumer.close(); } /** * Produce 10 messages into a kafka topic: offsets [0-9] * Setup our SidelineConsumer such that its pre-existing state says to start at offset 4 * Consume using the SidelineConsumer, verify we only get the last 5 messages back. */ @Test public void testConsumerWithInitialStateToSkipMessages() { // Define how many records to produce final int numberOfRecordsToProduce = 10; // Define how many records we expect to consumer final int numberOfRecordsToConsume = 5; // Produce entries to the topic. final List<ProducedKafkaRecord<byte[], byte[]>> producedRecords = produceRecords(numberOfRecordsToProduce, 0); // Create a list of the records we expect to get back from the consumer, this should be the last 5 entries. List<ProducedKafkaRecord<byte[], byte[]>> expectedProducedRecords = producedRecords.subList(5,10); // Setup our config SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create a state in which we have already acked the first 5 messages // 5 first msgs marked completed (0,1,2,3,4) = Committed Offset = 4. final ConsumerState consumerState = ConsumerState.builder() .withPartition(new TopicPartition(topicName, 0), 4L) .build(); persistenceManager.persistConsumerState(config.getConsumerId(), consumerState); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Read from topic, verify we get what we expect, we should only get the last 5 records. for (int x=numberOfRecordsToConsume; x<numberOfRecordsToProduce; x++) { ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNotNull(foundRecord); // Compare to what we expected ProducedKafkaRecord<byte[], byte[]> expectedRecord = producedRecords.get(x); logger.info("Expected {} Actual {}", expectedRecord.getKey(), foundRecord.key()); assertEquals("Found expected key", new String(expectedRecord.getKey(), Charsets.UTF_8), new String(foundRecord.key(), Charsets.UTF_8)); assertEquals("Found expected value", new String(expectedRecord.getValue(), Charsets.UTF_8), new String(foundRecord.value(), Charsets.UTF_8)); } // Additional calls to nextRecord() should return null for (int x=0; x<2; x++) { ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNull("Should have nothing new to consume and be null", foundRecord); } // Close out consumer sidelineConsumer.close(); } /** * 1. Setup a consumer to consume from a topic with 2 partitions. * 2. Produce several messages into both partitions * 3. Consume all of the msgs from the topic. * 4. Ack in various orders for the msgs * 5. Validate that the state is correct. */ @Test public void testConsumeFromTopicWithMultiplePartitionsWithAcking() { this.topicName = "testConsumeFromTopicWithMultiplePartitionsWithAcking" + System.currentTimeMillis(); final int expectedNumberOfPartitions = 2; // Create our multi-partition topic. kafkaTestServer.createTopic(topicName, expectedNumberOfPartitions); // Define our expected topic/partitions final TopicPartition partition0 = new TopicPartition(topicName, 0); final TopicPartition partition1 = new TopicPartition(topicName, 1); // Setup our config SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(topicName); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Ask the underlying consumer for our assigned partitions. Set<TopicPartition> assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate setup assertNotNull("Should be non-null", assignedPartitions); assertFalse("Should not be empty", assignedPartitions.isEmpty()); assertEquals("Should contain 2 entries", expectedNumberOfPartitions, assignedPartitions.size()); assertTrue("Should contain our expected topic/partition 0", assignedPartitions.contains(partition0)); assertTrue("Should contain our expected topic/partition 1", assignedPartitions.contains(partition1)); // Now produce 5 msgs to each topic (10 msgs total) final int expectedNumberOfMsgsPerPartition = 5; List<ProducedKafkaRecord<byte[], byte[]>> producedRecordsPartition0 = produceRecords(expectedNumberOfMsgsPerPartition, 0); List<ProducedKafkaRecord<byte[], byte[]>> producedRecordsPartition1 = produceRecords(expectedNumberOfMsgsPerPartition, 1); // Attempt to consume them // Read from topic, verify we get what we expect int partition0Index = 0; int partition1Index = 0; for (int x=0; x<(expectedNumberOfMsgsPerPartition * 2); x++) { ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNotNull(foundRecord); // Determine which partition its from final int partitionSource = foundRecord.partition(); assertTrue("Should be partition 0 or 1", partitionSource == 0 || partitionSource == 1); ProducedKafkaRecord<byte[], byte[]> expectedRecord; if (partitionSource == 0) { expectedRecord = producedRecordsPartition0.get(partition0Index); partition0Index++; } else { expectedRecord = producedRecordsPartition1.get(partition1Index); partition1Index++; } // Compare to what we expected logger.info("Expected {} Actual {}", expectedRecord.getKey(), foundRecord.key()); assertEquals("Found expected key", new String(expectedRecord.getKey(), Charsets.UTF_8), new String(foundRecord.key(), Charsets.UTF_8)); assertEquals("Found expected value", new String(expectedRecord.getValue(), Charsets.UTF_8), new String(foundRecord.value(), Charsets.UTF_8)); } // Next one should return null ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNull("Should have nothing new to consume and be null", foundRecord); logger.info("Consumer State {}", sidelineConsumer.flushConsumerState()); // Verify state is still -1 for partition 0, meaning not acked offsets yet, validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, -1L); // Verify state is still -1 for partition 1, meaning not acked offsets yet, validateConsumerState(sidelineConsumer.flushConsumerState(), partition1, -1L); // Ack offset 1 on partition 0, state should be: [partition0: -1, partition1: -1] sidelineConsumer.commitOffset(partition0, 1L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, -1L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition1, -1L); // Ack offset 0 on partition 0, state should be: [partition0: 1, partition1: -1] sidelineConsumer.commitOffset(partition0, 0L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 1L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition1, -1L); // Ack offset 2 on partition 0, state should be: [partition0: 2, partition1: -1] sidelineConsumer.commitOffset(partition0, 2L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 2L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition1, -1L); // Ack offset 0 on partition 1, state should be: [partition0: 2, partition1: 0] sidelineConsumer.commitOffset(partition1, 0L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 2L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition1, 0L); // Ack offset 2 on partition 1, state should be: [partition0: 2, partition1: 0] sidelineConsumer.commitOffset(partition1, 2L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 2L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition1, 0L); // Ack offset 0 on partition 1, state should be: [partition0: 2, partition1: 0] sidelineConsumer.commitOffset(partition1, 0L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 2L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition1, 0L); // Ack offset 1 on partition 1, state should be: [partition0: 2, partition1: 2] sidelineConsumer.commitOffset(partition1, 1L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 2L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition1, 2L); // Ack offset 3 on partition 1, state should be: [partition0: 2, partition1: 3] sidelineConsumer.commitOffset(partition1, 3L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition0, 2L); validateConsumerState(sidelineConsumer.flushConsumerState(), partition1, 3L); // Close out consumer sidelineConsumer.close(); } /** * 1. Setup a consumer to consume from a topic with 1 partition. * 2. Produce several messages into that partition. * 3. Consume all of the msgs from the topic. * 4. Produce more msgs into the topic. * 5. Unsubscribe from that partition. * 6. Attempt to consume more msgs, verify none are found. */ @Test public void testConsumeFromTopicAfterUnsubscribingFromSinglePartition() { // Define our expected topic/partition final TopicPartition expectedTopicPartition = new TopicPartition(topicName, 0); // Setup our config SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Ask the underlying consumer for our assigned partitions. Set<TopicPartition> assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate setup assertNotNull("Should be non-null", assignedPartitions); assertFalse("Should not be empty", assignedPartitions.isEmpty()); assertEquals("Should contain 1 entries", 1, assignedPartitions.size()); assertTrue("Should contain our expected topic/partition 0", assignedPartitions.contains(expectedTopicPartition)); // Now produce 5 msgs final int expectedNumberOfMsgs = 5; List<ProducedKafkaRecord<byte[], byte[]>> producedRecords = produceRecords(expectedNumberOfMsgs, 0); // Attempt to consume them // Read from topic, verify we get what we expect for (int x=0; x<expectedNumberOfMsgs; x++) { ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNotNull(foundRecord); // Compare to what we expected ProducedKafkaRecord<byte[], byte[]> expectedRecord = producedRecords.get(x); logger.info("Expected {} Actual {}", expectedRecord.getKey(), foundRecord.key()); assertEquals("Found expected key", new String(expectedRecord.getKey(), Charsets.UTF_8), new String(foundRecord.key(), Charsets.UTF_8)); assertEquals("Found expected value", new String(expectedRecord.getValue(), Charsets.UTF_8), new String(foundRecord.value(), Charsets.UTF_8)); } // Next one should return null ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNull("Should have nothing new to consume and be null", foundRecord); // Now produce 5 more msgs producedRecords = produceRecords(expectedNumberOfMsgs, 0); // Now unsub from the partition final boolean result = sidelineConsumer.unsubscribeTopicPartition(expectedTopicPartition); assertTrue("Should be true", result); // Attempt to consume, but nothing should be returned, because we unsubscribed. for (int x=0; x<expectedNumberOfMsgs; x++) { foundRecord = sidelineConsumer.nextRecord(); assertNull(foundRecord); } // Close out consumer sidelineConsumer.close(); } /** * 1. Setup a consumer to consume from a topic with 2 partitions. * 2. Produce several messages into both partitions * 3. Consume all of the msgs from the topic. * 4. Produce more msgs into both partitions. * 5. Unsubscribe from partition 0. * 6. Attempt to consume more msgs, verify only those from partition 1 come through. */ @Test public void testConsumeFromTopicAfterUnsubscribingFromMultiplePartitions() { this.topicName = "testConsumeFromTopicAfterUnsubscribingFromMultiplePartitions" + System.currentTimeMillis(); final int expectedNumberOfPartitions = 2; // Create our multi-partition topic. kafkaTestServer.createTopic(topicName, expectedNumberOfPartitions); // Define our expected topic/partitions final TopicPartition expectedTopicPartition0 = new TopicPartition(topicName, 0); final TopicPartition expectedTopicPartition1 = new TopicPartition(topicName, 1); // Setup our config SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(topicName); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(null); // Ask the underlying consumer for our assigned partitions. Set<TopicPartition> assignedPartitions = sidelineConsumer.getAssignedPartitions(); logger.info("Assigned partitions: {}", assignedPartitions); // Validate setup assertNotNull("Should be non-null", assignedPartitions); assertFalse("Should not be empty", assignedPartitions.isEmpty()); assertEquals("Should contain 2 entries", expectedNumberOfPartitions, assignedPartitions.size()); assertTrue("Should contain our expected topic/partition 0", assignedPartitions.contains(expectedTopicPartition0)); assertTrue("Should contain our expected topic/partition 1", assignedPartitions.contains(expectedTopicPartition1)); // Now produce 5 msgs to each topic (10 msgs total) final int expectedNumberOfMsgsPerPartition = 5; List<ProducedKafkaRecord<byte[], byte[]>> producedRecordsPartition0 = produceRecords(expectedNumberOfMsgsPerPartition, 0); List<ProducedKafkaRecord<byte[], byte[]>> producedRecordsPartition1 = produceRecords(expectedNumberOfMsgsPerPartition, 1); // Attempt to consume them // Read from topic, verify we get what we expect int partition0Index = 0; int partition1Index = 0; for (int x=0; x<(expectedNumberOfMsgsPerPartition * 2); x++) { ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNotNull(foundRecord); // Determine which partition its from final int partitionSource = foundRecord.partition(); assertTrue("Should be partition 0 or 1", partitionSource == 0 || partitionSource == 1); ProducedKafkaRecord<byte[], byte[]> expectedRecord; if (partitionSource == 0) { expectedRecord = producedRecordsPartition0.get(partition0Index); partition0Index++; } else { expectedRecord = producedRecordsPartition1.get(partition1Index); partition1Index++; } // Compare to what we expected logger.info("Expected {} Actual {}", expectedRecord.getKey(), foundRecord.key()); assertEquals("Found expected key", new String(expectedRecord.getKey(), Charsets.UTF_8), new String(foundRecord.key(), Charsets.UTF_8)); assertEquals("Found expected value", new String(expectedRecord.getValue(), Charsets.UTF_8), new String(foundRecord.value(), Charsets.UTF_8)); } // Next one should return null ConsumerRecord<byte[], byte[]> foundRecord = sidelineConsumer.nextRecord(); assertNull("Should have nothing new to consume and be null", foundRecord); // Now produce 5 more msgs into each partition producedRecordsPartition0 = produceRecords(expectedNumberOfMsgsPerPartition, 0); producedRecordsPartition1 = produceRecords(expectedNumberOfMsgsPerPartition, 1); // Now unsub from the partition 0 final boolean result = sidelineConsumer.unsubscribeTopicPartition(expectedTopicPartition0); assertTrue("Should be true", result); // Attempt to consume, but nothing should be returned from partition 0, only partition 1 for (int x=0; x<expectedNumberOfMsgsPerPartition; x++) { foundRecord = sidelineConsumer.nextRecord(); assertNotNull(foundRecord); // Determine which partition its from, should be only 1 assertEquals("Should be partition 1", 1, foundRecord.partition()); // Validate it ProducedKafkaRecord<byte[], byte[]> expectedRecord = producedRecordsPartition1.get(x); // Compare to what we expected logger.info("Expected {} Actual {}", expectedRecord.getKey(), foundRecord.key()); assertEquals("Found expected key", new String(expectedRecord.getKey(), Charsets.UTF_8), new String(foundRecord.key(), Charsets.UTF_8)); assertEquals("Found expected value", new String(expectedRecord.getValue(), Charsets.UTF_8), new String(foundRecord.value(), Charsets.UTF_8)); } // Next one should return null foundRecord = sidelineConsumer.nextRecord(); assertNull("Should have nothing new to consume and be null", foundRecord); // Close out consumer sidelineConsumer.close(); } /** * This tests what happens if we ask to consume from an offset that is invalid (does not exist). * Here's what we setup: * * 2 partitions, produce 4 messages into each. * * Start a consumer, asking to start at: * offset 2 for partition 1, (recorded completed offset = 1) * offset 21 for partition 2. (recorded completed offset = 20) * * Offset 20 does not exist for partition 2, this will raise an exception which * by the underlying kafka consumer. This exception should be handled internally * resetting the offset on partition 2 to the earliest available (which happens to be 0). * * We then consume and expect to receive messages: * partition 0 -> messages 2,3 (because we started at offset 2) * partition 1 -> messages 0,1,2,3 (because we got reset to earliest) * * This test also validates that for non-reset partitions, that it does not lose * any messages. */ @Test public void testWhatHappensIfOffsetIsInvalidShouldResetSmallest() { // Kafka topic setup this.topicName = "testWhatHappensIfOffsetIsInvalidShouldResetSmallest" + System.currentTimeMillis(); final int numberOfPartitions = 2; final int numberOfMsgsPerPartition = 4; // How many msgs we should expect, 2 for partition 0, 4 from partition1 final int numberOfExpectedMessages = 6; // Define starting offsets for partitions final long partition0StartingOffset = 1L; final long partition1StartingOffset = 20L; // Create our multi-partition topic. kafkaTestServer.createTopic(topicName, numberOfPartitions); // Define our expected topic/partitions final TopicPartition expectedTopicPartition0 = new TopicPartition(topicName, 0); final TopicPartition expectedTopicPartition1 = new TopicPartition(topicName, 1); // Produce messages into both topics produceRecords(numberOfMsgsPerPartition, 0); produceRecords(numberOfMsgsPerPartition, 1); // Setup our config set to reset to none // We should handle this internally now. SidelineConsumerConfig config = getDefaultSidelineConsumerConfig(topicName); // Create our Persistence Manager PersistenceManager persistenceManager = new InMemoryPersistenceManager(); persistenceManager.open(Maps.newHashMap()); // Create starting state final ConsumerState startingState = ConsumerState.builder() .withPartition(expectedTopicPartition0, partition0StartingOffset) .withPartition(expectedTopicPartition1, partition1StartingOffset) .build(); // Create our consumer SidelineConsumer sidelineConsumer = new SidelineConsumer(config, persistenceManager); sidelineConsumer.open(startingState); // Define the values we expect to get // Ugh this is hacky, whatever final Set<String> expectedValues = Sets.newHashSet( // Partition 0 should not skip any messages! "partition0-offset2", "partition0-offset3", // Partition 1 should get reset to offset 0 "partition1-offset0", "partition1-offset1", "partition1-offset2", "partition1-offset3" ); List<ConsumerRecord> records = Lists.newArrayList(); ConsumerRecord consumerRecord; do { consumerRecord = sidelineConsumer.nextRecord(); if (consumerRecord != null) { logger.info("Found offset {} on {}", consumerRecord.offset(), consumerRecord.partition()); records.add(consumerRecord); // Remove from our expected set expectedValues.remove("partition" + consumerRecord.partition() + "-offset" + consumerRecord.offset()); } } while (consumerRecord != null); // Now do validation logger.info("Found {} msgs", records.size()); assertEquals("Should have 6 messages from kafka", numberOfExpectedMessages, records.size()); assertTrue("Expected set should now be empty, we found everything", expectedValues.isEmpty()); // Call nextRecord 2 more times, both should be null for (int x=0; x<2; x++) { assertNull("Should be null", sidelineConsumer.nextRecord()); } } /** * Helper method * @param consumerState - the consumer state we want to validate * @param topicPartition - the topic/partition we want to validate * @param expectedOffset - the offset we expect */ private void validateConsumerState(ConsumerState consumerState, TopicPartition topicPartition, long expectedOffset) { final long actualOffset = consumerState.getOffsetForTopicAndPartition(topicPartition); assertEquals("Expected offset", expectedOffset, actualOffset); } /** * helper method to produce records into kafka. */ private List<ProducedKafkaRecord<byte[], byte[]>> produceRecords(final int numberOfRecords, final int partitionId) { KafkaTestUtils kafkaTestUtils = new KafkaTestUtils(kafkaTestServer); return kafkaTestUtils.produceRecords(numberOfRecords, topicName, partitionId); } private SidelineConsumerConfig getDefaultSidelineConsumerConfig() { return getDefaultSidelineConsumerConfig(topicName); } private SidelineConsumerConfig getDefaultSidelineConsumerConfig(final String topicName) { List<String> brokerHosts = Lists.newArrayList(kafkaTestServer.getKafkaServer().serverConfig().advertisedHostName() + ":" + kafkaTestServer.getKafkaServer().serverConfig().advertisedPort()); return new SidelineConsumerConfig(brokerHosts, "MyConsumerId", topicName); } }
// DataTools.java package loci.common; import java.io.ByteArrayInputStream; import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.IOException; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public final class DataTools { // -- Constants -- /** Timestamp formats. */ public static final int UNIX = 0; // January 1, 1970 public static final int COBOL = 1; // January 1, 1601 public static final int MICROSOFT = 2; // December 30, 1899 public static final int ZVI = 3; /** Milliseconds until UNIX epoch. */ public static final long UNIX_EPOCH = 0; public static final long COBOL_EPOCH = 11644444800000L; public static final long MICROSOFT_EPOCH = 2272060800000L; public static final long ZVI_EPOCH = 2921084975759000L; /** ISO 8601 date format string. */ public static final String ISO8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; /** Factory for generating SAX parsers. */ public static final SAXParserFactory SAX_FACTORY = SAXParserFactory.newInstance(); // -- Static fields -- /** * Persistent byte array for calling * {@link java.io.DataInput#readFully(byte[], int, int)} efficiently. */ private static ThreadLocal eightBytes = new ThreadLocal() { protected synchronized Object initialValue() { return new byte[8]; } }; // -- Constructor -- private DataTools() { } // -- Data reading -- /** Reads 1 signed byte [-128, 127]. */ public static byte readSignedByte(DataInput in) throws IOException { byte[] b = (byte[]) eightBytes.get(); in.readFully(b, 0, 1); return b[0]; } /** Reads 1 unsigned byte [0, 255]. */ public static short readUnsignedByte(DataInput in) throws IOException { short q = readSignedByte(in); if (q < 0) q += 256; return q; } /** Reads 2 signed bytes [-32768, 32767]. */ public static short read2SignedBytes(DataInput in, boolean little) throws IOException { byte[] b = (byte[]) eightBytes.get(); in.readFully(b, 0, 2); return bytesToShort(b, little); } /** Reads 2 unsigned bytes [0, 65535]. */ public static int read2UnsignedBytes(DataInput in, boolean little) throws IOException { int q = read2SignedBytes(in, little); if (q < 0) q += 65536; return q; } /** Reads 4 signed bytes [-2147483648, 2147483647]. */ public static int read4SignedBytes(DataInput in, boolean little) throws IOException { byte[] b = (byte[]) eightBytes.get(); in.readFully(b, 0, 4); return bytesToInt(b, little); } /** Reads 4 unsigned bytes [0, 4294967296]. */ public static long read4UnsignedBytes(DataInput in, boolean little) throws IOException { long q = read4SignedBytes(in, little); if (q < 0) q += 4294967296L; return q; } /** Reads 8 signed bytes [-9223372036854775808, 9223372036854775807]. */ public static long read8SignedBytes(DataInput in, boolean little) throws IOException { byte[] b = (byte[]) eightBytes.get(); in.readFully(b, 0, 8); return bytesToLong(b, little); } /** Reads 4 bytes in single precision IEEE format. */ public static float readFloat(DataInput in, boolean little) throws IOException { return Float.intBitsToFloat(read4SignedBytes(in, little)); } /** Reads 8 bytes in double precision IEEE format. */ public static double readDouble(DataInput in, boolean little) throws IOException { return Double.longBitsToDouble(read8SignedBytes(in, little)); } // -- Data writing -- /** Writes a string to the given data output destination. */ public static void writeString(DataOutput out, String s) throws IOException { byte[] b = s.getBytes("UTF-8"); out.write(b); } /** Writes a double to the given data output destination. */ public static void writeDouble(DataOutput out, double v, boolean little) throws IOException { writeLong(out, Double.doubleToLongBits(v), little); } /** Writes a long to the given data output destination. */ public static void writeLong(DataOutput out, long v, boolean little) throws IOException { for (int i=0; i<8; i++) { int shift = little ? i * 8 : 64 - (i + 1) * 8; out.write((int) ((v >>> shift) & 0xff)); } } /** Writes a float to the given data output destination. */ public static void writeFloat(DataOutput out, float v, boolean little) throws IOException { writeInt(out, Float.floatToIntBits(v), little); } /** Writes an integer to the given data output destination. */ public static void writeInt(DataOutput out, int v, boolean little) throws IOException { for (int i=0; i<4; i++) { int shift = little ? i * 8 : 32 - (i + 1) * 8; out.write((int) ((v >>> shift) & 0xff)); } } /** Writes a short to the given data output destination. */ public static void writeShort(DataOutput out, int v, boolean little) throws IOException { for (int i=0; i<2; i++) { int shift = little ? i * 8 : 16 - (i + 1) * 8; out.write((int) ((v >>> shift) & 0xff)); } } // -- Word decoding -- /** * Translates up to the first len bytes of a byte array beyond the given * offset to a short. If there are fewer than 2 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static short bytesToShort(byte[] bytes, int off, int len, boolean little) { if (bytes.length - off < len) len = bytes.length - off; short total = 0; for (int i=0, ndx=off; i<len; i++, ndx++) { total |= (bytes[ndx] < 0 ? 256 + bytes[ndx] : (int) bytes[ndx]) << ((little ? i : len - i - 1) * 8); } return total; } /** * Translates up to the first 2 bytes of a byte array beyond the given * offset to a short. If there are fewer than 2 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static short bytesToShort(byte[] bytes, int off, boolean little) { return bytesToShort(bytes, off, 2, little); } /** * Translates up to the first 2 bytes of a byte array to a short. * If there are fewer than 2 bytes in the array, the MSBs are all * assumed to be zero (regardless of endianness). */ public static short bytesToShort(byte[] bytes, boolean little) { return bytesToShort(bytes, 0, 2, little); } /** * Translates up to the first len bytes of a byte array byond the given * offset to a short. If there are fewer than 2 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static short bytesToShort(short[] bytes, int off, int len, boolean little) { if (bytes.length - off < len) len = bytes.length - off; short total = 0; for (int i=0, ndx=off; i<len; i++, ndx++) { total |= ((int) bytes[ndx]) << ((little ? i : len - i - 1) * 8); } return total; } /** * Translates up to the first 2 bytes of a byte array byond the given * offset to a short. If there are fewer than 2 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static short bytesToShort(short[] bytes, int off, boolean little) { return bytesToShort(bytes, off, 2, little); } /** * Translates up to the first 2 bytes of a byte array to a short. * If there are fewer than 2 bytes in the array, the MSBs are all * assumed to be zero (regardless of endianness). */ public static short bytesToShort(short[] bytes, boolean little) { return bytesToShort(bytes, 0, 2, little); } /** * Translates up to the first len bytes of a byte array beyond the given * offset to an int. If there are fewer than 4 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static int bytesToInt(byte[] bytes, int off, int len, boolean little) { if (bytes.length - off < len) len = bytes.length - off; int total = 0; for (int i=0, ndx=off; i<len; i++, ndx++) { total |= (bytes[ndx] < 0 ? 256 + bytes[ndx] : (int) bytes[ndx]) << ((little ? i : len - i - 1) * 8); } return total; } /** * Translates up to the first 4 bytes of a byte array beyond the given * offset to an int. If there are fewer than 4 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static int bytesToInt(byte[] bytes, int off, boolean little) { return bytesToInt(bytes, off, 4, little); } /** * Translates up to the first 4 bytes of a byte array to an int. * If there are fewer than 4 bytes in the array, the MSBs are all * assumed to be zero (regardless of endianness). */ public static int bytesToInt(byte[] bytes, boolean little) { return bytesToInt(bytes, 0, 4, little); } /** * Translates up to the first len bytes of a byte array beyond the given * offset to an int. If there are fewer than 4 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static int bytesToInt(short[] bytes, int off, int len, boolean little) { if (bytes.length - off < len) len = bytes.length - off; int total = 0; for (int i=0, ndx=off; i<len; i++, ndx++) { total |= ((int) bytes[ndx]) << ((little ? i : len - i - 1) * 8); } return total; } /** * Translates up to the first 4 bytes of a byte array beyond the given * offset to an int. If there are fewer than 4 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static int bytesToInt(short[] bytes, int off, boolean little) { return bytesToInt(bytes, off, 4, little); } /** * Translates up to the first 4 bytes of a byte array to an int. * If there are fewer than 4 bytes in the array, the MSBs are all * assumed to be zero (regardless of endianness). */ public static int bytesToInt(short[] bytes, boolean little) { return bytesToInt(bytes, 0, 4, little); } /** * Translates up to the first 4 bytes of a byte array to a float. * If there are fewer than 4 bytes in the array, the MSBs are all * assumed to be zero (regardless of endianness). */ public static float bytesToFloat(byte[] bytes, int off, int len, boolean little) { return Float.intBitsToFloat(bytesToInt(bytes, off, len, little)); } /** * Translates up to the first len bytes of a byte array beyond the given * offset to a long. If there are fewer than 8 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static long bytesToLong(byte[] bytes, int off, int len, boolean little) { if (bytes.length - off < len) len = bytes.length - off; long total = 0; for (int i=0, ndx=off; i<len; i++, ndx++) { total |= (bytes[ndx] < 0 ? 256L + bytes[ndx] : (long) bytes[ndx]) << ((little ? i : len - i - 1) * 8); } return total; } /** * Translates up to the first 8 bytes of a byte array beyond the given * offset to a long. If there are fewer than 8 bytes in the array, * the MSBs are all assumed to be zero (regardless of endianness). */ public static long bytesToLong(byte[] bytes, int off, boolean little) { return bytesToLong(bytes, off, 8, little); } /** * Translates up to the first 8 bytes of a byte array to a long. * If there are fewer than 8 bytes in the array, the MSBs are all * assumed to be zero (regardless of endianness). */ public static long bytesToLong(byte[] bytes, boolean little) { return bytesToLong(bytes, 0, 8, little); } /** * Translates up to the first len bytes of a byte array beyond the given * offset to a long. If there are fewer than 8 bytes to be translated, * the MSBs are all assumed to be zero (regardless of endianness). */ public static long bytesToLong(short[] bytes, int off, int len, boolean little) { if (bytes.length - off < len) len = bytes.length - off; long total = 0; for (int i=0, ndx=off; i<len; i++, ndx++) { total |= ((long) bytes[ndx]) << ((little ? i : len - i - 1) * 8); } return total; } /** * Translates up to the first 8 bytes of a byte array beyond the given * offset to a long. If there are fewer than 8 bytes to be translated, * the MSBs are all assumed to be zero (regardless of endianness). */ public static long bytesToLong(short[] bytes, int off, boolean little) { return bytesToLong(bytes, off, 8, little); } /** * Translates up to the first 8 bytes of a byte array to a long. * If there are fewer than 8 bytes in the array, the MSBs are all * assumed to be zero (regardless of endianness). */ public static long bytesToLong(short[] bytes, boolean little) { return bytesToLong(bytes, 0, 8, little); } /** * Translates the specified number of bytes of a byte array to a double. * If there are fewer than 8 bytes in the array, the MSBs are all assumed * to be zero (regardless of endianness). */ public static double bytesToDouble(byte[] bytes, int offset, int len, boolean little) { return Double.longBitsToDouble(bytesToLong(bytes, offset, len, little)); } /** Translates the short value into an array of two bytes. */ public static byte[] shortToBytes(short value, boolean little) { byte[] v = new byte[2]; unpackShort(value, v, 0, little); return v; } /** Translates the int value into an array of four bytes. */ public static byte[] intToBytes(int value, boolean little) { byte[] v = new byte[4]; unpackBytes(value, v, 0, 4, little); return v; } /** Translates an array of short values into an array of byte values. */ public static byte[] shortsToBytes(short[] values, boolean little) { byte[] v = new byte[values.length * 2]; for (int i=0; i<values.length; i++) { unpackShort(values[i], v, i * 2, little); } return v; } /** Translates an array of int values into an array of byte values. */ public static byte[] intsToBytes(int[] values, boolean little) { byte[] v = new byte[values.length * 4]; for (int i=0; i<values.length; i++) { unpackBytes(values[i], v, i * 4, 4, little); } return v; } /** Translates an array of float values into an array of byte values. */ public static byte[] floatsToBytes(float[] values, boolean little) { byte[] v = new byte[values.length * 4]; for (int i=0; i<values.length; i++) { unpackBytes(Float.floatToIntBits(values[i]), v, i * 4, 4, little); } return v; } /** * Translates the short value into two bytes, and places them in a byte * array at the given index. */ public static void unpackShort(short value, byte[] buf, int ndx, boolean little) { if (little) { buf[ndx] = (byte) (value & 0xff); buf[ndx + 1] = (byte) ((value >> 8) & 0xff); } else { buf[ndx + 1] = (byte) (value & 0xff); buf[ndx] = (byte) ((value >> 8) & 0xff); } } /** * Translates nBytes of the given long and places the result in the * given byte array. */ public static void unpackBytes(long value, byte[] buf, int ndx, int nBytes, boolean little) { if (little) { for (int i=0; i<nBytes; i++) { buf[ndx + i] = (byte) ((value >> (8*i)) & 0xff); } } else { for (int i=0; i<nBytes; i++) { buf[ndx + i] = (byte) ((value >> (8*(nBytes - i - 1))) & 0xff); } } } /** * Convert a byte array to the appropriate primitive type array. * @param b Byte array to convert. * @param bpp Denotes the number of bytes in the returned primitive type * (e.g. if bpp == 2, we should return an array of type short). * @param fp If set and bpp == 4 or bpp == 8, then return floats or doubles. * @param little Whether byte array is in little-endian order. */ public static Object makeDataArray(byte[] b, int bpp, boolean fp, boolean little) { if (bpp == 1) { return b; } else if (bpp == 2) { short[] s = new short[b.length / 2]; for (int i=0; i<s.length; i++) { s[i] = bytesToShort(b, i*2, 2, little); } return s; } else if (bpp == 4 && fp) { float[] f = new float[b.length / 4]; for (int i=0; i<f.length; i++) { f[i] = bytesToFloat(b, i * 4, 4, little); } return f; } else if (bpp == 4) { int[] i = new int[b.length / 4]; for (int j=0; j<i.length; j++) { i[j] = bytesToInt(b, j*4, 4, little); } return i; } else if (bpp == 8 && fp) { double[] d = new double[b.length / 8]; for (int i=0; i<d.length; i++) { d[i] = bytesToDouble(b, i * 8, 8, little); } return d; } else if (bpp == 8) { long[] l = new long[b.length / 8]; for (int i=0; i<l.length; i++) { l[i] = bytesToLong(b, i*8, 8, little); } return l; } return null; } /** * @deprecated Use {@link #makeDataArray(byte[], int, boolean, boolean)} * regardless of signedness. */ public static Object makeDataArray(byte[] b, int bpp, boolean fp, boolean little, boolean signed) { return makeDataArray(b, bpp, fp, little); } // -- Byte swapping -- public static short swap(short x) { return (short) ((x << 8) | ((x >> 8) & 0xFF)); } public static char swap(char x) { return (char) ((x << 8) | ((x >> 8) & 0xFF)); } public static int swap(int x) { return (int) ((swap((short) x) << 16) | (swap((short) (x >> 16)) & 0xFFFF)); } public static long swap(long x) { return (long) (((long) swap((int) x) << 32) | ((long) swap((int) (x >> 32)) & 0xFFFFFFFFL)); } public static float swap(float x) { return Float.intBitsToFloat(swap(Float.floatToIntBits(x))); } public static double swap(double x) { return Double.longBitsToDouble(swap(Double.doubleToLongBits(x))); } // -- Miscellaneous -- /** Remove null bytes from a string. */ public static String stripString(String toStrip) { StringBuffer s = new StringBuffer(); for (int i=0; i<toStrip.length(); i++) { if (toStrip.charAt(i) != 0) { s.append(toStrip.charAt(i)); } } return s.toString().trim(); } /** Check if two filenames have the same prefix. */ public static boolean samePrefix(String s1, String s2) { if (s1 == null || s2 == null) return false; int n1 = s1.indexOf("."); int n2 = s2.indexOf("."); if ((n1 == -1) || (n2 == -1)) return false; int slash1 = s1.lastIndexOf(File.pathSeparator); int slash2 = s2.lastIndexOf(File.pathSeparator); String sub1 = s1.substring(slash1 + 1, n1); String sub2 = s2.substring(slash2 + 1, n2); return sub1.equals(sub2) || sub1.startsWith(sub2) || sub2.startsWith(sub1); } /** Remove unprintable characters from the given string. */ public static String sanitize(String s) { if (s == null) return null; StringBuffer buf = new StringBuffer(s); for (int i=0; i<buf.length(); i++) { char c = buf.charAt(i); if (c != '\t' && c != '\n' && (c < ' ' || c > '~')) { buf = buf.deleteCharAt(i } } return buf.toString(); } /** Remove invalid characters from an XML string. */ public static String sanitizeXML(String s) { for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (Character.isISOControl(c) || !Character.isDefined(c) || c > '~') { s = s.replace(c, ' '); } } return s; } /** * Normalize the given float array so that the minimum value maps to 0.0 * and the maximum value maps to 1.0. */ public static float[] normalizeFloats(float[] data) { float[] rtn = new float[data.length]; // make a quick pass through to determine the real min and max values float min = Float.MAX_VALUE; float max = Float.MIN_VALUE; float range = max - min; for (int i=0; i<data.length; i++) { if (data[i] < min) min = data[i]; if (data[i] > max) max = data[i]; } // now normalize; min => 0.0, max => 1.0 for (int i=0; i<rtn.length; i++) { rtn[i] = (data[i] - min) / range; } return rtn; } /** * Normalize the given double array so that the minimum value maps to 0.0 * and the maximum value maps to 1.0. */ public static double[] normalizeDoubles(double[] data) { double[] rtn = new double[data.length]; double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; double range = max - min; for (int i=0; i<data.length; i++) { if (data[i] < min) min = data[i]; if (data[i] > max) max = data[i]; } for (int i=0; i<rtn.length; i++) { rtn[i] = (data[i] - min) / range; } return rtn; } public static void parseXML(String xml, DefaultHandler handler) throws IOException { parseXML(xml.getBytes(), handler); } public static void parseXML(RandomAccessInputStream stream, DefaultHandler handler) throws IOException { byte[] b = new byte[(int) (stream.length() - stream.getFilePointer())]; stream.read(b); parseXML(b, handler); b = null; } public static void parseXML(byte[] xml, DefaultHandler handler) throws IOException { try { SAXParser parser = SAX_FACTORY.newSAXParser(); parser.parse(new ByteArrayInputStream(xml), handler); } catch (ParserConfigurationException exc) { IOException e = new IOException(); e.initCause(exc); throw e; } catch (SAXException exc) { IOException e = new IOException(); e.initCause(exc); throw e; } } // -- Date handling -- /** Converts the given timestamp into an ISO 8601 date. */ public static String convertDate(long stamp, int format) { // dates than you will ever need (or want) long ms = stamp; switch (format) { case UNIX: ms -= UNIX_EPOCH; break; case COBOL: ms -= COBOL_EPOCH; break; case MICROSOFT: ms -= MICROSOFT_EPOCH; break; case ZVI: ms -= ZVI_EPOCH; break; } SimpleDateFormat fmt = new SimpleDateFormat(ISO8601_FORMAT); StringBuffer sb = new StringBuffer(); Date d = new Date(ms); fmt.format(d, sb, new FieldPosition(0)); return sb.toString(); } /** Return given date in ISO 8601 format. */ public static String formatDate(String date, String format) { SimpleDateFormat f = new SimpleDateFormat(format); Date d = f.parse(date, new ParsePosition(0)); if (d == null) return null; f = new SimpleDateFormat(ISO8601_FORMAT); return f.format(d); } /** * Converts a string date in the given format to a long timestamp * (in Unix format: milliseconds since January 1, 1970). */ public static long getTime(String date, String format) { SimpleDateFormat f = new SimpleDateFormat(format); Date d = f.parse(date, new ParsePosition(0)); if (d == null) return -1; return d.getTime(); } // -- Array handling -- /** Returns true if the given value is contained in the given array. */ public static boolean containsValue(int[] array, int value) { return indexOf(array, value) != -1; } /** * Returns the index of the first occurence of the given value in the given * array. If the value is not in the array, returns -1. */ public static int indexOf(int[] array, int value) { for (int i=0; i<array.length; i++) { if (array[i] == value) return i; } return -1; } // -- Signed data conversion -- public static byte[] makeSigned(byte[] b) { for (int i=0; i<b.length; i++) { b[i] = (byte) (b[i] + 128); } return b; } public static short[] makeSigned(short[] s) { for (int i=0; i<s.length; i++) { s[i] = (short) (s[i] + 32768); } return s; } public static int[] makeSigned(int[] i) { for (int j=0; j<i.length; j++) { i[j] = (int) (i[j] + 2147483648L); } return i; } }
package guitests; import static org.junit.Assert.assertTrue; import static seedu.geekeep.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.Test; import guitests.guihandles.PersonCardHandle; import seedu.geekeep.commons.core.Messages; import seedu.geekeep.logic.commands.EditCommand; import seedu.geekeep.model.tag.Tag; import seedu.geekeep.model.task.EndDateTime; import seedu.geekeep.model.task.Location; import seedu.geekeep.model.task.StartDateTime; import seedu.geekeep.model.task.Title; import seedu.geekeep.testutil.PersonBuilder; import seedu.geekeep.testutil.TestPerson; // TODO: reduce GUI tests by transferring some tests to be covered by lower level tests. public class EditCommandTest extends AddressBookGuiTest { // The list of persons in the person list panel is expected to match this list. // This list is updated with every successful call to assertEditSuccess(). TestPerson[] expectedPersonsList = td.getTypicalPersons(); @Test public void edit_allFieldsSpecified_success() throws Exception { String detailsToEdit = "Bobby s/2017-04-01T10:16:30 e/2017-04-01T10:16:30 l/Block 123, Bobby Street 3 t/husband"; int addressBookIndex = 1; TestPerson editedPerson = new PersonBuilder().withName("Bobby") .withEndDateTime("2017-04-01T10:16:30") .withStartDateTime("2017-04-01T10:16:30") .withLocation("Block 123, Bobby Street 3") .withTags("husband").build(); assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedPerson); } @Test public void edit_notAllFieldsSpecified_success() throws Exception { String detailsToEdit = "t/sweetie t/bestie"; int addressBookIndex = 2; TestPerson personToEdit = expectedPersonsList[addressBookIndex - 1]; TestPerson editedPerson = new PersonBuilder(personToEdit).withTags("sweetie", "bestie").build(); assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedPerson); } @Test public void edit_clearTags_success() throws Exception { String detailsToEdit = "t/"; int addressBookIndex = 2; TestPerson personToEdit = expectedPersonsList[addressBookIndex - 1]; TestPerson editedPerson = new PersonBuilder(personToEdit).withTags().build(); assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedPerson); } @Test public void edit_findThenEdit_success() throws Exception { commandBox.runCommand("find Elle"); String detailsToEdit = "Belle"; int filteredPersonListIndex = 1; int addressBookIndex = 5; TestPerson personToEdit = expectedPersonsList[addressBookIndex - 1]; TestPerson editedPerson = new PersonBuilder(personToEdit).withName("Belle").build(); assertEditSuccess(filteredPersonListIndex, addressBookIndex, detailsToEdit, editedPerson); } @Test public void edit_missingPersonIndex_failure() { commandBox.runCommand("edit Bobby"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } @Test public void edit_invalidPersonIndex_failure() { commandBox.runCommand("edit 8 Bobby"); assertResultMessage(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } @Test public void edit_noFieldsSpecified_failure() { commandBox.runCommand("edit 1"); assertResultMessage(EditCommand.MESSAGE_NOT_EDITED); } @Test public void edit_invalidValues_failure() { commandBox.runCommand("edit 1 *&"); assertResultMessage(Title.MESSAGE_TITLE_CONSTRAINTS); commandBox.runCommand("edit 1 e/abcd"); assertResultMessage(EndDateTime.MESSAGE_DATETIME_CONSTRAINTS); commandBox.runCommand("edit 1 s/yahoo!!!"); assertResultMessage(StartDateTime.MESSAGE_DATETIME_CONSTRAINTS); commandBox.runCommand("edit 1 l/"); assertResultMessage(Location.MESSAGE_LOCATION_CONSTRAINTS); /** * Checks whether the edited person has the correct updated details. * * @param filteredPersonListIndex index of person to edit in filtered list * @param addressBookIndex index of person to edit in the address book. * Must refer to the same person as {@code filteredPersonListIndex} * @param detailsToEdit details to edit the person with as input to the edit command * @param editedPerson the expected person after editing the person's details */ private void assertEditSuccess(int filteredPersonListIndex, int addressBookIndex, String detailsToEdit, TestPerson editedPerson) { commandBox.runCommand("edit " + filteredPersonListIndex + " " + detailsToEdit); // confirm the new card contains the right data PersonCardHandle editedCard = personListPanel.navigateToPerson(editedPerson.getTitle().fullTitle); assertMatching(editedPerson, editedCard); // confirm the list now contains all previous persons plus the person with updated details expectedPersonsList[addressBookIndex - 1] = editedPerson; assertTrue(personListPanel.isListMatching(expectedPersonsList)); assertResultMessage(String.format(EditCommand.MESSAGE_EDIT_PERSON_SUCCESS, editedPerson)); } }
package loci.common; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public final class DateTools { // -- Constants -- /** Timestamp formats. */ public static final int UNIX = 0; // January 1, 1970 public static final int COBOL = 1; // January 1, 1601 public static final int MICROSOFT = 2; // December 30, 1899 public static final int ZVI = 3; public static final int ALT_ZVI = 4; /** Milliseconds until UNIX epoch. */ public static final long UNIX_EPOCH = 0; public static final long COBOL_EPOCH = 11644473600000L; public static final long MICROSOFT_EPOCH = 2209143600000L; public static final long ZVI_EPOCH = 2921084975759000L; public static final long ALT_ZVI_EPOCH = 2921084284761000L; /** ISO 8601 date format string. */ public static final String ISO8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; // -- Constructor -- private DateTools() { } // -- Date handling -- /** * Converts from two-word tick representation to milliseconds. * Mainly useful in conjunction with COBOL date conversion. */ public static long getMillisFromTicks(long hi, long lo) { long ticks = ((hi << 32) | lo); return ticks / 10000; // 100 ns = 0.0001 ms } /** Converts the given timestamp into an ISO8601 date. */ public static String convertDate(long stamp, int format) { return convertDate(stamp, format, ISO8601_FORMAT); } /** Converts the given timestamp into a date string with the given format. */ public static String convertDate(long stamp, int format, String outputFormat) { return convertDate(stamp, format, outputFormat, false); } /** * Converts the given timestamp into a date string with the given format. * * If correctTimeZoneForGMT is set, then the timestamp will be interpreted * as being relative to GMT and not the local time zone. */ public static String convertDate(long stamp, int format, String outputFormat, boolean correctTimeZoneForGMT) { // dates than you will ever need (or want) long ms = stamp; switch (format) { case UNIX: ms -= UNIX_EPOCH; break; case COBOL: ms -= COBOL_EPOCH; break; case MICROSOFT: ms -= MICROSOFT_EPOCH; break; case ZVI: ms -= ZVI_EPOCH; break; case ALT_ZVI: ms -= ALT_ZVI_EPOCH; break; } SimpleDateFormat fmt = new SimpleDateFormat(outputFormat); if (correctTimeZoneForGMT) { TimeZone tz = TimeZone.getDefault(); ms -= tz.getOffset(ms); } StringBuffer sb = new StringBuffer(); Date d = new Date(ms); fmt.format(d, sb, new FieldPosition(0)); return sb.toString(); } /** * Formats the given date as an ISO 8601 date. * Delegates to {@link #formatDate(String, String, boolean)}, with the * 'lenient' flag set to false. * * @param date The date to format as ISO 8601. * @param format The date's input format. */ public static String formatDate(String date, String format) { return formatDate(date, format, false); } /** * Formats the given date as an ISO 8601 date. * * @param date The date to format as ISO 8601. * @param format The date's input format. * @param lenient Whether or not to leniently parse the date. */ public static String formatDate(String date, String format, boolean lenient) { if (date == null) return null; SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setLenient(lenient); Date d = sdf.parse(date, new ParsePosition(0)); if (d == null) return null; sdf = new SimpleDateFormat(ISO8601_FORMAT); return sdf.format(d); } /** * Formats the given date as an ISO 8601 date. * Delegates to {@link #formatDate(String, String[], boolean)}, with the * 'lenient' flag set to false. * * @param date The date to format as ISO 8601. * @param formats The date's possible input formats. */ public static String formatDate(String date, String[] formats) { return formatDate(date, formats, false); } /** * Formats the given date as an ISO 8601 date. * * @param date The date to format as ISO 8601. * @param formats The date's possible input formats. * @param lenient Whether or not to leniently parse the date. */ public static String formatDate(String date, String[] formats, boolean lenient) { for (int i=0; i<formats.length; i++) { String result = formatDate(date, formats[i], lenient); if (result != null) return result; } return null; } /** * Converts a string date in the given format to a long timestamp * (in Unix format: milliseconds since January 1, 1970). */ public static long getTime(String date, String format) { SimpleDateFormat f = new SimpleDateFormat(format); Date d = f.parse(date, new ParsePosition(0)); if (d == null) return -1; return d.getTime(); } }
package guitests; import static org.junit.Assert.assertTrue; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.Test; import guitests.guihandles.TaskCardHandle; import seedu.taskboss.commons.core.Messages; import seedu.taskboss.logic.commands.EditCommand; import seedu.taskboss.model.category.Category; import seedu.taskboss.model.task.Name; import seedu.taskboss.model.task.PriorityLevel; import seedu.taskboss.testutil.TaskBuilder; import seedu.taskboss.testutil.TestTask; // TODO: reduce GUI tests by transferring some tests to be covered by lower level tests. public class EditCommandTest extends TaskBossGuiTest { // The list of tasks in the task list panel is expected to match this list. // This list is updated with every successful call to assertEditSuccess(). TestTask[] expectedTasksList = td.getTypicalTasks(); @Test public void edit_allFieldsSpecified_success() throws Exception { String detailsToEdit = "n/Alice p/Yes sd/10am Feb 19, 2017 ed/10am Feb 28, 2017 i/123," + " Jurong West Ave 6, #08-111 c/friends"; int taskBossIndex = 1; TestTask editedTask = new TaskBuilder().withName("Alice").withPriorityLevel("Yes") .withStartDateTime("10am Feb 19, 2017").withEndDateTime("10am Feb 28, 2017") .withInformation("123, Jurong West Ave 6, #08-111").withCategories("friends").build(); assertEditSuccess(false, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } //@@author A0143157J // EP: edit all fields @Test public void edit_allFieldsWithShortCommand_success() throws Exception { String detailsToEdit = "n/Amanda p/Yes sd/feb 27 2016 ed/feb 28 2016 i/discuss about life c/relax"; int taskBossIndex = 1; TestTask editedTask = new TaskBuilder().withName("Amanda").withPriorityLevel("Yes") .withStartDateTime("feb 27 2016").withEndDateTime("feb 28 2016") .withInformation("discuss about life").withCategories("relax").build(); assertEditSuccess(true, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } // EP: edit categories with short command @Test public void edit_notAllFieldsWithShortCommand_success() throws Exception { String detailsToEdit = "c/work c/fun"; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withCategories("work", "fun").build(); assertEditSuccess(true, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } //@@author @Test public void edit_notAllFieldsSpecified_success() throws Exception { String detailsToEdit = "c/sweetie c/bestie"; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withCategories("sweetie", "bestie").build(); assertEditSuccess(false, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } @Test public void edit_clearCategories_success() throws Exception { String detailsToEdit = "c/"; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withCategories().build(); assertEditSuccess(false, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } @Test public void edit_findThenEdit_success() throws Exception { commandBox.runCommand("find k/Elle"); String detailsToEdit = "k/Belle"; int filteredTaskListIndex = 1; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withName("Belle").build(); assertEditSuccess(false, filteredTaskListIndex, taskBossIndex, detailsToEdit, editedTask); } @Test public void edit_missingTaskIndex_failure() { commandBox.runCommand("edit n/Bobby"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } @Test public void edit_invalidTaskIndex_failure() { commandBox.runCommand("edit 8 n/Bobby"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } @Test public void edit_noFieldsSpecified_failure() { commandBox.runCommand("edit 1"); assertResultMessage(EditCommand.MESSAGE_NOT_EDITED); } @Test public void edit_invalidValues_failure() { /** * Checks whether the edited task has the correct updated details. * * @param filteredTaskListIndex index of task to edit in filtered list * @param taskBossIndex index of task to edit in TaskBoss. * Must refer to the same task as {@code filteredTaskListIndex} * @param detailsToEdit details to edit the task with as input to the edit command * @param editedTask the expected task after editing the task's details */ private void assertEditSuccess(boolean isShortCommand, int filteredTaskListIndex, int taskBossIndex, String detailsToEdit, TestTask editedTask) { if (isShortCommand) { commandBox.runCommand("e " + filteredTaskListIndex + " " + detailsToEdit); } else { commandBox.runCommand("edit " + filteredTaskListIndex + " " + detailsToEdit); } // confirm the new card contains the right data TaskCardHandle editedCard = taskListPanel.navigateToTask(editedTask.getName().fullName); assertMatching(editedTask, editedCard); // confirm the list now contains all previous tasks plus the task with updated details expectedTasksList[taskBossIndex - 1] = editedTask; assertTrue(taskListPanel.isListMatching(expectedTasksList)); assertResultMessage(String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, editedTask)); } }
package guitests; import org.junit.Test; import seedu.address.commons.core.Messages; import seedu.address.testutil.TestTask; import static org.junit.Assert.assertTrue; public class FindCommandTest extends ToDoListGuiTest { @Test public void find() { assertFindResult("find Mark"); //no results assertFindResult("find gas", td.car, td.zika); //multiple results //find after deleting one result commandBox.runCommand("delete 1"); assertFindResult("find gas",td.zika); commandBox.runCommand("done 1"); assertFindResult("find --done", td.zika); commandBox.runCommand("clear"); assertFindResult("find Jean"); //no results commandBox.runCommand("findgeorge"); assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND); } private void assertFindResult(String command, TestTask... expectedHits ) { commandBox.runCommand(command); assertListSize(expectedHits.length); assertResultMessage(expectedHits.length + " tasks listed!"); assertTrue(taskListPanel.isListMatching(expectedHits)); } }
package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; import seedu.address.logic.commands.ClearCommand; import seedu.address.logic.commands.DeleteCommand; import seedu.address.logic.commands.MarkCommand; import seedu.address.logic.commands.RedoCommand; import seedu.address.logic.commands.UndoCommand; import seedu.address.testutil.TestTask; import seedu.address.testutil.TestUtil; public class RedoCommandTest extends TaskManagerGuiTest { TestTask[] expectedList = td.getTypicalTasks(); /** * Tries to redo an add command */ @Test public void redoAdd() { TestTask taskToAdd = td.alice; commandBox.runCommand(taskToAdd.getAddCommand()); commandBox.runCommand(UndoCommand.COMMAND_WORD); expectedList = TestUtil.addTasksToList(expectedList, taskToAdd); assertRedoSuccess(expectedList); } /** * Tries to redo a delete command */ @Test public void redoDelete() { int targetIndex = 1; commandBox.runCommand(DeleteCommand.COMMAND_WORD + " " + targetIndex); commandBox.runCommand(UndoCommand.COMMAND_WORD); expectedList = TestUtil.removeTaskFromList(expectedList, targetIndex); assertRedoSuccess(expectedList); } /** * Tries to redo a clear command */ @Test public void redoClear() { commandBox.runCommand("mark 1"); commandBox.runCommand("mark 2"); commandBox.runCommand(ClearCommand.COMMAND_WORD + " done"); commandBox.runCommand(UndoCommand.COMMAND_WORD); expectedList = TestUtil.removeTaskFromList(expectedList, 1); expectedList = TestUtil.removeTaskFromList(expectedList, 1); assertRedoSuccess(expectedList); } /** * Tries to redo a mark command */ @Test public void redoMark() { int targetIndex = 1; commandBox.runCommand(MarkCommand.COMMAND_WORD + " " + 1); commandBox.runCommand(UndoCommand.COMMAND_WORD); expectedList[targetIndex - 1].setStatus("Done"); assertRedoSuccess(expectedList); } /** * Runs redo command and checks whether the current list matches the expected list * @param currentList list before redo command is carried out * @param expectedList list after redo command is carried out */ private void assertRedoSuccess(TestTask[] expectedList) { commandBox.runCommand(RedoCommand.COMMAND_WORD); assertTrue(taskListPanel.isListMatching(expectedList)); assertResultMessage(String.format(RedoCommand.MESSAGE_SUCCESS)); } }
package pl.mprzybylak.presentation.rxjavaquick; import io.reactivex.Observable; import org.assertj.core.api.Assertions; import org.assertj.core.api.Condition; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.Assertions.assertThat; public class ObservableFilteringTest { private static final Condition<Integer> EVEN = new Condition<>(integer -> integer % 2 == 0, "cond"); @Test public void onlyElementsMatchPredicate() { // given List<Integer> evenNumbers = new ArrayList<>(500); // when Observable.range(1, 1000) .filter(i -> i % 2 == 0) .subscribe(evenNumbers::add); // then evenNumbers.forEach(e -> assertThat(e).is(EVEN)); } @Test public void onlyDistinctElements() { // given List<Integer> withDupicates = Arrays.asList(1,1,2,2,3,3,4,4,5,5); List<Integer> withoutDuplicates = new ArrayList<>(5); // when Observable.fromIterable(withDupicates) .distinct() .subscribe(withoutDuplicates::add); // then assertThat(withoutDuplicates).hasSize(5); } @Test public void onlyFirstElement() { // given AtomicInteger firstValue = new AtomicInteger(); // when Observable.range(1, 1000) .first() .subscribe(firstValue::set); // then assertThat(firstValue.get()).isEqualTo(1); } @Test public void onlyLastElement() { // given AtomicInteger firstValue = new AtomicInteger(); // when Observable.range(1, 1000) .last() .subscribe(firstValue::set); // then assertThat(firstValue.get()).isEqualTo(1000); } @Test public void onlyNthElement() { // given List<Integer> input = Arrays.asList(1,2,3,4,5); AtomicInteger thirdItem = new AtomicInteger(); // when Observable.fromIterable(input) .elementAt(2) .subscribe(thirdItem::set); // then assertThat(thirdItem.get()).isEqualTo(3); } }
package objektwerks; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Optional; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class OptionalTest { @Test void emptyTest() { var optional = Optional.<Integer>empty(); assert(optional.isEmpty()); assert(!optional.isPresent()); } @Test void ofNullableTest() { Integer nullable = null; var optional = Optional.ofNullable(nullable); assert(optional.isEmpty()); assert(!optional.isPresent()); } @Test void orTest() { assert(Optional.<Integer>empty().or(() -> Optional.of(1)).get() == 1); } @Test void getTest() { var optional = Optional.of(1); assert(optional.get() == 1); } @Test void orElseTest() { var optional = Optional.of(1); assert(optional.orElse(-1) == 1); // default value ALWAYS if present or empty created! } @Test void orElseGetTest() { var optional = Optional.<Integer>empty(); assert(optional.orElseGet(() -> 1) == 1); // default value ONLY created when empty! } @Test void orElseThrowTest() { Integer nullable = null; assertThrows(NoSuchElementException.class, () -> { Optional.ofNullable(nullable).orElseThrow(); }); } @Test void ifPresentTest() { var optional = Optional.of(1); optional.ifPresent( value -> assertEquals(value, 1) ); } @Test void mapTest() { assert(Optional.of(4).map(Math::sqrt).get() == 2.0); } @Test void flatMapTest() { var box = new Box<Integer>(); box.set(-1); var optionalBox = Optional.of(box); assert(optionalBox.flatMap( b -> Optional.of( Math.abs( b.get() ) ) ).orElse(-1) == 1); } @Test void filterTest() { assert(Optional.of(2).filter( i -> i % 2 == 0 ).isPresent()); } @Test void listOfOptionalTest() { var list = Arrays.<Optional<String>>asList( Optional.empty(), Optional.of("a"), Optional.empty(), Optional.of("b"), Optional.empty() ); var concatenated = list.stream() .filter(Optional::isPresent) .map(Optional::get) .reduce(String::concat); assert(concatenated.orElse("").equals("ab")); } }
package test.factory; import static org.testng.Assert.assertFalse; import org.testng.Assert; import org.testng.annotations.AfterSuite; import org.testng.annotations.Factory; import org.testng.annotations.Parameters; public class FactoryTest { static boolean m_invoked = false; @Parameters({ "factory-param" }) @Factory public Object[] createObjects(String param) { Assert.assertEquals(param, "FactoryParam"); assertFalse(m_invoked, "Should only be invoked once"); m_invoked = true; return new Object[] { new FactoryTest2(42), new FactoryTest2(43) }; } @AfterSuite public void afterSuite() { m_invoked = false; } }
package io.spine.server.trace.stackdriver; import com.google.devtools.cloudtrace.v2.AttributeValue; import com.google.devtools.cloudtrace.v2.Span; import com.google.devtools.cloudtrace.v2.TruncatableString; import com.google.protobuf.Any; import com.google.protobuf.Timestamp; import io.spine.base.Time; import io.spine.code.java.ClassName; import io.spine.core.BoundedContextName; import io.spine.core.MessageId; import io.spine.core.Signal; import io.spine.core.SignalId; import io.spine.system.server.EntityTypeName; import io.spine.type.TypeName; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkNotNull; import static io.spine.protobuf.AnyPacker.unpack; import static java.lang.String.format; /** * A span based on a signal. * * <p>Signal messages may be processed once or many times by different entities. The processing time * is tracked and represented with a span so that each message handler invocation is converted into * a single span. * * <p>The exception from the span-per-handler rule is * an {@linkplain io.spine.server.aggregate.Apply event applier} invocation, which is treated as * a part of the respective command handler or event reactor. */ @SuppressWarnings("WeakerAccess") // Allows customization via subclassing. public class SignalSpan { private static final int SPAN_DISPLAY_NAME_LENGTH = 128; private final BoundedContextName context; private final Signal<?, ?, ?> signal; private final MessageId receiver; private final EntityTypeName receiverType; protected SignalSpan(BoundedContextName context, Signal<?, ?, ?> signal, MessageId receiver, EntityTypeName receiverType) { this.context = checkNotNull(context); this.signal = checkNotNull(signal); this.receiver = checkNotNull(receiver); this.receiverType = checkNotNull(receiverType); } private SignalSpan(Builder builder) { this(builder.context, builder.signal, builder.receiver, builder.receiverType); } /** * Creates a {@link Span Stackdriver Trace Span} from this signal span. * * @param gcpProjectId * the Google Cloud Platform project ID * @return new span */ protected Span asTraceSpan(ProjectId gcpProjectId) { Span.Builder span = buildSpan(gcpProjectId); buildSpanAttributes(span); return span.build(); } private String displayName() { TypeName signalType = signal.typeUrl() .toTypeName(); ClassName className = ClassName.of(receiverType.getJavaClassName()); return format("%s handles %s", className.toSimple(), signalType.simpleName()); } private Span.Builder buildSpan(ProjectId projectId) { SpanId spanId = SpanId.random(); Timestamp whenStarted = signal.time(); Timestamp whenFinished = Time.currentTime(); TruncatableString displayName = Truncate.stringTo(displayName(), SPAN_DISPLAY_NAME_LENGTH); return Span .newBuilder() .setName(spanName(projectId, spanId).value()) .setSpanId(spanId.value()) .setDisplayName(displayName) .setStartTime(whenStarted) .setEndTime(whenFinished); } private void buildSpanAttributes(Span.Builder span) { Span.Attributes.Builder attributesBuilder = span.getAttributesBuilder(); Stream.of(SpanAttribute.values()) .forEach(attribute -> { String key = attribute.qualifiedName(); AttributeValue value = attribute.value(this); attributesBuilder.putAttributeMap(key, value); }); } private SpanName spanName(ProjectId projectId, SpanId spanId) { Any id = signal.rootMessage() .getId(); SignalId signalId = (SignalId) unpack(id); TraceId traceId = new TraceId(signalId); return SpanName.from(projectId, traceId, spanId); } /** * Obtains the name of the bounded context to which the signal receiver belongs. */ protected BoundedContextName contextName() { return context; } /** * Obtains the processed signal. */ protected Signal<?, ?, ?> signal() { return signal; } /** * Obtains the signal receiver ID. */ protected MessageId receiver() { return receiver; } /** * Creates a new instance of {@code Builder} for {@code SignalSpan} instances. * * @return new instance of {@code Builder} */ public static Builder newBuilder() { return new Builder(); } /** * A builder for the {@code SignalSpan} instances. */ public static final class Builder { private BoundedContextName context; private Signal<?, ?, ?> signal; private MessageId receiver; private EntityTypeName receiverType; /** * Prevents direct instantiation. */ private Builder() { } public Builder setContext(BoundedContextName context) { this.context = checkNotNull(context); return this; } public Builder setSignal(Signal<?, ?, ?> signal) { this.signal = checkNotNull(signal); return this; } public Builder setReceiver(MessageId receiver) { this.receiver = checkNotNull(receiver); return this; } public Builder setReceiverType(EntityTypeName receiverType) { this.receiverType = checkNotNull(receiverType); return this; } /** * Creates a new instance of {@code SignalSpan}. * * @return new instance of {@code SignalSpan} */ public SignalSpan build() { return new SignalSpan(this); } } }
package com.github.davidmoten.fsm.runtime; public final class Create implements Event<Void> { private static final Create instance = new Create(); public static Create instance() { return instance; } }
package timeBench.test; import java.util.Iterator; import prefuse.Visualization; import prefuse.data.Graph; import prefuse.data.Node; import prefuse.data.Table; import prefuse.util.collections.IntIterator; import prefuse.visual.VisualGraph; import timeBench.data.TemporalDataException; import timeBench.data.relational.TemporalDataset; import timeBench.data.relational.TemporalElement; import timeBench.data.relational.TemporalObject; import timeBench.data.util.DefaultIntervalComparator; import timeBench.data.util.IntervalIndex; public class TestTemporalDataSet { public static void evilStuff() { // TemporalElement instant = new timeBench.data.relational.Instant(); // instant.setLong(TemporalDataset.KIND, TemporalDataset.PRIMITIVE_INSTANT); } /** * Test * * * @param args * system arguments * @throws TemporalDataException */ public static void main(String[] args) throws TemporalDataException { evilStuff(); TemporalDataset dataset = new TemporalDataset(); dataset.addTemporalElement(1, 10, 1, 2); dataset.addTemporalElement(4, 12, 1, 2); dataset.addTemporalElement(6, 8, 1, 2); dataset.addTemporalElement(3, 14, 1, 2); int begin = dataset.addTemporalElement(2, 6, 1, 2); int end = dataset.addTemporalElement(5, 13, 1, 2); int interval = dataset.addTemporalElement(2, 13, 1, 3); dataset.getTemporalElementsGraph().addEdge(begin, interval); dataset.getTemporalElementsGraph().addEdge(end, interval); Table dataElements = dataset.getDataElements(); dataElements.addColumn("ID", String.class); dataElements.addColumn("Age", int.class); dataElements.addRows(6); dataElements.set(0, "ID", "Morg"); dataElements.set(0, "Age", 28); dataElements.set(1, "ID", "Ben"); dataElements.set(1, "Age", 26); dataElements.set(2, "ID", "Xu"); dataElements.set(2, "Age", 29); dataElements.set(3, "ID", "Fab"); dataElements.set(3, "Age", 21); dataElements.set(4, "ID", "Sha"); dataElements.set(4, "Age", 25); dataElements.set(5, "ID", "Tra"); dataElements.set(5, "Age", 29); int occ0 = dataset.addOccurrence(0, 0); int occ1 = dataset.addOccurrence(1, 1); int occ2 = dataset.addOccurrence(2, 2); int occ3 = dataset.addOccurrence(3, 3); int occ4 = dataset.addOccurrence(4, 4); int occ5 = dataset.addOccurrence(5, interval); Graph occurrencesGraph = dataset.getOccurrencesGraph(); occurrencesGraph.addEdge(occ0, occ1); occurrencesGraph.addEdge(occ0, occ2); occurrencesGraph.addEdge(occ0, occ4); occurrencesGraph.addEdge(occ3, occ4); occurrencesGraph.addEdge(occ3, occ5); System.out.println("Test relations between occurrences"); Iterator<?> neighbors = occurrencesGraph.getNode(occ0).neighbors(); while (neighbors.hasNext()) { System.out.println(neighbors.next()); } System.out.println(dataset); System.out.println("Test interval index"); IntervalIndex index = dataset.createTemporalIndex(new DefaultIntervalComparator()); IntIterator rows5 = index.rows(7, 8); while (rows5.hasNext()) { int row = rows5.nextInt(); System.out.println(row + " " + dataset.getTemporalElement(row)); } System.out.println("Test iterator & tuplemanager"); System.out.println(dataset.getTemporalElement(0)); // Iterator<TemporalElement> teIterator = dataset.temporalElements(); // while (teIterator.hasNext()) { // TemporalElement te = teIterator.next(); for (TemporalElement te : dataset.temporalElementsIterable()) { System.out.println(te); } Iterator<TemporalElement> teIterator = dataset.temporalPrimitives(); while (teIterator.hasNext()) { System.out.println(teIterator.next()); } System.out.println("Test temporal elements graph"); TemporalElement te = dataset.getTemporalElement(interval); System.out.println("Children of interval count=" + te.getChildElementCount()); teIterator = te.childElements(); while (teIterator.hasNext()) { System.out.println(teIterator.next()); } te = dataset.getTemporalElement(begin); System.out.println("Children of instant count=" + te.getChildElementCount()); teIterator = te.childElements(); while (teIterator.hasNext()) { System.out.println(teIterator.next()); } te = dataset.getTemporalElement(begin); System.out.println("Parents of begin instant count=" + te.getParentElementCount()); teIterator = te.parentElements(); while (teIterator.hasNext()) { System.out.println(teIterator.next()); } System.out.println("\nTest tuplemanager for TemporalObject"); Iterator<TemporalObject> toIterator = dataset.temporalObjects(); while (toIterator.hasNext()) { TemporalObject to = toIterator.next(); System.out.println(to); System.out.println(" " + to.getDataElement()); System.out.println(" " + to.getTemporalElement()); System.out.println(" anchored=" + to.getTemporalElement().isAnchored() + ", length=" + to.getTemporalElement().getLength()); } /* Iterator iter = dataset.getTemporalElement(interval).inEdges(); while (iter.hasNext()) { prefuse.data.Edge edge = (prefuse.data.Edge) iter.next(); System.out.println("c" + edge.getColumnName(2)); } */ // check that adding a tuple set to a visualization does not affect existing tuples TemporalElement t2 = dataset.getTemporalElement(2); System.out.println(t2); Visualization viz = new Visualization(); viz.addTable("aex", dataElements); System.out.println(t2); VisualGraph vg = viz.addGraph("bex", dataset.getTemporalElementsGraph()); Node v2 = vg.getNode(2); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(t2 + " " + v2); } }
package hudson.maven; import hudson.FilePath; import hudson.Launcher; import hudson.maven.reporters.MavenFingerprinter; import hudson.model.BuildListener; import hudson.tasks.LogRotator; import hudson.tasks.Maven.MavenInstallation; import java.io.File; import java.io.IOException; import java.util.Collection; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Bug; import org.jvnet.hudson.test.ExtractResourceWithChangesSCM; import org.jvnet.hudson.test.For; import org.jvnet.hudson.test.JenkinsRule; /** * * Test that looks in jobs archive with 2 builds. When LogRotator set as build * discarder with settings to keep only 1 build with artifacts, test searches * for jars in archive for build one and build two, expecting no jars in build 1 * and expecting jars in build 2. * * */ public class MavenMultiModuleLogRotatorCleanArtifactsTest { @Rule public JenkinsRule j = new JenkinsRule(); private MavenModuleSet m; private FilePath jobs; private static class TestReporter extends MavenReporter { private static final long serialVersionUID = 1L; @Override public boolean end(MavenBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { Assert.assertNotNull(build.getProject().getSomeWorkspace()); Assert.assertNotNull(build.getWorkspace()); return true; } } @Before public void setUp() throws Exception { j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21); m = j.createMavenProject(); m.setBuildDiscarder(new LogRotator("-1", "2", "-1", "1")); m.getReporters().add(new TestReporter()); m.getReporters().add(new MavenFingerprinter()); m.setScm(new ExtractResourceWithChangesSCM(getClass().getResource( "maven-multimod.zip"), getClass().getResource( "maven-multimod-changes.zip"))); j.buildAndAssertSuccess(m); // Now run a second build with the changes. m.setIncrementalBuild(false); j.buildAndAssertSuccess(m); FilePath workspace = m.getSomeWorkspace(); FilePath parent = workspace.getParent().getParent(); jobs = new FilePath(parent, "jobs"); } @Test @Bug(17508) @For({MavenModuleSetBuild.class, LogRotator.class}) @SuppressWarnings("unchecked") public void testArtifactsAreDeletedInBuildOneWhenBuildDiscarderRun() throws Exception { File directory = new File(new FilePath(jobs, "test0/builds/1").getRemote()); Collection<File> files = FileUtils.listFiles(directory, new String[] { "jar" }, true); Assert.assertTrue( "Found jars in previous build, that should not happen", files.isEmpty()); Collection<File> files2 = FileUtils.listFiles(new File(new FilePath( jobs, "test0/builds/2").getRemote()), new String[] { "jar" }, true); Assert.assertFalse("No jars in last build ALERT!", files2.isEmpty()); } /** * Performs a third build and expecting build one to be deleted * @throws Exception */ @For({MavenModuleSetBuild.class, LogRotator.class}) @Test public void testArtifactsOldBuildsDeletedWhenBuildDiscarderRun() throws Exception { j.buildAndAssertSuccess(m); File directory = new File(new FilePath(jobs, "test0/builds/1").getRemote()); Assert.assertFalse("oops the build should have been deleted", directory.exists()); } }
package edu.northwestern.bioinformatics.studycalendar.web; import java.util.Date; import java.sql.Timestamp; import edu.northwestern.bioinformatics.studycalendar.domain.auditing.LoginAudit; import edu.northwestern.bioinformatics.studycalendar.dao.auditing.LoginAuditDao; import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase; import gov.nih.nci.security.AuthenticationManager; import gov.nih.nci.security.exceptions.CSException; import gov.nih.nci.cabig.ctms.domain.MutableDomainObject; import org.easymock.classextension.EasyMock; import static org.easymock.classextension.EasyMock.expect; /** * @author Rhett Sutphin * @author Padmaja Vedula */ public class LoginCommandTest extends StudyCalendarTestCase { private static final String USERNAME = "alice"; private static final String PASSWORD = "wonderland"; private static final String IPADDRESS = "123.0.0.1"; private LoginCommand command; private AuthenticationManager authenticationManager; private LoginAuditDao auditDao; protected void setUp() throws Exception { super.setUp(); authenticationManager = registerMockFor(AuthenticationManager.class); auditDao = registerMockFor(LoginAuditDao.class, LoginAuditDao.class.getMethod("save", MutableDomainObject.class)); command = new LoginCommand(authenticationManager, auditDao); command.setUsername(USERNAME); command.setPassword(PASSWORD); } public void testLoginSuccessfulWhenSuccessful() throws Exception { expect(authenticationManager.login(USERNAME, PASSWORD)).andReturn(true); auditDao.save((LoginAudit) EasyMock.notNull()); replayMocks(); assertTrue(command.login(IPADDRESS)); verifyMocks(); } public void testLoginFailsWhenFails() throws Exception { expect(authenticationManager.login(USERNAME, PASSWORD)).andReturn(false); auditDao.save((LoginAudit) EasyMock.notNull()); replayMocks(); assertFalse(command.login(IPADDRESS)); verifyMocks(); } public void testLoginFailsWhenException() throws Exception { expect(authenticationManager.login(USERNAME, PASSWORD)).andThrow(new CSException()); auditDao.save((LoginAudit) EasyMock.notNull()); replayMocks(); assertFalse(command.login(IPADDRESS)); verifyMocks(); } /** * @throws Exception */ public void testCreateLoginAudit() throws Exception { LoginAudit loginAudit = new LoginAudit(); loginAudit.setIpAddress("123.0.0.1"); loginAudit.setLoginStatus("Success"); loginAudit.setTime(new Timestamp(new Date().getTime())); loginAudit.setUserName("study_admin"); auditDao.save(loginAudit); replayMocks(); command.saveAudit(loginAudit); verifyMocks(); } }
package de.hs_mannheim.IB.SS15.OOT.test; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import de.hs_mannheim.IB.SS15.OOT.Subject; import de.hs_mannheim.IB.SS15.OOT.Exceptions.SameSubjectException; import de.hs_mannheim.IB.SS15.OOT.Participants.Assessor; import de.hs_mannheim.IB.SS15.OOT.Participants.Desire; import de.hs_mannheim.IB.SS15.OOT.Participants.Examinee; import de.hs_mannheim.IB.SS15.OOT.Participants.Examiner; import de.hs_mannheim.IB.SS15.OOT.PlanObjects.Exam; public class ExamsTest { private Exam exam, exam2, exam3; Desire desireOne, desireTwo, desireThree; private Subject[] subjects = new Subject[2]; private Subject[] subjects2 = new Subject[2]; private Subject[] subjects3 = new Subject[2]; private Examinee examinee, examinee1, examinee2, examinee3, examinee4, examinee5, examinee6; private Examiner[] examiner = new Examiner[2]; private Assessor assessor, assessor1, assessor2, assessor3, assessor4, assessor5, assessor6; private Examiner examiner1, examiner2, examiner3, examiner4, examiner5, examiner6, examiner7; private Subject subjectOne, subjectTwo, subjectThree; private ArrayList<Desire> desiresListOne, desiresList1, desiresList2, desiresList3, desiresList4, desiresList5, desiresList6; private Desire d1, d2, d3, d4, d5, d6; ArrayList<Subject> subjectsArrayList ; @Before public void setUp() throws Exception { // Subjects subjectOne = new Subject("Lineare Algebra", "LAL"); subjectTwo = new Subject("Analysis", "ANA"); subjectThree = new Subject("Hhere Mathematik 1", "HM1", true); subjects[0] = subjectOne; subjects[1] = subjectTwo; subjects3[0] = subjectOne; subjects3[1] = null; subjects2[0] = null; subjects2[1] = null; subjectsArrayList = new ArrayList<Subject>(); subjectsArrayList.add(subjectOne); subjectsArrayList.add(subjectTwo); // desires desiresListOne = new ArrayList<Desire>(); desireOne = new Desire(61, 122, "wichtig", 3); desiresListOne.add(desireOne); // desiresListen desiresList1 = new ArrayList<Desire>(); desiresList2 = new ArrayList<Desire>(); desiresList3 = new ArrayList<Desire>(); desiresList4 = new ArrayList<Desire>(); desiresList5 = new ArrayList<Desire>(); desiresList6 = new ArrayList<Desire>(); // desires d1 = new Desire(600, 930, "hoch", 3); d2 = new Desire(480, 600, "hoch", 3); d3 = new Desire(480, 600, "mittel", 2); d4 = new Desire(600, 720, "mittel", 2); d5 = new Desire(600, 720, "niedrig", 1); d6 = new Desire(480, 500, "niedrig", 1); desiresList1.add(d1); desiresList2.add(d2); desiresList3.add(d3); desiresList4.add(d4); desiresList5.add(d5); desiresList6.add(d6); // assessors assessor1 = new Assessor("Rudi", subjectsArrayList); assessor2 = new Assessor("Johan", subjectsArrayList); assessor3 = new Assessor("Bert", subjectsArrayList); assessor4 = new Assessor("Ernie", subjectsArrayList); assessor5 = new Assessor("Olaf", subjectsArrayList); assessor6 = new Assessor("Ludwig", subjectsArrayList); // examiner && examinee Examinee examineeTest = new Examinee("Harald", subjectsArrayList, desiresList1); examinee1 = new Examinee("Wolfram", subjectsArrayList, desiresList1); examinee2 = new Examinee("Walburga", subjectsArrayList, desiresList2); examinee3 = new Examinee("Berta", subjectsArrayList, desiresList3); examinee4 = new Examinee("Herta", subjectsArrayList, desiresList4); examinee5 = new Examinee("Friedrich-Wilhelm", subjectsArrayList, desiresList5); examinee6 = new Examinee("Karl-August", subjectsArrayList, desiresList6); examiner1 = new Examiner("Bernd", subjectsArrayList, desiresList1); examiner2 = new Examiner("Hugo", subjectsArrayList, desiresList2); examiner3 = new Examiner("Brunhilde", subjectsArrayList, desiresList3); examiner4 = new Examiner("Heidi", subjectsArrayList, desiresList4); examiner5 = new Examiner("Willhelm", subjectsArrayList, desiresList5); examiner6 = new Examiner("Hedwig", subjectsArrayList, desiresList6); examiner7 = new Examiner("Horst", subjectsArrayList, desiresList6); Examiner examinerTestOne = new Examiner("Dieter", subjectsArrayList, desiresListOne); Examiner examinerTestTwo = new Examiner("Wolfgang", subjectsArrayList, null); examiner[0] = examinerTestOne; examiner[1] = examinerTestTwo; // assessor Assessor assessorTest = new Assessor("Helene", subjectsArrayList); // create exams exam = new Exam(subjects, examineeTest, examiner, assessorTest, 3); exam2 = new Exam(subjects2, examineeTest, examiner, assessorTest, 3); exam3 = new Exam(subjects3, examineeTest, examiner, assessorTest, 3); } @Test(expected = IllegalArgumentException.class) public void CheckDesire_ExamineeNull() { examiner[0] = examiner6; examiner[1] = examiner7; exam = new Exam(subjects, null, examiner, assessor6, 25); exam.checkDesires(3, 600); } @Test(expected = IllegalArgumentException.class) public void checkDesireTest_ExaminerArrayNull() { exam = new Exam(subjects, examinee2, null, assessor6, 25); exam.checkDesires(3, 600); } @Test(expected = IllegalArgumentException.class) public void checkDesireTest_ExaminerArrayEmpty() { examiner[0] = null; examiner[1] = null; exam = new Exam(subjects, examinee2, examiner, assessor6, 25); exam.checkDesires(3, 600); } @Test public void checkDesireTest_ExaminerArrayHalfFull() { examiner[0] = examiner2; examiner[1] = null; exam = new Exam(subjects, examinee2, examiner, assessor6, 25); assertEquals(true, exam.checkDesires(3, 600)); } @Test public void checkDesireTest_Assessornull() { exam = new Exam(subjects, examinee2, examiner, null, 25); assertEquals(true, exam.checkDesires(600, 3)); } // teilnehmer, die nicht im testnamen stehen auer der Testzeit liegen @Test public void checkDesireTest_LegalArgumentsExaminersBothNotInTestetTime() { examiner1=new Examiner("Hans", subjectsArrayList,desiresList2 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList2); examiner[0]=examiner1; examiner[1]=examiner2; exam=new Exam(subjects, examinee6, examiner, assessor6,25); assertEquals(true, exam.checkDesires(3, 700)); } @Test public void checkDesireTest_LegalArgumentsExaminerOneIsInTestetTime(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList1 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList2); examiner[0]=examiner1; examiner[1]=examiner2; exam=new Exam(subjects, examinee6, examiner, assessor6,25); assertEquals(false, exam.checkDesires(3, 600)); } @Test public void checkDesireTest_LegalArgumentsExaminerBothAreInTestetTime(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList1 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList1); examiner[0]=examiner1; examiner[1]=examiner2; exam=new Exam(subjects, examinee6, examiner, assessor6,25); assertEquals(false, exam.checkDesires(3, 600)); } @Test public void checkDesireTest_LegalArgumentsExaminerPrioOFExaminersAreHigherAndInTestetTime(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList1 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList1); examiner[0]=examiner1; examiner[1]=examiner2; exam=new Exam(subjects, examinee6, examiner, assessor6,25); assertEquals(false, exam.checkDesires(2, 600)); } @Test public void checkDesireTest_LegalArgumentsExaminerPrioOFExaminersAreHigherButNotInTestetTime(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList2 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList2); examiner[0]=examiner1; examiner[1]=examiner2; exam=new Exam(subjects, examinee6, examiner, assessor6,25); assertEquals(false, exam.checkDesires(2, 600)); } @Test public void checkDesireTEst_LegalArgumentsExamineeNotInTestetTime(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList6 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList6); examiner[0]=examiner1; examiner[1]=examiner2; examinee1 = new Examinee("Harald", subjectsArrayList, desiresList2); exam=new Exam(subjects, examinee1, examiner, assessor6,25); assertEquals(true, exam.checkDesires(3, 600)); } @Test public void checkDesireTEst_LegalArgumentsExamineeInTestetTimeSamePrio(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList6 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList6); examiner[0]=examiner1; examiner[1]=examiner2; examinee1 = new Examinee("Harald", subjectsArrayList, desiresList1); exam=new Exam(subjects, examinee1, examiner, assessor6,25); assertEquals(false, exam.checkDesires(3, 600)); } @Test public void checkDesireTEst_LegalArgumentsExamineeInTestetTimeHigherPrio(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList6 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList6); examiner[0]=examiner1; examiner[1]=examiner2; examinee1 = new Examinee("Harald", subjectsArrayList, desiresList1); exam=new Exam(subjects, examinee1, examiner, assessor6,25); assertEquals(true, exam.checkDesires(2, 600)); } @Test public void checkDesireTEst_LegalArgumentsExamineeNotInTestetTimeHigherPrio(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList6 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList6); examiner[0]=examiner1; examiner[1]=examiner2; examinee1 = new Examinee("Harald", subjectsArrayList, desiresList2); exam=new Exam(subjects, examinee1, examiner, assessor6,25); assertEquals(true, exam.checkDesires(2, 600)); } @Test public void checkDesireTEst_LegalArgumentsExamineeInTestetTimeSamePrioPrio2(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList6 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList6); examiner[0]=examiner1; examiner[1]=examiner2; examinee1 = new Examinee("Harald", subjectsArrayList, desiresList4); exam=new Exam(subjects, examinee1, examiner, assessor6,25); assertEquals(false, exam.checkDesires(2, 600)); } @Test public void checkDesireTEst_LegalArgumentsExamineeInTestetTimeSamePrioPrio1(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList6 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList6); examiner[0]=examiner1; examiner[1]=examiner2; examinee1 = new Examinee("Harald", subjectsArrayList, desiresList5); exam=new Exam(subjects, examinee1, examiner, assessor6,25); assertEquals(false, exam.checkDesires(1, 600)); } @Test public void checkDesireTEst_LegalArgumentsExamineeInTestetTimeSameLowerPrio(){ examiner1=new Examiner("Hans", subjectsArrayList,desiresList6 ); examiner2=new Examiner("Traude", subjectsArrayList,desiresList6); examiner[0]=examiner1; examiner[1]=examiner2; examinee1 = new Examinee("Harald", subjectsArrayList, desiresList4); exam=new Exam(subjects, examinee1, examiner, assessor6,25); assertEquals(true, exam.checkDesires(3, 600)); } @Test(expected = IllegalArgumentException.class) public void addSubjectTest_NameNull() { exam.addSubject(null); exam2.addSubject(null); exam3.addSubject(null); } // @Test (expected = SameSubjectException.class) // public void addSubjectTest_ArrayHalfFullSameSubject(){ // exam3.addSubject(subjectOne); // exam.addSubject(subjectOne); @Test public void addSubjectTest_ArrayFull() { assertEquals(false, exam.addSubject(subjectThree)); } @Test public void addSubjectTest_ArrayHalfFull_Legal() { assertEquals(true, exam3.addSubject(subjectTwo)); } @Test public void addSubjectTest_LegalArguments() { assertEquals(true, exam2.addSubject(subjectOne)); assertEquals(true, exam2.addSubject(subjectTwo)); assertEquals(true, exam3.addSubject(subjectTwo)); } @Test public void equalsTest() { assertEquals(true, subjectThree.equals(new Subject( "Hhere Mathematik 1", "HM1", true))); assertEquals(true, subjectOne.equals(new Subject("Lineare Algebra", "LAL"))); } }
package de.jungblut.classification.eval; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ThreadFactoryBuilder; import de.jungblut.classification.Classifier; import de.jungblut.classification.ClassifierFactory; import de.jungblut.datastructure.ArrayUtils; import de.jungblut.math.DoubleVector; import de.jungblut.math.MathUtils; import de.jungblut.math.MathUtils.PredictionOutcomePair; import de.jungblut.partition.BlockPartitioner; import de.jungblut.partition.Boundaries.Range; /** * Binary-/Multi-class classification evaluator utility that takes care of * test/train splitting and its evaluation with various metrics. * * @author thomas.jungblut * */ public final class Evaluator { private static final Log LOG = LogFactory.getLog(Evaluator.class); private Evaluator() { throw new IllegalAccessError(); } public static class EvaluationResult { int numLabels, correct, testSize, truePositive, falsePositive, trueNegative, falseNegative; int[][] confusionMatrix; double auc; public double getAUC() { return auc; } public double getPrecision() { return ((double) truePositive) / (truePositive + falsePositive); } public double getRecall() { return ((double) truePositive) / (truePositive + falseNegative); } // fall-out public double getFalsePositiveRate() { return ((double) falsePositive) / (falsePositive + trueNegative); } public double getAccuracy() { if (isBinary()) { return ((double) truePositive + trueNegative) / (truePositive + trueNegative + falsePositive + falseNegative); } else { return correct / (double) testSize; } } public double getF1Score() { return 2d * (getPrecision() * getRecall()) / (getPrecision() + getRecall()); } public int getCorrect() { if (!isBinary()) { return correct; } else { return truePositive + trueNegative; } } public int getNumLabels() { return numLabels; } public int getTestSize() { return testSize; } public int[][] getConfusionMatrix() { return this.confusionMatrix; } public boolean isBinary() { return numLabels == 2; } public void add(EvaluationResult res) { correct += res.correct; testSize += res.testSize; truePositive += res.truePositive; falsePositive += res.falsePositive; trueNegative += res.trueNegative; falseNegative += res.falseNegative; auc += res.auc; if (this.confusionMatrix == null && res.confusionMatrix != null) { this.confusionMatrix = res.confusionMatrix; } else if (this.confusionMatrix != null && res.confusionMatrix != null) { for (int i = 0; i < numLabels; i++) { for (int j = 0; j < numLabels; j++) { this.confusionMatrix[i][j] += res.confusionMatrix[i][j]; } } } } public void average(int pn) { final double n = pn; correct /= n; testSize /= n; truePositive /= n; falsePositive /= n; trueNegative /= n; falseNegative /= n; auc /= n; if (this.confusionMatrix != null) { for (int i = 0; i < numLabels; i++) { for (int j = 0; j < numLabels; j++) { this.confusionMatrix[i][j] /= n; } } } } public int getTruePositive() { return this.truePositive; } public int getFalsePositive() { return this.falsePositive; } public int getTrueNegative() { return this.trueNegative; } public int getFalseNegative() { return this.falseNegative; } public void print() { print(LOG); } public void print(Log log) { log.info("Number of labels: " + getNumLabels()); log.info("Testset size: " + getTestSize()); log.info("Correctly classified: " + getCorrect()); log.info("Accuracy: " + getAccuracy()); if (isBinary()) { log.info("TP: " + truePositive); log.info("FP: " + falsePositive); log.info("TN: " + trueNegative); log.info("FN: " + falseNegative); log.info("Precision: " + getPrecision()); log.info("Recall: " + getRecall()); log.info("F1 Score: " + getF1Score()); log.info("AUC: " + getAUC()); } else { printConfusionMatrix(); } } public void printConfusionMatrix() { printConfusionMatrix(null); } public void printConfusionMatrix(String[] classNames) { Preconditions.checkNotNull(this.confusionMatrix, "No confusion matrix found."); System.out .println("\nConfusion matrix (real outcome on rows, prediction in columns)\n"); for (int i = 0; i < getNumLabels(); i++) { System.out.format("%5d", i); } System.out.format(" <- %5s %5s\t%s\n", "sum", "perc", "class"); for (int i = 0; i < getNumLabels(); i++) { int sum = 0; for (int j = 0; j < getNumLabels(); j++) { if (i != j) { sum += confusionMatrix[i][j]; } System.out.format("%5d", confusionMatrix[i][j]); } float falsePercentage = sum / (float) (sum + confusionMatrix[i][i]); String clz = classNames != null ? " " + i + " (" + classNames[i] + ")" : " " + i; System.out.format(" <- %5s %5s\t%s\n", sum, NumberFormat .getPercentInstance().format(falsePercentage), clz); } } } /** * Trains and evaluates the given classifier with a test split. * * @param classifier the classifier to train and evaluate. * @param features the features to split. * @param outcome the outcome to split. * @param splitFraction a value between 0f and 1f that sets the size of the * trainingset. With 1k items, a splitFraction of 0.9f will result in * 900 items to train and 100 to evaluate. * @param random true if you want to perform shuffling on the data beforehand. * @return a new {@link EvaluationResult}. */ public static EvaluationResult evaluateClassifier(Classifier classifier, DoubleVector[] features, DoubleVector[] outcome, float splitFraction, boolean random) { return evaluateClassifier(classifier, features, outcome, splitFraction, random, null); } /** * Trains and evaluates the given classifier with a test split. * * @param classifier the classifier to train and evaluate. * @param features the features to split. * @param outcome the outcome to split. * @param numLabels the number of labels that are used. (e.G. 2 in binary * classification). * @param splitFraction a value between 0f and 1f that sets the size of the * trainingset. With 1k items, a splitFraction of 0.9f will result in * 900 items to train and 100 to evaluate. * @param random true if you want to perform shuffling on the data beforehand. * @param threshold in case of binary predictions, threshold is used to call * in {@link Classifier#predictedClass(DoubleVector, double)}. Can be * null, then no thresholding will be used. * @return a new {@link EvaluationResult}. */ public static EvaluationResult evaluateClassifier(Classifier classifier, DoubleVector[] features, DoubleVector[] outcome, float splitFraction, boolean random, Double threshold) { EvaluationSplit split = EvaluationSplit.create(features, outcome, splitFraction, random); return evaluateSplit(classifier, split, threshold); } /** * Evaluates a given train/test split with the given classifier. * * @param classifier the classifier to train on the train split. * @param split the {@link EvaluationSplit} that contains the test and train * data. * @return a fresh evalation result filled with the evaluated metrics. */ public static EvaluationResult evaluateSplit(Classifier classifier, EvaluationSplit split) { return evaluateSplit(classifier, split.getTrainFeatures(), split.getTrainOutcome(), split.getTestFeatures(), split.getTestOutcome(), null); } /** * Evaluates a given train/test split with the given classifier. * * @param classifier the classifier to train on the train split. * @param split the {@link EvaluationSplit} that contains the test and train * data. * @param threshold the threshold for predicting a specific class by * probability (if not provided = null). * @return a fresh evalation result filled with the evaluated metrics. */ public static EvaluationResult evaluateSplit(Classifier classifier, EvaluationSplit split, Double threshold) { return evaluateSplit(classifier, split.getTrainFeatures(), split.getTrainOutcome(), split.getTestFeatures(), split.getTestOutcome(), threshold); } /** * Evaluates a given train/test split with the given classifier. * * @param classifier the classifier to train on the train split. * @param trainFeatures the features to train with. * @param trainOutcome the outcomes to train with. * @param testFeatures the features to test with. * @param testOutcome the outcome to test with. * @param threshold the threshold for predicting a specific class by * probability (if not provided = null). * @return a fresh evalation result filled with the evaluated metrics. */ public static EvaluationResult evaluateSplit(Classifier classifier, DoubleVector[] trainFeatures, DoubleVector[] trainOutcome, DoubleVector[] testFeatures, DoubleVector[] testOutcome, Double threshold) { classifier.train(trainFeatures, trainOutcome); return testClassifier(classifier, testFeatures, testOutcome, threshold); } /** * Tests the given classifier without actually training it. * * @param classifier the classifier to evaluate on the test split. * @param testFeatures the features to test with. * @param testOutcome the outcome to test with. * @return a fresh evalation result filled with the evaluated metrics. */ public static EvaluationResult testClassifier(Classifier classifier, DoubleVector[] testFeatures, DoubleVector[] testOutcome) { return testClassifier(classifier, testFeatures, testOutcome, null); } /** * Tests the given classifier without actually training it. * * @param classifier the classifier to evaluate on the test split. * @param testFeatures the features to test with. * @param testOutcome the outcome to test with. * @param threshold the threshold for predicting a specific class by * probability (if not provided = null). * @return a fresh evalation result filled with the evaluated metrics. */ public static EvaluationResult testClassifier(Classifier classifier, DoubleVector[] testFeatures, DoubleVector[] testOutcome, Double threshold) { EvaluationResult result = new EvaluationResult(); result.numLabels = Math.max(2, testOutcome[0].getDimension()); result.testSize = testOutcome.length; // check the binary case to calculate special metrics if (result.isBinary()) { List<PredictionOutcomePair> outcomePredictedPairs = new ArrayList<>(); for (int i = 0; i < testFeatures.length; i++) { int outcomeClass = ((int) testOutcome[i].get(0)); DoubleVector predictedVector = classifier.predict(testFeatures[i]); outcomePredictedPairs.add(PredictionOutcomePair.from(outcomeClass, predictedVector.get(0))); int prediction = 0; if (threshold == null) { prediction = classifier.extractPredictedClass(predictedVector); } else { prediction = classifier.extractPredictedClass(predictedVector, threshold); } if (outcomeClass == 1) { if (prediction == 1) { result.truePositive++; // "Correct result" } else { result.falseNegative++; // "Missing the correct result" } } else if (outcomeClass == 0) { if (prediction == 0) { result.trueNegative++; // "Correct absence of result" } else { result.falsePositive++; // "Unexpected result" } } else { throw new IllegalArgumentException( "Outcome class was neither 0 or 1. Was: " + outcomeClass + "; the supplied outcome value was: " + testOutcome[i].get(0)); } // we can compute the AUC from the outcomePredictedPairs we gathered result.auc = MathUtils.computeAUC(outcomePredictedPairs); } } else { int[][] confusionMatrix = new int[result.numLabels][result.numLabels]; for (int i = 0; i < testFeatures.length; i++) { int outcomeClass = testOutcome[i].maxIndex(); int prediction = classifier.predictedClass(testFeatures[i]); confusionMatrix[outcomeClass][prediction]++; if (outcomeClass == prediction) { result.correct++; } } result.confusionMatrix = confusionMatrix; } return result; } /** * Does a k-fold crossvalidation on the given classifiers with features and * outcomes. The folds will be calculated on a new thread. * * @param classifierFactory the classifiers to train and test. * @param features the features to train/test with. * @param outcome the outcomes to train/test with. * @param numLabels the total number of labels that are possible. e.G. 2 in * the binary case. * @param folds the number of folds to fold, usually 10. * @param threshold the threshold for predicting a specific class by * probability (if not provided = null). * @param verbose true if partial fold results should be printed. * @return a averaged evaluation result over all k folds. */ public static <A extends Classifier> EvaluationResult crossValidateClassifier( ClassifierFactory<A> classifierFactory, DoubleVector[] features, DoubleVector[] outcome, int numLabels, int folds, Double threshold, boolean verbose) { return crossValidateClassifier(classifierFactory, features, outcome, numLabels, folds, threshold, 1, verbose); } /** * Does a k-fold crossvalidation on the given classifiers with features and * outcomes. * * @param classifierFactory the classifiers to train and test. * @param features the features to train/test with. * @param outcome the outcomes to train/test with. * @param numLabels the total number of labels that are possible. e.G. 2 in * the binary case. * @param folds the number of folds to fold, usually 10. * @param threshold the threshold for predicting a specific class by * probability (if not provided = null). * @param numThreads how many threads to use to evaluate the folds. * @param verbose true if partial fold results should be printed. * @return a averaged evaluation result over all k folds. */ public static <A extends Classifier> EvaluationResult crossValidateClassifier( ClassifierFactory<A> classifierFactory, DoubleVector[] features, DoubleVector[] outcome, int numLabels, int folds, Double threshold, int numThreads, boolean verbose) { // train on k-1 folds, test on 1 fold, results are averaged final int numFolds = folds + 1; // multi shuffle the arrays first, note that this is not stratified. ArrayUtils.multiShuffle(features, outcome); EvaluationResult averagedModel = new EvaluationResult(); averagedModel.numLabels = numLabels; final int m = features.length; // compute the split ranges by blocks, so we have range from 0 to the next // partition index end that will be our testset, and so on. List<Range> partition = new ArrayList<>(new BlockPartitioner().partition( numFolds, m).getBoundaries()); int[] splitRanges = new int[numFolds]; for (int i = 1; i < numFolds; i++) { splitRanges[i] = partition.get(i).getEnd(); } // because we are dealing with indices, we have to subtract 1 from the end splitRanges[numFolds - 1] = splitRanges[numFolds - 1] - 1; if (verbose) { LOG.info("Computed split ranges: " + Arrays.toString(splitRanges) + "\n"); } final ExecutorService pool = Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setDaemon(true).build()); final ExecutorCompletionService<EvaluationResult> completionService = new ExecutorCompletionService<>( pool); // build the models fold for fold for (int fold = 0; fold < folds; fold++) { completionService.submit(new CallableEvaluation<>(fold, splitRanges, m, classifierFactory, features, outcome, folds, threshold)); } // retrieve the results for (int fold = 0; fold < folds; fold++) { Future<EvaluationResult> take; try { take = completionService.take(); EvaluationResult foldSplit = take.get(); if (verbose) { LOG.info("Fold: " + (fold + 1)); foldSplit.print(); LOG.info(""); } averagedModel.add(foldSplit); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } // average the sums in the model averagedModel.average(folds); return averagedModel; } /** * Does a 10 fold crossvalidation. * * @param classifierFactory the classifiers to train and test. * @param features the features to train/test with. * @param outcome the outcomes to train/test with. * @param numLabels the total number of labels that are possible. e.G. 2 in * the binary case. * @param threshold the threshold for predicting a specific class by * probability (if not provided = null). * @param numThreads how many threads to use to evaluate the folds. * @param verbose true if partial fold results should be printed. * @return a averaged evaluation result over all 10 folds. */ public static <A extends Classifier> EvaluationResult tenFoldCrossValidation( ClassifierFactory<A> classifierFactory, DoubleVector[] features, DoubleVector[] outcome, int numLabels, Double threshold, boolean verbose) { return crossValidateClassifier(classifierFactory, features, outcome, numLabels, 10, threshold, verbose); } /** * Does a 10 fold crossvalidation. * * @param classifierFactory the classifiers to train and test. * @param features the features to train/test with. * @param outcome the outcomes to train/test with. * @param numLabels the total number of labels that are possible. e.G. 2 in * the binary case. * @param threshold the threshold for predicting a specific class by * probability (if not provided = null). * @param verbose true if partial fold results should be printed. * @return a averaged evaluation result over all 10 folds. */ public static <A extends Classifier> EvaluationResult tenFoldCrossValidation( ClassifierFactory<A> classifierFactory, DoubleVector[] features, DoubleVector[] outcome, int numLabels, Double threshold, int numThreads, boolean verbose) { return crossValidateClassifier(classifierFactory, features, outcome, numLabels, 10, threshold, numThreads, verbose); } private static class CallableEvaluation<A extends Classifier> implements Callable<EvaluationResult> { private final int fold; private final int[] splitRanges; private final int m; private final DoubleVector[] features; private final DoubleVector[] outcome; private final ClassifierFactory<A> classifierFactory; private final Double threshold; public CallableEvaluation(int fold, int[] splitRanges, int m, ClassifierFactory<A> classifierFactory, DoubleVector[] features, DoubleVector[] outcome, int folds, Double threshold) { this.fold = fold; this.splitRanges = splitRanges; this.m = m; this.classifierFactory = classifierFactory; this.features = features; this.outcome = outcome; this.threshold = threshold; } @Override public EvaluationResult call() throws Exception { DoubleVector[] featureTest = ArrayUtils.subArray(features, splitRanges[fold], splitRanges[fold + 1]); DoubleVector[] outcomeTest = ArrayUtils.subArray(outcome, splitRanges[fold], splitRanges[fold + 1]); DoubleVector[] featureTrain = new DoubleVector[m - featureTest.length]; DoubleVector[] outcomeTrain = new DoubleVector[m - featureTest.length]; int index = 0; for (int i = 0; i < m; i++) { if (i < splitRanges[fold] || i > splitRanges[fold + 1]) { featureTrain[index] = features[i]; outcomeTrain[index] = outcome[i]; index++; } } return evaluateSplit(classifierFactory.newInstance(), featureTrain, outcomeTrain, featureTest, outcomeTest, threshold); } } }
package de.lmu.ifi.dbs.varianceanalysis; import de.lmu.ifi.dbs.data.RealVector; import de.lmu.ifi.dbs.database.Database; import de.lmu.ifi.dbs.math.linearalgebra.Matrix; import de.lmu.ifi.dbs.utilities.Util; /** * Computes the principal components for vector objects of a given database. * * @author Elke Achtert (<a href="mailto:achtert@dbs.ifi.lmu.de">achtert@dbs.ifi.lmu.de</a>) */ public class GlobalPCA<O extends RealVector> extends AbstractPCA { /** * Holds the covariance matrix. */ private Matrix covarianceMatrix; /** * Computes the principal components for vector objects of a given database. */ public GlobalPCA() { super(); // this.debug = true; } /** * Computes the principal components for objects of the given database. * * @param database the database containing the objects */ public void run(Database<O> database) { covarianceMatrix = Util.covarianceMatrix(database); if (debug) { debugFine("covarianceMatrix " + covarianceMatrix.dimensionInfo() + "\n" + covarianceMatrix); } determineEigenPairs(covarianceMatrix); } /** * Computes the principal components for objects of the given matrix. * * @param matrix the matrix containing the objects as column vectors */ public void run(Matrix matrix) { covarianceMatrix = Util.covarianceMatrix(matrix); if (debug) { debugFine("covarianceMatrix " + covarianceMatrix.dimensionInfo() + "\n" + covarianceMatrix); } determineEigenPairs(covarianceMatrix); } /** * Returns the covariance matrix. * * @return the covariance matrix */ public Matrix getCovarianceMatrix() { return covarianceMatrix; } }
package de.uxnr.tsoexpert.game.trade; import de.uxnr.tsoexpert.game.player.Player; public class TradeRequest implements Comparable<TradeRequest> { private final String bid; private final int bidsize; private final String demand; private final int demandsize; private final Player player; private final boolean aktiv; private final long time; public TradeRequest(String input, Player player) { String[] splits = input.split("\\|"); this.bid = splits[0]; this.bidsize = Integer.parseInt(splits[1]); this.demand = splits[2]; this.demandsize = Integer.parseInt(splits[3]); this.player = player; this.aktiv = true; this.time = System.currentTimeMillis(); } public String getBid() { return this.bid; } public int getBidsize() { return this.bidsize; } public String getDemand() { return this.demand; } public int getDemandsize() { return this.demandsize; } public Player getPlayer() { return this.player; } public boolean isAktiv() { return this.aktiv; } public long getTime() { return this.time; } @Override public int compareTo(TradeRequest tr) { if (this.equals(tr)) return 0; if (!this.bid.equals(tr.bid)) return this.bid.compareTo(tr.bid); if (!this.demand.equals(tr.demand)) return this.demand.compareTo(tr.demand); if (this.bidsize != tr.bidsize) return this.bidsize - tr.bidsize; if (this.bidsize != tr.bidsize) return this.bidsize - tr.bidsize; if (this.player.equals(tr.player)) return this.player.compareTo(tr.player); return 0; } @Override public boolean equals(Object o) { if (o != null && o instanceof TradeRequest) { TradeRequest tr = (TradeRequest) o; if (this.aktiv == tr.aktiv && tr.bid.equals(this.bid) && tr.demand.equals(this.demand) && this.bidsize == tr.bidsize && this.demandsize == tr.demandsize) return true; } return false; } @Override public String toString() { return new StringBuilder(this.aktiv ? "Aktiv" : "Inaktiv").append(this.player.toString()).append(" bids ").append(this.bidsize).append(" pct. of ").append(this.bid).append(" and demands ").append(this.demandsize).append(" pct. of ").append(this.demand).toString(); } @Override public int hashCode() { return this.toString().hashCode(); } }
package uk.org.cinquin.mutinack; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import javax.jdo.annotations.Column; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import org.eclipse.jdt.annotation.NonNull; import com.beust.jcommander.IStringConverter; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterDescription; import com.beust.jcommander.WrappedParameter; import com.beust.jcommander.converters.BaseConverter; import com.fasterxml.jackson.annotation.JsonIgnore; import uk.org.cinquin.mutinack.misc_util.Assert; import uk.org.cinquin.mutinack.misc_util.FieldIteration; import uk.org.cinquin.mutinack.misc_util.Handle; import uk.org.cinquin.mutinack.misc_util.SettableInteger; import uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel; @PersistenceCapable public final class Parameters implements Serializable, Cloneable { public void automaticAdjustments() { if (outputAlignmentFile.isEmpty()) { logReadIssuesInOutputBam = false; } } public void validate() { try { validate1(); } catch (IllegalArgumentException e) { throw new RuntimeException("Problem while validating command line " + commandLine, e); } } public void validate1() { if (parallelizationFactor != 1 && !contigByContigParallelization.isEmpty()) { throw new IllegalArgumentException("Cannot use parallelizationFactor and " + "contigByContigParallelization at the same time"); } if (ignoreFirstNBasesQ2 < ignoreFirstNBasesQ1) { throw new IllegalArgumentException("Parameter ignoreFirstNBasesQ2 must be greater than ignoreFirstNBasesQ1"); } final int nMaxDupArg = maxNDuplexes.size(); if (nMaxDupArg > 0 && nMaxDupArg < inputReads.size()) { throw new IllegalArgumentException("maxNDuplexes must be specified once for each input file or not at all"); } final OutputLevel[] d = OutputLevel.values(); if (verbosity < 0 || verbosity >= d.length) { throw new IllegalArgumentException("Invalid verbosity " + verbosity + "; must be >= 0 and < " + d.length); } if (inputReads.isEmpty() && startServer == null && startWorker == null && !help && !version) { throw new IllegalArgumentException("No input reads specified"); } for (String ir: inputReads) { if (ir.endsWith(".bai")) { throw new IllegalArgumentException("Unexpected .bai extension in input read path " + ir); } } if (clipPairOverlap && !collapseFilteredReads) { throw new IllegalArgumentException("-clipPairOverlap requires -collapseFilteredReads"); } switch(candidateQ2Criterion) { case "1Q2Duplex": String baseErrorMessage = " only valid when candidateQ2Criterion==NQ1Duplexes"; throwIAEIfFalse(minQ1Duplexes == Integer.MAX_VALUE, "Option minQ1Duplexes" + baseErrorMessage); throwIAEIfFalse(minTotalReadsForNQ1Duplexes == Integer.MAX_VALUE, "Option minTotalReadsForNQ1Duplexes" + baseErrorMessage); break; case "NQ1Duplexes": String baseErrorMessage1 = " must be set when candidateQ2Criterion==NQ1Duplexes"; throwIAEIfFalse(minQ1Duplexes != Integer.MAX_VALUE, "Option minQ1Duplexes " + baseErrorMessage1); throwIAEIfFalse(minTotalReadsForNQ1Duplexes != Integer.MAX_VALUE, "Option minTotalReadsForNQ1Duplexes " + baseErrorMessage1); throwIAEIfFalse(minQ2DuplexesToCallMutation == 1, "Option minQ2DuplexesToCallMutation only valid when candidateQ2Criterion==1Q2Duplex"); break; default: throw new RuntimeException("Option candidateQ2Criterion must be one of 1Q2Duplex or NQ1Duplexes, not " + candidateQ2Criterion); } checkNoDuplicates(); for (String p: exploreParameters) { String [] split = p.split(":"); if (split.length != 4 && split.length != 3 && split.length != 1) { throw new IllegalArgumentException("exploreParameters argument should be formatted as " + "name:min:max[:n_steps] or name, but " + (split.length - 1) + " columns found in " + p); } final String paramName = split[0]; final Field f; try { f = Parameters.class.getDeclaredField(paramName); } catch (NoSuchFieldException e) { throw new RuntimeException("Unknown parameter " + paramName, e); } catch (SecurityException e) { throw new RuntimeException(e); } if (f.getAnnotation(OnlyUsedAfterDuplexGrouping.class) == null && f.getAnnotation(UsedAtDuplexGrouping.class) == null) { throw new IllegalArgumentException("Parameter " + paramName + " does not explicitly support exploration"); } if (computeRawMismatches && f.getAnnotation(ExplorationIncompatibleWithRawMismatches.class) != null) { throw new IllegalArgumentException("Please turn computeRawMismatches off to explore " + paramName); } final Object value; try { value = f.get(this); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } if (!(value instanceof Integer) && !(value instanceof Float) && !(value instanceof Boolean)) { throw new IllegalArgumentException("Parameter " + paramName + " is not a number or boolean"); } } if (randomOutputRate != 0) { if (!readContigsFromFile) { throw new IllegalArgumentException("Option randomOutputRate " + "requires readContigsFromFiles"); } } if (minMappingQIntersect.size() != intersectAlignment.size()) { throw new IllegalArgumentException( "Lists given in minMappingQIntersect and intersectAlignment must have same length"); } if (reportBreakdownForBED.size() != saveBEDBreakdownToPathPrefix.size()) { throw new IllegalArgumentException("Arguments -reportBreakdownForBED and " + "-saveBEDBreakdownToPathPrefix must appear same number of times"); } checkValues(); } private void checkValues() { FieldIteration.iterateFields((field, obj) -> { CheckValues checkAnnotation = field.getAnnotation(CheckValues.class); if (checkAnnotation == null || obj == null) { return; } String [] strings = checkAnnotation.permissibleStrings(); if (strings.length > 0) { Assert.isTrue(obj instanceof String); List<String> stringsList = Arrays.asList(strings); if (stringsList.contains(obj)) { throw new IllegalArgumentException("Parameter " + field.getName() + " must be one of " + stringsList + " but found " + obj); } } Float min = checkAnnotation.min(); if (!Float.isNaN(min)) { Assert.isTrue(obj instanceof Float); if ((Float) obj < min) { throw new IllegalArgumentException("Parameter " + field.getName() + " must be at least " + min + " but found " + obj); } } Float max = checkAnnotation.max(); if (!Float.isNaN(max)) { Assert.isTrue(obj instanceof Float); if ((Float) obj > max) { throw new IllegalArgumentException("Parameter " + field.getName() + " must be at most " + max + " but found " + obj); } } }, this); } private static void throwIAEIfFalse(boolean b, String message) { if (!b) { throw new IllegalArgumentException(message); } } private void checkNoDuplicates() { FieldIteration.iterateFields((field, obj) -> { if (field.getAnnotation(NoDuplicates.class) == null || obj == null) { return; } @SuppressWarnings("unchecked") Collection<Object> col = (Collection<Object>) obj; final Set<Object> set = new HashSet<>(); for (Object o: col) { if (!set.add(o)) { throw new IllegalArgumentException("Can specify each argument at most once for " + field.getName() + " but " + o + " is specified more than once"); } } }, this); } public static boolean isUsedAtDuplexGrouping(String key) { try { Field f = Parameters.class.getDeclaredField(key); return f.getAnnotation(UsedAtDuplexGrouping.class) != null; } catch (NoSuchFieldException e) { throw new RuntimeException(e); } } @HideInToString @JsonIgnore @IgnoreInHashcodeEquals public String commandLine; @HideInToString @JsonIgnore @IgnoreInHashcodeEquals public transient MutinackGroup group; @IgnoreInHashcodeEquals public Map<String, Object> distinctParameters = new HashMap<>(); public static final long serialVersionUID = 1L; @JsonIgnore private static final boolean hideInProgressParameters = true; @JsonIgnore private static final boolean hideAdvancedParameters = true; @Parameter(names = {"-help", "--help"}, help = true, description = "Display this message and return") @HideInToString @JsonIgnore public boolean help; @Parameter(names = {"-version", "--version"}, help = true, description = "Display version information and return") @HideInToString @JsonIgnore public boolean version; @Parameter(names = "-noStatusMessages", description = "Do not output any status information on stderr or stdout", required = false) @HideInToString @IgnoreInHashcodeEquals public boolean noStatusMessages = false; @Parameter(names = "-skipVersionCheck", description = "Do not check whether update is available for download", required = false) @HideInToString @JsonIgnore @IgnoreInHashcodeEquals public boolean skipVersionCheck = false; @Parameter(names = "-verbosity", description = "0: main mutation detection results only; 3: open the firehose", required = false) public int verbosity = 0; @IgnoreInHashcodeEquals @Parameter(names = "-suppressStderrOutput", description = "Only partially implemented so far", required = false) public boolean suppressStderrOutput = false; @IgnoreInHashcodeEquals @Parameter(names = "-runBatchName", description = "User-defined string to identify batch to which this run belongs", required = false) public String runBatchName = ""; @IgnoreInHashcodeEquals @Parameter(names = "-outputToDatabaseURL", description = "Formatted e.g. as jdbc:postgresql://localhost/mutinack_test_db", required = false) public String outputToDatabaseURL = "jdbc:postgresql://localhost/mutinack_test_db"; @IgnoreInHashcodeEquals @Parameter(names = "-outputToDatabaseUserName", description = "", required = false) public String outputToDatabaseUserName = "testuser3"; @IgnoreInHashcodeEquals @Parameter(names = "-outputToDatabaseUserPassword", description = "", required = false) public @NotPersistent String outputToDatabaseUserPassword = "testpassword34"; @FilePath @IgnoreInHashcodeEquals @Parameter(names = "-outputJSONTo", description = "Path to which JSON-formatted output should be written", required = false) public @Column(length = 1_000) String outputJSONTo = ""; @FilePath @IgnoreInHashcodeEquals @Parameter(names = "-outputSerializedTo", description = "Path to which serialized Java object output should be written", required = false) public @Column(length = 1_000) String outputSerializedTo = ""; @Parameter(names = "-outputDuplexDetails", description = "For each reported mutation, give list of its reads and duplexes", required = false) public boolean outputDuplexDetails = false; @IgnoreInHashcodeEquals @Parameter(names = "-parallelizationFactor", description = "Number of chunks into which to split each contig for parallel processing; setting this value too high can be highly counter-productive", required = false) public int parallelizationFactor = 1; @IgnoreInHashcodeEquals @Parameter(names = "-noParallelizationOfContigsBelow", description = "Processing of contigs below this size will not be parallelized", required = false) public int noParallelizationOfContigsBelow = 200_000; @IgnoreInHashcodeEquals @Parameter(names = "-contigByContigParallelization", description = "Contig-by-contig list of number of chunks into which to split contig for parallel processing; setting this value too high can be highly counter-productive; last value in the list applies to all contigs whose index falls outside of the list", required = false) public List<Integer> contigByContigParallelization = new ArrayList<>(); @IgnoreInHashcodeEquals @Parameter(names = "-maxThreadsPerPool", description = "Maximum number of threads per pool;" + " for now, to avoid deadlocks this number should be kept higher than number of inputs *" + " number of contigs * parallelization factor", required = false) public int maxThreadsPerPool = 64; @IgnoreInHashcodeEquals @Parameter(names = "-maxParallelContigs", description = "JVM-wide maximum number of concurrently analyzed contigs; first call sets final value", required = false) public int maxParallelContigs = 30; @IgnoreInHashcodeEquals @Parameter(names = "-terminateImmediatelyUponError", description = "If true, any error causes immediate termination of the run", required = false) public boolean terminateImmediatelyUponError = true; @IgnoreInHashcodeEquals @Parameter(names = "-terminateUponOutputFileError", description = "If true, any error in writing auxiliary output files causes termination of the run", required = false) public boolean terminateUponOutputFileError = true; @IgnoreInHashcodeEquals @Parameter(names = "-processingChunk", description = "Size of sliding windows used to synchronize analysis in different samples", required = false) public int processingChunk = 160; @FilePathList @NoDuplicates @Parameter(names = "-inputReads", description = "Input BAM read file, sorted and with an index; repeat as many times as there are samples", required = true) public List<@NonNull String> inputReads = new ArrayList<>(); @Parameter(names = "-computeHashForBAMSmallerThanInGB", description = "A simple hash will be computed for all input BAM files whose size is below specified threshold (in GB)", required = false) public float computeHashForBAMSmallerThanInGB = 0.5f; @Parameter(names = "-lenientSamValidation", description = "Passed to Picard; seems at least sometimes necessary for" + " alignments produced by BWA", required = false) public boolean lenientSamValidation = true; @Parameter(names = "-allowMissingSupplementaryFlag", description = "", required = false) public boolean allowMissingSupplementaryFlag = false; @FilePathList @NoDuplicates @Parameter(names = "-originalReadFile1", description = "Fastq-formatted raw read data", required = false, hidden = true) public List<@NonNull String> originalReadFile1 = new ArrayList<>(); @FilePathList @NoDuplicates @Parameter(names = "-originalReadFile2", description = "Fastq-formatted raw read data", required = false, hidden = true) public List<@NonNull String> originalReadFile2 = new ArrayList<>(); @Parameter(names = "-nRecordsToProcess", description = "Only process first N reads", required = false) public long nRecordsToProcess = Long.MAX_VALUE; @Parameter(names = "-dropReadProbability", description = "Reads will be randomly ignored with a probability given by this number") public float dropReadProbability = 0; @Parameter(names = "-randomizeMates", description = "Randomize first/second of pair; WARNING: this will lead to incorrect top/bottom strand grouping") public boolean randomizeMates = false; @UsedAtDuplexGrouping @Parameter(names = "-randomizeStrand", description = "Randomize read mapping to top or bottom strand, preserving for each duplex" + " the number in the top strand and the number in the bottom strand; WARNING: this will lead to incorrect mutation and disagreement detection") public boolean randomizeStrand = false; @FilePathList @NoDuplicates @Parameter(names = "-intersectAlignment", description = "List of BAM files with which alignments in inputReads must agree; each file must be sorted", required = false, hidden = hideInProgressParameters) public List<@NonNull String> intersectAlignment = new ArrayList<>(); @Parameter(names = "-minMappingQIntersect", description = "Minimum mapping quality for reads in intersection files", required = false, hidden = hideInProgressParameters) public List<Integer> minMappingQIntersect = new ArrayList<>(); @FilePath @Parameter(names = "-referenceGenome", description = "Reference genome in FASTA format; index file must be present", required = true) public @Column(length = 1_000) String referenceGenome = ""; @Parameter(names = "-referenceGenomeShortName", description = "e.g. ce10, hg19, etc.", required = true) public String referenceGenomeShortName = ""; @Parameter(names = "-contigNamesToProcess", description = "Reads not mapped to any of these contigs will be ignored") @NoDuplicates @NonNull List<@NonNull String> contigNamesToProcess = Arrays.asList("chrI", "chrII", "chrIII", "chrIV", "chrV", "chrX", "chrM"); { Collections.sort(contigNamesToProcess); } @Parameter(names = "-startAtPosition", description = "Formatted as chrI:12,000,000 or chrI:12000000; specify up to once per contig", required = false, converter = SwallowCommasConverter.class, listConverter = SwallowCommasConverter.class) public List<@NonNull String> startAtPositions = new ArrayList<>(); @Parameter(names = "-stopAtPosition", description = "Formatted as chrI:12,000,000 or chrI:12000000; specify up to once per contig", required = false, converter = SwallowCommasConverter.class, listConverter = SwallowCommasConverter.class) public List<@NonNull String> stopAtPositions = new ArrayList<>(); @Parameter(names = "-readContigsFromFile", description = "Read contig names from reference genome file") public boolean readContigsFromFile = false; @Parameter(names = "-traceField", description = "Output each position at which" + " specified statistic is incremented; formatted as sampleName:statisticName", required = false) @NoDuplicates public List<String> traceFields = new ArrayList<>(); @Parameter(names = "-tracePositions", description = "Log details of mutations read at specified positions", required = false, converter = SwallowCommasConverter.class, listConverter = SwallowCommasConverter.class) @NoDuplicates public List<@NonNull String> tracePositions = new ArrayList<>(); public final List<SequenceLocation> parsedTracePositions = new ArrayList<>(); @Parameter(names = "-contigStatsBinLength", description = "Length of bin to use for statistics that" + " are broken down more finely than contig by contig", required = false) public int contigStatsBinLength = 2_000_000; @Parameter(names = "-reportCoverageAtAllPositions", description = "Report key coverage statistics at every position analyzed; do not use when analyzing large regions!", arity = 1) public boolean reportCoverageAtAllPositions = false; @Parameter(names = "-minMappingQualityQ1", description = "Reads whose mapping quality is below this" + " threshold are discarded (best to keep this relatively low to allow non-unique mutation candidates to be identified in all samples)", required = false) public int minMappingQualityQ1 = 20; @Parameter(names = "-minMappingQualityQ2", description = "Reads whose mapping quality is below this" + " threshold are not used to propose Q2 mutation candidates", required = false) @OnlyUsedAfterDuplexGrouping @ExplorationIncompatibleWithRawMismatches public int minMappingQualityQ2 = 50; @Parameter(names = "-minReadsPerStrandQ1", description = "Duplexes that have fewer reads for the" + " original top and bottom strands are ignored when calling substitutions or indels", required = false) @OnlyUsedAfterDuplexGrouping public int minReadsPerStrandQ1 = 0; @Parameter(names = "-minReadsPerStrandQ2", description = "Only duplexes that have at least this number of reads" + " for original top and bottom strands can contribute Q2 candidates", required = false) @OnlyUsedAfterDuplexGrouping public int minReadsPerStrandQ2 = 3; @Parameter(names = "-minReadsPerDuplexQ2", description = "Only duplexes that have at least this total number of reads" + " (irrespective of whether they come from the original top and bottom strands) can contribute Q2 candidates", required = false) @OnlyUsedAfterDuplexGrouping public int minReadsPerDuplexQ2 = 3; @Parameter(names = "-candidateQ2Criterion", description = "Must be one of 1Q2Duplex, NQ1Duplexes", required = false) @OnlyUsedAfterDuplexGrouping public String candidateQ2Criterion = "1Q2Duplex"; @Parameter(names = "-minQ1Duplexes", description = "If candidateQ2Criterion is set to NQ1Duplexes, allow mutation candidate to be Q2 if it has at least this many Q1 duplexes", required = false, hidden = true) @OnlyUsedAfterDuplexGrouping public int minQ1Duplexes = Integer.MAX_VALUE; @Parameter(names = "-minTotalReadsForNQ1Duplexes", description = "If candidateQ2Criterion is set to NQ1Duplexes, allow mutation candidate to be Q2 only if it has at least this many supporting reads", required = false, hidden = true) @OnlyUsedAfterDuplexGrouping public int minTotalReadsForNQ1Duplexes = Integer.MAX_VALUE; /*@Parameter(names = "-promoteNSingleStrands", description = "Not yet functional, and probably never will be - Promote duplex that has just 1 original strand but at least this many reads to Q1", required = false, hidden = true) public int promoteNSingleStrands = Integer.MAX_VALUE; @Parameter(names = "-promoteFractionReads", description = "Promote candidate supported by at least this fraction of reads to Q2", required = false, hidden = hideAdvancedParameters) public float promoteFractionReads = Float.MAX_VALUE;*/ @Parameter(names = "-minConsensusThresholdQ1", description = "Lenient value for minimum fraction of reads from the same" + " original strand that define a consensus (must be > 0.5)", required = false) @OnlyUsedAfterDuplexGrouping public float minConsensusThresholdQ1 = 0.51f; @Parameter(names = "-minConsensusThresholdQ2", description = "Strict value for minimum fraction of reads from the same" + " original strand that define a consensus (must be > 0.5)", required = false) @OnlyUsedAfterDuplexGrouping public float minConsensusThresholdQ2 = 0.95f; @Parameter(names = "-disagreementConsensusThreshold", description = "NOT YET IMPLEMENTED; Disagreements are only reported if for each strand" + " consensus is above this threshold, in addition to being above minConsensusThresholdQ2", required = false, hidden = true) public float disagreementConsensusThreshold = 0.0f; @Parameter(names = "-minReadsPerStrandForDisagreement", description = "Minimal number of reads" + " for original top and bottom strands to examine duplex for disagreement between these strands", required = false) @OnlyUsedAfterDuplexGrouping public int minReadsPerStrandForDisagreement = 0; @Parameter(names = "-Q2DisagCapsMatchingMutationQuality", description = "Q2 disagreement in the same sample or in sister sample caps to Q1 the quality of matching, same-position mutations from other duplexes", required = false, arity = 1) @OnlyUsedAfterDuplexGrouping public boolean Q2DisagCapsMatchingMutationQuality = true; @CheckValues(min = 0, max = 1) @Parameter(names = "-maxMutFreqForDisag", description = "Disagreements are marked as Q0 if the frequency of matching mutation candidates at the same position is greater than this threshold; " + "note that this parameter does NOT affect coverage", required = false, arity = 1) @OnlyUsedAfterDuplexGrouping public float maxMutFreqForDisag = 1.0f; @Parameter(names = "-computeRawMismatches", description = "Compute mismatches between raw reads and reference sequence", arity = 1, required = false) public boolean computeRawMismatches = true; @CheckValues(min = 0, max = 1) @Parameter(names = "-topAlleleFreqReport", description = "Sites at which the top allele frequency is below this value are reported and marked with a % sign", required = false) public float topAlleleFreqReport = 0.3f; @CheckValues(min = 0, max = 1) @Parameter(names = "-minTopAlleleFreqQ2", description = "Only positions where the frequency of the top allele is at least this high can contribute Q2 candidates", required = false) public float minTopAlleleFreqQ2 = 0; @CheckValues(min = 0, max = 1) @Parameter(names = "-maxTopAlleleFreqQ2", description = "Only positions where the frequency of the top allele is at least this low can contribute Q2 candidates", required = false) public float maxTopAlleleFreqQ2 = 1; @Parameter(names = "-minBasePhredScoreQ1", description = "Bases whose Phred score is below this threshold" + " are discarded (keeping this relatively low helps identify problematic reads)", required = false) public int minBasePhredScoreQ1 = 20; @Parameter(names = "-minBasePhredScoreQ2", description = "Bases whose Phred score is below this threshold are not used to propose Q2 mutation candidates", required = false) @OnlyUsedAfterDuplexGrouping @ExplorationIncompatibleWithRawMismatches public int minBasePhredScoreQ2 = 30; @Parameter(names = "-ignoreFirstNBasesQ1", description = "Bases that occur within this many bases of read start are discarded", required = false) public int ignoreFirstNBasesQ1 = 4; @Parameter(names = "-ignoreFirstNBasesQ2", description = "Bases that occur within this many bases of read start are not used to propose Q2 mutation candidates", required = false) @OnlyUsedAfterDuplexGrouping @ExplorationIncompatibleWithRawMismatches public int ignoreFirstNBasesQ2 = 35; @Parameter(names = "-ignoreLastNBases", description = "Potential mutations that occur within this many bases of read end are ignored", required = false) public int ignoreLastNBases = 4; @Parameter(names = "-minReadMedianPhredScore", description = "Reads whose median Phred score is below this threshold are discarded", required = false) public int minReadMedianPhredScore = 0; @Parameter(names = {"-minMedianPhredScoreAtPosition", "-minMedianPhredQualityAtPosition"}, description = "Positions whose median Phred score is below this threshold are not used to propose Q2 mutation candidates", required = false) @OnlyUsedAfterDuplexGrouping public int minMedianPhredScoreAtPosition = 0; @Parameter(names = "-minCandidateMedianPhredScore", description = "Mutation candidates for which the median Phred score of supporting reads at the corresponding position is below this threshold are capped at Q1", required = false) @OnlyUsedAfterDuplexGrouping public int minCandidateMedianPhredScore = 20; @Parameter(names = "-maxFractionWrongPairsAtPosition", description = "Positions are not used to propose Q2 mutation candidates if the fraction of reads covering the position that have an unmapped mate or a mate that forms a wrong pair orientation (RF, Tandem) is above this threshold", required = false) public float maxFractionWrongPairsAtPosition = 1.0f; @Parameter(names = "-maxAverageBasesClipped", description = "Duplexes whose mean number of clipped bases is above this threshold are not used to propose Q2 mutation candidates", required = false) @UsedAtDuplexGrouping @ExplorationIncompatibleWithRawMismatches public int maxAverageBasesClipped = 15; @Parameter(names = "-maxAverageClippingOfAllCoveringDuplexes", description = "Positions whose average covering duplex average number of clipped bases is above this threshold are not used to propose Q2 mutation candidates", required = false) @OnlyUsedAfterDuplexGrouping public int maxAverageClippingOfAllCoveringDuplexes = 999; @Parameter(names = "-maxConcurringDuplexClipping", description = "Duplexes for which all reads have at least this many clipped bases are not counted as concurring with a mutation", required = false) @OnlyUsedAfterDuplexGrouping public int maxConcurringDuplexClipping = maxAverageBasesClipped; @Parameter(names = "-minConcurringDuplexReads", description = "Only duplexes that have at least this many reads are counted as concurring with a mutation", required = false) @OnlyUsedAfterDuplexGrouping public int minConcurringDuplexReads = 2; @Parameter(names = "-maxNDuplexes", description = "Positions whose number of Q1 or Q2 duplexes is above this threshold are ignored when computing mutation rates", required = false) public List<Integer> maxNDuplexes = new ArrayList<>(); @Parameter(names = "-maxInsertSize", description = "Inserts above this size are not used to propose Q2 mutation candidates, and will most of the time be ignored when identifying Q1 candidates", required = false) public int maxInsertSize = 1_000; @Parameter(names = "-minInsertSize", description = "Inserts below this size are not used to propose Q2 mutation candidates", required = false) public int minInsertSize = 0; @Parameter(names = "-ignoreZeroInsertSizeReads", description = "Reads 0 or undefined insert size are thrown out at the onset (and thus cannot contribute to exclusion of mutation candidates found in multiple samples)", required = false) public boolean ignoreZeroInsertSizeReads = false; @Parameter(names = "-ignoreSizeOutOfRangeInserts", description = "Reads with insert size out of range are thrown out at the onset (and thus cannot contribute to exclusion of mutation candidates found in multiple samples)", required = false) public boolean ignoreSizeOutOfRangeInserts = false; @Parameter(names = "-ignoreTandemRFPairs", description = "Read pairs that form tandem or RF are thrown out at the onset", required = false) public boolean ignoreTandemRFPairs = false; @Parameter(names = "-filterOpticalDuplicates", description = "", required = false) public boolean filterOpticalDuplicates = false; @Parameter(names = "-opticalDuplicateDistance", description = "", required = false) public int opticalDuplicateDistance = 100; @Parameter(names = "-computeAllReadDistances", description = "higher computational cost", required = false) public boolean computeAllReadDistances = false; @Parameter(names = {"-minNumberDuplexesSisterArm", "-minNumberDuplexesSisterSamples"}, description = "Min number of duplexes in sister arm to call a candidate mutation unique; adjust this number to deal with heterozygous mutations", required = false) @OnlyUsedAfterDuplexGrouping public int minNumberDuplexesSisterSamples = 10; @Parameter(names = "-minQ2DuplexesToCallMutation", description = "Min number of Q2 duplexes to call mutation (condition set by minQ1Q2DuplexesToCallMutation must also be met)", required = false) @OnlyUsedAfterDuplexGrouping public int minQ2DuplexesToCallMutation = 1; @Parameter(names = "-minQ1Q2DuplexesToCallMutation", description = "Min number of Q1 or Q2 duplexes to call mutation (condition set by minQ2DuplexesToCallMutation must also be met)", required = false) @OnlyUsedAfterDuplexGrouping public int minQ1Q2DuplexesToCallMutation = 1; @Parameter(names = "-acceptNInBarCode", description = "If true, an N read within the barcode is" + " considered a match", required = false) public boolean acceptNInBarCode = true; @Parameter(names = "-variableBarcodeLength", description = "Length of variable barcode, irrespective of whether it has been removed from the aligned sequences", required = false) public int variableBarcodeLength = 3; @Parameter(names = "-constantBarcode", description = "Used to only analyze reads whose constant barcode matches expected value", required = false) public @NonNull String constantBarcode = "TCT"; @Parameter(names = "-nVariableBarcodeMismatchesAllowed", description = "Used for variable barcode matching", required = false) public int nVariableBarcodeMismatchesAllowed = 1; @Parameter(names = "-nConstantBarcodeMismatchesAllowed", description = "Used for constant barcode matching", required = false) public int nConstantBarcodeMismatchesAllowed = 3; @Parameter(names = "-alignmentPositionMismatchAllowed", description = "Reads assigned to same duplex must have alignment positions match within this tolerance (see also parameter requireMatchInAlignmentEnd)", required = false) public int alignmentPositionMismatchAllowed = 0; @Parameter(names = "-requireMatchInAlignmentEnd", description = "Used while grouping reads into duplexes; turn off if alignments were aggregated from sequencing runs with different read lengths", required = false) public boolean requireMatchInAlignmentEnd = false; @Parameter(names = "-computeDuplexGroupingStats", description = "Off by default for higher performance", required = false) public boolean computeDuplexGroupingStats = false; @FilePathList @NoDuplicates @Parameter(names = "-saveFilteredReadsTo", description = "Not implemented; write raw reads that were kept for analysis to specified files", required = false, hidden = hideInProgressParameters) public List<@NonNull String> saveFilteredReadsTo = new ArrayList<>(); @Parameter(names = "-collapseFilteredReads", description = "Only write one (randomly-chosen) read pair per duplex strand", required = false) public boolean collapseFilteredReads = false; @Parameter(names = "-writeBothStrands", description = "Used in conjunction with -collapseFilteredReads; write read pairs from both the top and the bottom strand, when available", required = false, arity = 1) public boolean writeBothStrands = true; @Parameter(names = "-clipPairOverlap", description = "Hard clip overlap between read pairs (currently does not add an H block to the Cigar); requires -collapseFilteredReads", required = false) public boolean clipPairOverlap = false; @FilePathList @NoDuplicates @Parameter(names = "-bamReadsWithBarcodeField", description = "Unimplemented; BAM/SAM file saved from previous run with barcodes stored as attributes", required = false, hidden = hideInProgressParameters) public List<@NonNull String> bamReadsWithBarcodeField = new ArrayList<>(); @Parameter(names = "-saveRawReadsDB", description = "Not functional at present", required = false, arity = 1, hidden = hideInProgressParameters) public boolean saveRawReadsDB = false; @Parameter(names = "-saveRawReadsMVDB", description = "Not functional at present", required = false, arity = 1, hidden = hideInProgressParameters) public boolean saveRawReadsMVDB = false; @Parameter(names = "-outputCoverageBed", description = "Output bed file that gives number of duplexes covering each position in the reference sequence;" + " note that this is a highly-inefficient format that creates a huge file", required = false) public boolean outputCoverageBed = false; @Parameter(names = "-outputCoverageProto", description = "Output protobuf file that gives number of duplexes covering each position in the reference sequence", required = false) public boolean outputCoverageProto = false; /** * Output section */ @NoDuplicates @Parameter(names = "-sampleName", description = "Used to name samples in output file; can be repeated as many times as there are inputReads", required = false) public List<@NonNull String> sampleNames = new ArrayList<>(); @FilePathList @NoDuplicates @Parameter(names = {"-forceOutputAtPositionsTextFile", "-forceOutputAtPositionsFile"}, description = "Detailed information is reported for all positions listed in the file", required = false) public List<@NonNull String> forceOutputAtPositionsTextFile = new ArrayList<>(); @FilePathList @NoDuplicates @Parameter(names = "-forceOutputAtPositionsBinFile", description = "Detailed information is reported for all positions listed in the file", required = false) public List<@NonNull String> forceOutputAtPositionsBinFile = new ArrayList<>(); @Parameter(names = "-forceOutputAtPositions", description = "Detailed information is reported for positions given as ranges", required = false, converter = SwallowCommasConverter.class, listConverter = SwallowCommasConverter.class) public @NoDuplicates List<@NonNull String> forceOutputAtPositions = new ArrayList<>(); @FilePath @Parameter(names = "-annotateMutationsInFile", description = "TODO", required = false) public @Column(length = 1_000) String annotateMutationsInFile = null; @FilePath @Parameter(names = "-annotateMutationsOutputFile", description = "TODO", required = false) public @Column(length = 1_000) String annotateMutationsOutputFile = null; @Parameter(names = "-randomOutputRate", description = "Randomly choose genome positions at this rate to include in output", required = false) public float randomOutputRate = 0; @FilePathList @IgnoreInHashcodeEquals @Parameter(names = "-outputAlignmentFile", description = "Write BAM output with duplex information provided in custom tags;" + " note that a read may be omitted from the output, e.g. if it falls below a Q1 threshold (it is" + " relatively rare but possible for a read to be omitted even though it counts toward coverage). Specify" + " parameter once for all reads to go to same output file (with different AI tags), or as many times" + " as there are input files", required = false) public @NonNull @Column(length = 1_000) List<String> outputAlignmentFile = new ArrayList<>(); @FilePath @Parameter(names = "-discardedReadFile", description = "Write discarded reads to BAM file specified by parameter", required = false, hidden = hideInProgressParameters) public @Column(length = 1_000) String discardedReadFile = null; @Parameter(names = "-logReadIssuesInOutputBam", description = "Use custom fields in output BAM to give reasons why duplexes as a whole or individual bases did not reach maximum quality", required = false, arity = 1) public boolean logReadIssuesInOutputBam = true; @Parameter(names = "-sortOutputAlignmentFile", description = "Sort BAM file; can require a large amount of memory", required = false, arity = 1) public boolean sortOutputAlignmentFile = false; @Parameter(names = "-outputTopBottomDisagreementBED", description = "Output to file specified by option -topBottomDisagreementFileBaseName", required = false, arity = 1) public boolean outputTopBottomDisagreementBED = true; @FilePathList @NoDuplicates @Parameter(names = "-reportStatsForBED", description = "Report number of observations that fall within" + " the union of regions listed by BED file whose path follows", required = false) public List<@NonNull String> reportStatsForBED = new ArrayList<>(); @FilePathList @NoDuplicates @Parameter(names = "-reportStatsForNotBED", description = "Report number of observations that do *not* fall within" + " the union of regions listed by BED file whose path follows", required = false) public List<@NonNull String> reportStatsForNotBED = new ArrayList<>(); @FilePathList @NoDuplicates @Parameter(names = "-excludeRegionsInBED", description = "Positions covered by this BED file will be completely ignored in the analysis", required = false) public List<@NonNull String> excludeRegionsInBED = new ArrayList<>(); @FilePathList @NoDuplicates @Parameter(names = "-repetiveRegionBED", description = "If specified, used for stats (mutant|wt)Q2CandidateQ1Q2DCoverage[Non]Repetitive", required = false) public List<@NonNull String> repetiveRegionBED = new ArrayList<>(); @FilePath @Parameter(names = "-bedDisagreementOrienter", description = "Gene orientation read from this file" + " is used to orient top/bottom strand disagreements with respect to transcribed strand", required = false) public @Column(length = 1_000) String bedDisagreementOrienter = null; @FilePathList @NoDuplicates @Parameter(names = "-reportBreakdownForBED", description = "Report number of observations that fall within" + " each of the regions defined by BED file whose path follows", required = false) public List<@NonNull String> reportBreakdownForBED = new ArrayList<>(); @FilePathList @NoDuplicates @Parameter(names = {"-saveBEDBreakdownToPathPrefix", "-saveBEDBreakdownTo"}, description = "Path prefix for saving of BED region counts; argument " + " list must match that given to -reportBreakdownForBED", required = false) public List<@NonNull String> saveBEDBreakdownToPathPrefix = new ArrayList<>(); @FilePath @Parameter(names = "-bedFeatureSuppInfoFile", description = "Read genome annotation supplementary info, used in output of counter with BED feature breakdown") public @Column(length = 1_000) String bedFeatureSuppInfoFile = null; @FilePath @Parameter(names = "-refSeqToOfficialGeneName", description = "Tab separated text file with RefSeq ID, tab, and official gene name and any other useful info; " + "counts will be reported both by RefSeq ID and official gene name") public @Column(length = 1_000) String refSeqToOfficialGeneName = null; @FilePath @Parameter(names = "-auxOutputFileBaseName", description = "Base name of files to which to record mutations, disagreements between top and bottom strands, etc.", required = false) public @Column(length = 1_000) String auxOutputFileBaseName = null; public String jsonFilePathExtraPrefix = ""; @Parameter(names = "-rnaSeq", description = "Ignore deletions and turn off checks that do not make sense for RNAseq data", required = false) public boolean rnaSeq = false; @Parameter(names = "-submitToServer", description = "RMI address", required = false, hidden = hideInProgressParameters) public String submitToServer = null; @IgnoreInHashcodeEquals @Parameter(names = "-writePIDPath", description = "Write PID to this file when ready", required = false, hidden = hideInProgressParameters) public String writePIDPath = null; @Parameter(names = "-startServer", help = true, description = "RMI address", required = false, hidden = hideInProgressParameters) public String startServer = null; @Parameter(names = "-startWorker", help = true, description = "RMI server address", required = false, hidden = hideInProgressParameters) public String startWorker = null; @IgnoreInHashcodeEquals @Parameter(names = "-timeoutSeconds", help = true, description = "If this many seconds elapse without ping from worker, worker is considered dead", required = false, hidden = hideInProgressParameters) public int timeoutSeconds = 0; @FilePath @Parameter(names = "-workingDirectory", help = true, description = "Evaluate parameter file paths using specified directory as workind directory", required = false, hidden = hideAdvancedParameters) public @Column(length = 1_000) String workingDirectory = null; @FilePath @Parameter(names = "-referenceOutput", description = "Path to reference output to be used for functional tests", required = false, hidden = hideAdvancedParameters) public @Column(length = 1_000) String referenceOutput = null; @FilePath @Parameter(names = "-recordRunsTo", description = "Get server to output a record of all runs it processed, to be replayed for functional tests", required = false, hidden = hideAdvancedParameters) public @Column(length = 1_000) String recordRunsTo = null; @Parameter(names = "-runName", description = "Name of run to be used in conjunction with -recordRunsTo", required = false, hidden = hideAdvancedParameters) public String runName = null; @Parameter(names = "-enableCostlyAssertions", description = "Enable internal sanity checks that significantly slow down execution", required = false, arity = 1) public boolean enableCostlyAssertions = true; @Parameter(names = "-jiggle", description = "Internally jiggle the data in a way that should not change the important outputs; use in combination with random seed to get reproducible jiggling", required = false) public boolean jiggle = false; @Parameter(names = "-randomSeed", description = "TODO", required = false, hidden = hideAdvancedParameters) public long randomSeed = new SecureRandom().nextLong(); @IgnoreInHashcodeEquals @Parameter(names = "-keysFile", description = "Location of .jks file for RMI SSL encryption", required = false, hidden = hideAdvancedParameters) public String keysFile = "mutinack_public_selfsigned.jks"; @IgnoreInHashcodeEquals @Parameter(names = "-exploreParameter", description = "Perform mutation detection separately for each parameter value specified as name:min:max[:n_steps]", required = false, hidden = true) public @NoDuplicates List<String> exploreParameters = new ArrayList<>(); @IgnoreInHashcodeEquals @Parameter(names = "-cartesianProductOfExploredParameters", description = "", required = false, hidden = true, arity = 1) public boolean cartesianProductOfExploredParameters = true; @IgnoreInHashcodeEquals @Parameter(names = "-includeInsertionsInParamExploration", description = "", required = false, hidden = true, arity = 1) public boolean includeInsertionsInParamExploration = false; @Retention(RetentionPolicy.RUNTIME) /** * Used to mark parameters that it is not useful to print in toString method. * @author olivier * */ public @interface HideInToString {} @Retention(RetentionPolicy.RUNTIME) public @interface IgnoreInHashcodeEquals {} @Retention(RetentionPolicy.RUNTIME) public @interface OnlyUsedAfterDuplexGrouping {} @Retention(RetentionPolicy.RUNTIME) public @interface ExplorationIncompatibleWithRawMismatches {} @Retention(RetentionPolicy.RUNTIME) public @interface UsedAtDuplexGrouping {} @Retention(RetentionPolicy.RUNTIME) private @interface NoDuplicates {} @Retention(RetentionPolicy.RUNTIME) public @interface FilePath {} @Retention(RetentionPolicy.RUNTIME) public @interface FilePathList {} @Retention(RetentionPolicy.RUNTIME) public @interface CheckValues { String [] permissibleStrings() default {}; float min() default Float.NaN; float max() default Float.NaN; } public void canonifyFilePaths() { transformFilePaths(s -> { try { File f = new File(s); String canonical = f.getCanonicalPath(); if (f.isDirectory()) { return canonical + '/'; } else { return canonical; } } catch (IOException e) { throw new RuntimeException(e); } }); } public void transformFilePaths(Function<String, String> transformer) { FieldIteration.iterateFields((field, fieldValue) -> { if (fieldValue == null) { return; } if (field.getAnnotation(FilePath.class) != null) { Assert.isTrue(fieldValue instanceof String, "Field %s not string", field); String path = (String) fieldValue; String transformed = transformer.apply(path); field.set(this, transformed); } else if (field.getAnnotation(FilePathList.class) != null) { Assert.isTrue(fieldValue instanceof List, "Field %s not list", field); @SuppressWarnings("unchecked") List<String> paths = (List<String>) fieldValue; for (int i = 0; i < paths.size(); i++) { String path = paths.get(i); String transformed = transformer.apply(path); paths.set(i, transformed); } } }, this); } /** * Used to make JCommander ignore commas in genome locations. * @author olivier * */ public static class SwallowCommasConverter extends BaseConverter<String> implements IStringConverter<String> { public SwallowCommasConverter(String optionName) { super(optionName); } @Override public String convert(String value) { return value.replaceAll(",", ""); } } @HideInToString @JsonIgnore @IgnoreInHashcodeEquals private static final Parameters defaultValues = new Parameters(); private static final Set<String> fieldsToIgnore = new HashSet<>(); static { fieldsToIgnore.add("$jacocoData"); fieldsToIgnore.add("dnFieldFlags"); fieldsToIgnore.add("dnFieldTypes"); fieldsToIgnore.add("dnFieldNames"); } @Override public String toString() { String defaultValuesString = ""; String nonDefaultValuesString = ""; for (Field field: Parameters.class.getDeclaredFields()) { try { field.setAccessible(true); if (field.getAnnotation(HideInToString.class) != null) continue; if (fieldsToIgnore.contains(field.getName())) { continue; } Object fieldValue = field.get(this); Assert.isFalse(fieldValue instanceof Parameters);//Avoid infinite //recursion and StackOverflowError during mutation testing Object fieldDefaultValue = field.get(defaultValues); String stringValue; if (fieldValue == null) stringValue = field.getName() + " = null"; else { Method toStringMethod = fieldValue.getClass().getMethod("toString"); toStringMethod.setAccessible(true); stringValue = field.getName() + " = " + toStringMethod.invoke (fieldValue); } final boolean fieldHasDefaultValue; if (fieldValue == null) { fieldHasDefaultValue = fieldDefaultValue == null; } else { Method equalsMethod = fieldValue.getClass().getMethod("equals", Object.class); equalsMethod.setAccessible(true); fieldHasDefaultValue = (Boolean) equalsMethod.invoke(fieldValue, fieldDefaultValue); } if (fieldHasDefaultValue) { defaultValuesString += "Default parameter value: " + stringValue + '\n'; } else { nonDefaultValuesString += "Non-default parameter value: " + stringValue + '\n'; } } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new RuntimeException(e); } } return "Working directory: " + System.getProperty("user.dir") + '\n' + nonDefaultValuesString + '\n' + defaultValuesString + '\n'; } public Object getFieldValue(String name) { try { Field f = Parameters.class.getDeclaredField(name); return f.get(this); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } public boolean isParameterInstanceOf(String name, Class<?> clazz) { Field f; try { f = Parameters.class.getDeclaredField(name); return clazz.isInstance(f.get(this)); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } public void setFieldValue(String name, Object value) { try { Field f = Parameters.class.getDeclaredField(name); if (f.get(this) instanceof Integer) { f.set(this, ((Number) value).intValue()); } else if (f.get(this) instanceof Float) { f.set(this, ((Number) value).floatValue()); } else if (f.get(this) instanceof Boolean) { f.set(this, value); } else throw new IllegalArgumentException("Field " + name + " is not Integer, Float, or Boolean"); } catch (ClassCastException e) { throw new RuntimeException("Class of " + " value " + " does not match field " + name, e); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } public static List<String> differingFields(Parameters obj1, Parameters obj2) { List<String> result = new ArrayList<>(); for (Field field: Parameters.class.getDeclaredFields()) { try { if (field.getAnnotation(HideInToString.class) != null) continue; if (field.getName().equals("$jacocoData")) { continue; } if (!Objects.equals(field.get(obj1), field.get(obj2))) { result.add(field.getName()); } } catch (IllegalArgumentException | IllegalAccessException | SecurityException e) { throw new RuntimeException(e); } } return result; } public static Set<String> differingFields(List<Parameters> list) { Set<String> result = new HashSet<>(); for (int i = list.size() - 1; i >= 0; i for (int j = 0; j < i; j++) { result.addAll(differingFields(list.get(i), list.get(j))); } } return result; } public static void getUnsortedUsage(JCommander jc, Class<?> paramClass, StringBuilder out) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { List<@NonNull Field> fields = Arrays.asList(paramClass.getDeclaredFields()); // Special treatment of main parameter. ParameterDescription mainParam = jc.getMainParameter(); if (mainParam != null) { out.append("Required parameters:\n"); out.append(" ").append(mainParam.getDescription()).append('\n'); } @SuppressWarnings("null") String requiredParams = fields.stream().map(f -> f.getAnnotation(Parameter.class)). filter(Objects::nonNull). filter(a -> (!a.hidden()) && a.required()).map(a -> a.names()[0]). collect(Collectors.joining(", ")); if (! "".equals(requiredParams)) { out.append("Required parameters: " + requiredParams + " (see explanations marked with *** below)\n"); } out.append("Options:\n"); List<ParameterDescription> params = jc.getParameters(); final Field getWrapperParameter = ParameterDescription.class.getDeclaredField("m_wrappedParameter"); getWrapperParameter.setAccessible(true); for (Field f: fields) { boolean required = false; Parameter annotation = f.getAnnotation(Parameter.class); if (annotation != null) { if (annotation.hidden()) { continue; } if (annotation.required()) { required = true; } } else { continue; } int nIt = 0; Handle<String> suffix = new Handle<>(""); outer: while (true) { if (nIt == 1) { suffix.set("s"); } else if (nIt == 2) { throw new RuntimeException("Could not find field annotation for " + f.getName()); } nIt++; for (ParameterDescription p: params) { List<String> names = Arrays.asList(((WrappedParameter) getWrapperParameter.get(p)).names()).stream().map( s -> s.substring(1) + suffix.get()).collect(Collectors.toList()); if (names.contains(f.getName())) { out.append(p.getNames()).append('\n'); String def = (required ? "\nRequired parameter" : (p.getDefault() == null ? "" : ("\nDefault: " + p.getDefault().toString().trim() + '.'))) + '\n'; String desc = wordWrap(p.getDescription(), 75) + def; desc = " " + desc; desc = desc.replaceAll("\n", "\n ") + '\n'; desc = desc.replaceAll(" Required parameter", "**** Required parameter"); out.append(desc); break outer; } } } } } /** * Copied from StackOverflow * @param s String without pre-existing line breaks * @param nColumns * @return */ private static String wordWrap(String s, int nColumns) { StringBuilder sb = new StringBuilder(s); int i = 0; while (i + nColumns < sb.length() && (i = sb.lastIndexOf(" ", i + nColumns)) != -1) { sb.replace(i, i + 1, "\n"); } return sb.toString(); } @Override public Parameters clone() { try { return (Parameters) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } @Override public int hashCode() { SettableInteger hashCode = new SettableInteger(0); FieldIteration.iterateFields((f, value) -> { if (f.getAnnotation(IgnoreInHashcodeEquals.class) == null) { hashCode.set(hashCode.get() * 31 + Objects.hashCode(value)); } }, this); return hashCode.get(); } @Override public boolean equals(Object other0) { Handle<Boolean> notEqual = new Handle<>(false); Parameters other = (Parameters) other0; FieldIteration.iterateFields((f, value) -> { if (notEqual.get()) { return; } if (f.getAnnotation(IgnoreInHashcodeEquals.class) == null) { if (!Objects.equals(value, f.get(other))) { notEqual.set(true); } } }, this); return !notEqual.get(); } }
package rtdc.web.server.servlet; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rtdc.core.event.ActionCompleteEvent; import rtdc.core.event.ErrorEvent; import rtdc.core.event.FetchUserEvent; import rtdc.core.event.FetchUsersEvent; import rtdc.core.exception.ValidationException; import rtdc.core.json.JSONObject; import rtdc.core.model.Permission; import rtdc.core.model.SimpleValidator; import rtdc.core.model.User; import rtdc.web.server.config.PersistenceConfig; import rtdc.web.server.model.UserCredentials; import rtdc.web.server.service.AsteriskRealTimeService; import rtdc.web.server.service.AuthService; import javax.annotation.security.RolesAllowed; import javax.servlet.http.HttpServletRequest; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.ws.rs.*; import javax.ws.rs.core.Context; import java.sql.SQLException; import java.util.List; import java.util.Set; @Path("users") public class UserServlet { private static final Logger log = LoggerFactory.getLogger(UserServlet.class); @GET @RolesAllowed({Permission.USER, Permission.ADMIN}) public String getUsers(@Context HttpServletRequest req){ Session session = PersistenceConfig.getSessionFactory().openSession(); Transaction transaction = null; List<User> users = null; try{ transaction = session.beginTransaction(); users = (List<User>) session.createCriteria(User.class).list(); transaction.commit(); // TODO: Replace string with actual username log.info("{}: USER: Getting all users for user.", "Username"); } catch (RuntimeException e) { if(transaction != null) transaction.rollback(); throw e; } finally{ session.close(); } return new FetchUsersEvent(users).toString(); } @GET @Path("{username}") @Consumes("application/x-www-form-urlencoded") @RolesAllowed({Permission.USER, Permission.ADMIN}) public String getUser(@Context HttpServletRequest req, @Context User user, @PathParam("username") String username){ Session session = PersistenceConfig.getSessionFactory().openSession(); Transaction transaction = null; User retrievedUser = null; try{ transaction = session.beginTransaction(); List<User> userList = (List<User>) session.createCriteria(User.class).add(Restrictions.eq("username", username)).list(); if(!userList.isEmpty()) retrievedUser = userList.get(0); else return new ErrorEvent("No user with username " + username + " found.").toString(); transaction.commit(); log.info("{}: USER: Getting user + " + retrievedUser.getUsername() + " for user.", user.getUsername()); } catch (RuntimeException e) { if(transaction != null) transaction.rollback(); throw e; } finally{ session.close(); } return new FetchUserEvent(retrievedUser).toString(); } @POST @Path("add") @Consumes("application/x-www-form-urlencoded") @Produces("application/json") @RolesAllowed({Permission.USER, Permission.ADMIN}) public String addUser(@Context HttpServletRequest req, @Context User user, @FormParam("user") String userString, @FormParam("password") String password){ User newUser = new User(new JSONObject(userString)); Set<ConstraintViolation<User>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(newUser); if(!violations.isEmpty()) { log.warn("Error adding user: " + violations.toString()); return new ErrorEvent(violations.toString()).toString(); } try { SimpleValidator.validateUser(newUser); SimpleValidator.validatePassword(password); }catch (ValidationException e){ log.warn("Error adding user: " + e.getMessage()); return new ErrorEvent(e.getMessage()).toString(); } Session session = PersistenceConfig.getSessionFactory().openSession(); Transaction transaction = null; try{ transaction = session.beginTransaction(); session.saveOrUpdate(newUser); UserCredentials credentials = AuthService.generateUserCredentials(newUser, password); session.saveOrUpdate(credentials); AsteriskRealTimeService.addUser(newUser, credentials.getAsteriskPassword()); transaction.commit(); log.info("{}: USER: New user added: {}", user.getUsername(), userString); } catch (RuntimeException e) { if(transaction != null) transaction.rollback(); throw e; } finally { session.close(); } return new ActionCompleteEvent(newUser.getId(), "user", "add").toString(); } @PUT @Consumes("application/x-www-form-urlencoded") @Produces("application/json") @RolesAllowed({Permission.USER, Permission.ADMIN}) public String editUser(@Context HttpServletRequest req, @Context User user, @FormParam("user") String userString, @FormParam("password") String password, @FormParam("changePassword") String changePassword){ User editedUser = new User(new JSONObject(userString)); Set<ConstraintViolation<User>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(editedUser); if(!violations.isEmpty()) return new ErrorEvent(violations.toString()).toString(); try { SimpleValidator.validateUser(editedUser); }catch (ValidationException e){ log.warn("Error editing user: " + e.getMessage()); return new ErrorEvent(e.getMessage()).toString(); } Session session = PersistenceConfig.getSessionFactory().openSession(); Transaction transaction = null; try{ transaction = session.beginTransaction(); session.merge(editedUser); transaction.commit(); log.info("{}: USER: User updated: {}", user.getUsername(), userString); } catch (RuntimeException e) { if(transaction != null) transaction.rollback(); throw e; } finally { session.close(); } if(Boolean.parseBoolean(changePassword) && !password.isEmpty()) AuthService.editPassword(editedUser, password); return new ActionCompleteEvent(user.getId(), "user", "update").toString(); } @DELETE @Path("{id}") @Produces("application/json") @RolesAllowed({Permission.USER, Permission.ADMIN}) public String deleteUser(@Context HttpServletRequest req, @Context User user, @PathParam("id") String idString){ Session session = PersistenceConfig.getSessionFactory().openSession(); Transaction transaction = null; int id = Integer.valueOf(idString); try{ log.warn("Deleting user with id " + id); transaction = session.beginTransaction(); User userToDelete = (User) session.load(User.class, id); session.delete(userToDelete); AsteriskRealTimeService.deleteUser(userToDelete); transaction.commit(); log.warn("{}: USER: User deleted: {}", user.getUsername(), userToDelete.getUsername()); } catch (RuntimeException e) { if(transaction != null) transaction.rollback(); throw e; } finally { session.close(); } return new ActionCompleteEvent(id, "user", "delete").toString(); } }
package info.xiaomo.thymeleaf.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ThymeleafController { @RequestMapping("/") public String hello(ModelMap map) { map.put("hello", "thymeleaf!"); return "index"; } }
package cz.hobrasoft.pdfmu; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import cz.hobrasoft.pdfmu.operation.Operation; import cz.hobrasoft.pdfmu.operation.OperationAttach; import cz.hobrasoft.pdfmu.operation.OperationException; import cz.hobrasoft.pdfmu.operation.metadata.OperationMetadata; import cz.hobrasoft.pdfmu.operation.signature.OperationSignature; import cz.hobrasoft.pdfmu.operation.version.OperationVersion; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.LogManager; import java.util.logging.Logger; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparsers; /** * The main class of PDFMU * * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a> */ public class Main { private static void disableLoggers() { LogManager.getLogManager().reset(); // Remove the handlers } private static final Logger logger = Logger.getLogger(Main.class.getName()); /** * The main entry point of PDFMU * * @param args the command line arguments */ public static void main(String[] args) { // Configure log message format // Arguments: // http://docs.oracle.com/javase/7/docs/api/java/util/logging/SimpleFormatter.html#format%28java.util.logging.LogRecord%29 // %4$s: level // %5$s: message System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%n"); // Create a command line argument parser ArgumentParser parser = ArgumentParsers.newArgumentParser("pdfmu") .description("Manipulate a PDF document") .defaultHelp(true); // TODO: Use an enum parser.addArgument("-of", "--output_format") .choices("text", "json") .setDefault("text") .type(String.class) .nargs("?") .help("format of stdout output"); // TODO: Set pdfmu version in `parser`. For example: // parser.version("1.0"); // http://argparse4j.sourceforge.net/usage.html#argumentparser-version // Try to extract the version from `pom.xml`. // Once the version has been set, enable a CL argument: // parser.addArgument("-v", "--version") // .help("print version of pdfmu") // .action(Arguments.version()); // Create a Subparsers instance for operation subparsers Subparsers subparsers = parser.addSubparsers() .help("operation to execute") .metavar("OPERATION") .dest("operation"); // Create a map of operations SortedMap<String, Operation> operations = new TreeMap<>(); operations.put("version", OperationVersion.getInstance()); operations.put("signature", OperationSignature.getInstance()); operations.put("attach", OperationAttach.getInstance()); operations.put("metadata", OperationMetadata.getInstance()); // Configure operation subparsers for (Map.Entry<String, Operation> e : operations.entrySet()) { String name = e.getKey(); Operation operation = e.getValue(); operation.configureSubparser(subparsers.addParser(name)); } // Parse command line arguments Namespace namespace = null; try { // If help is requested, // `parseArgs` prints help message and throws `ArgumentParserException` // (so `namespace` stays null). // If insufficient or invalid `args` are given, // `parseArgs` throws `ArgumentParserException`. namespace = parser.parseArgs(args); } catch (ArgumentParserException e) { // Prints information about the parsing error (missing argument etc.) parser.handleError(e); } // Handle command line arguments if (namespace != null) { // Extract operation name String operationName = namespace.getString("operation"); assert operationName != null; // The argument "operation" is a sub-command, thus it is required // Select the operation from `operations` Operation operation = operations.get(operationName); assert operation != null; // Choose the output format String outputFormat = namespace.getString("output_format"); switch (outputFormat) { case "json": // Initialize the JSON serializer ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); // Enable nice formatting WritingMapper wm = new WritingMapper(mapper, System.err); // Bind to `System.err` operation.setWritingMapper(wm); // Configure the operation // Disable loggers disableLoggers(); break; case "text": // Initialize the text output TextOutput to = new TextOutput(System.err); // Bind to `System.err` operation.setTextOutput(to); // Configure the operation break; default: assert false; // The option has limited choices } // Execute the operation try { operation.execute(namespace); } catch (OperationException ex) { // Log the exception logger.severe(ex.getMessage()); Throwable cause = ex.getCause(); if (cause != null && cause.getMessage() != null) { logger.severe(cause.getMessage()); } // TODO: Output a JSON document if "-of=json" } } // TODO: Return an exit code } }
package toothpick.compiler.factory; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedOptions; import javax.inject.Inject; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; import toothpick.Factory; import toothpick.compiler.common.ToothpickProcessor; import toothpick.compiler.factory.generators.FactoryGenerator; import toothpick.compiler.factory.targets.ConstructorInjectionTarget; import toothpick.compiler.registry.generators.RegistryGenerator; import toothpick.compiler.registry.targets.RegistryInjectionTarget; import toothpick.registries.factory.AbstractFactoryRegistry; import static java.lang.String.format; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; @SupportedAnnotationTypes({ ToothpickProcessor.INJECT_ANNOTATION_CLASS_NAME }) @SupportedOptions({ ToothpickProcessor.PARAMETER_REGISTRY_PACKAGE_NAME, ToothpickProcessor.PARAMETER_REGISTRY_CHILDREN_PACKAGE_NAMES, ToothpickProcessor.PARAMETER_EXCLUDES }) public class FactoryProcessor extends ToothpickProcessor { private Map<TypeElement, ConstructorInjectionTarget> mapTypeElementToConstructorInjectionTarget = new LinkedHashMap<>(); @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { findAndParseTargets(roundEnv); if (!roundEnv.processingOver()) { return false; } // Generate Factories List<TypeElement> elementsWithFactoryCreated = new ArrayList<>(); for (Map.Entry<TypeElement, ConstructorInjectionTarget> entry : mapTypeElementToConstructorInjectionTarget.entrySet()) { ConstructorInjectionTarget constructorInjectionTarget = entry.getValue(); FactoryGenerator factoryGenerator = new FactoryGenerator(constructorInjectionTarget); TypeElement typeElement = entry.getKey(); String fileDescription = format("Factory for type %s", typeElement); boolean success = writeToFile(factoryGenerator, fileDescription, typeElement); if (success) { elementsWithFactoryCreated.add(typeElement); } } // Generate Registry //this allows tests to by pass the option mechanism in processors if (toothpickRegistryPackageName != null || readProcessorOptions()) { RegistryInjectionTarget registryInjectionTarget = new RegistryInjectionTarget(Factory.class, AbstractFactoryRegistry.class, toothpickRegistryPackageName, toothpickRegistryChildrenPackageNameList, elementsWithFactoryCreated); RegistryGenerator registryGenerator = new RegistryGenerator(registryInjectionTarget); String fileDescription = "Factory registry"; Element[] allTypes = elementsWithFactoryCreated.toArray(new Element[elementsWithFactoryCreated.size()]); writeToFile(registryGenerator, fileDescription, allTypes); } return false; } private void findAndParseTargets(RoundEnvironment roundEnv) { for (ExecutableElement constructorElement : ElementFilter.constructorsIn(roundEnv.getElementsAnnotatedWith(Inject.class))) { TypeElement enclosingElement = (TypeElement) constructorElement.getEnclosingElement(); if (!isSingleInjectedConstructor(constructorElement)) { error(constructorElement, "Class %s cannot have more than one @Inject annotated constructor.", enclosingElement.getQualifiedName()); } parseInjectedConstructor(constructorElement, mapTypeElementToConstructorInjectionTarget); } //optimistically, we try to generate a factory for injected classes. //we want to alleviate the burden of creating @Inject constructors in trivially injected classes (those which //are bound to themselves, which is the default. //but we should process injected fields when they are of a class type, //not an interface. We could also create factories for them, if possible. //that would allow not to have to declare an annotation constructor in the //dependency. We would only use the default constructor. for (VariableElement fieldElement : ElementFilter.fieldsIn(roundEnv.getElementsAnnotatedWith(Inject.class))) { parseInjectedField(fieldElement, mapTypeElementToConstructorInjectionTarget); } //we do the same for all arguments of all methods for (ExecutableElement methodElement : ElementFilter.methodsIn(roundEnv.getElementsAnnotatedWith(Inject.class))) { parseInjectedMethod(methodElement, mapTypeElementToConstructorInjectionTarget); } } private boolean isSingleInjectedConstructor(Element constructorElement) { TypeElement enclosingElement = (TypeElement) constructorElement.getEnclosingElement(); boolean isSingleInjectedConstructor = true; List<ExecutableElement> constructorElements = ElementFilter.constructorsIn(enclosingElement.getEnclosedElements()); for (ExecutableElement constructorElementInClass : constructorElements) { if (constructorElementInClass.getAnnotation(Inject.class) != null && !constructorElement.equals(constructorElementInClass)) { isSingleInjectedConstructor = false; } } return isSingleInjectedConstructor; } private void parseInjectedConstructor(ExecutableElement constructorElement, Map<TypeElement, ConstructorInjectionTarget> targetClassMap) { TypeElement enclosingElement = (TypeElement) constructorElement.getEnclosingElement(); // Verify common generated code restrictions. if (!isValidInjectConstructor(constructorElement)) { return; } if (!isValidInjectedType(enclosingElement)) { return; } targetClassMap.put(enclosingElement, createConstructorInjectionTarget(constructorElement)); //optimistic creation of factories for constructor param types parseInjectedParameters(constructorElement, mapTypeElementToConstructorInjectionTarget); } private void parseInjectedField(VariableElement fieldElement, Map<TypeElement, ConstructorInjectionTarget> mapTypeElementToConstructorInjectionTarget) { // Verify common generated code restrictions. if (!isValidInjectField(fieldElement)) { return; } final TypeElement fieldTypeElement = (TypeElement) typeUtils.asElement(fieldElement.asType()); if (mapTypeElementToConstructorInjectionTarget.containsKey(fieldTypeElement)) { //the class is already known return; } // Verify common generated code restrictions. if (!isValidInjectedType(fieldTypeElement)) { return; } ConstructorInjectionTarget constructorInjectionTarget = createConstructorInjectionTarget(fieldElement); if (constructorInjectionTarget != null) { mapTypeElementToConstructorInjectionTarget.put(fieldTypeElement, constructorInjectionTarget); } } private void parseInjectedMethod(ExecutableElement methodElement, Map<TypeElement, ConstructorInjectionTarget> mapTypeElementToConstructorInjectionTarget) { // Verify common generated code restrictions. if (!isValidInjectMethod(methodElement)) { return; } parseInjectedParameters(methodElement, mapTypeElementToConstructorInjectionTarget); } private void parseInjectedParameters(ExecutableElement methodElement, Map<TypeElement, ConstructorInjectionTarget> mapTypeElementToConstructorInjectionTarget) { for (VariableElement paramElement : methodElement.getParameters()) { final TypeElement paramTypeElement = (TypeElement) typeUtils.asElement(paramElement.asType()); if (mapTypeElementToConstructorInjectionTarget.containsKey(paramTypeElement)) { //the class is already known continue; } // Verify common generated code restrictions. if (!isValidInjectedType(paramTypeElement)) { continue; } ConstructorInjectionTarget constructorInjectionTarget = createConstructorInjectionTarget(paramElement); if (constructorInjectionTarget != null) { mapTypeElementToConstructorInjectionTarget.put(paramTypeElement, constructorInjectionTarget); } } } private boolean isValidInjectConstructor(Element element) { boolean valid = true; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify modifiers. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE)) { error(element, "@Inject constructors must not be private in class %s.", enclosingElement.getQualifiedName()); valid = false; } // Verify parentScope modifiers. Set<Modifier> parentModifiers = enclosingElement.getModifiers(); //TODO should not be a non static inner class neither if (!parentModifiers.contains(PUBLIC)) { error(element, "Class %s is private. @Inject constructors are not allowed in non public classes.", enclosingElement.getQualifiedName()); valid = false; } return valid; } private ConstructorInjectionTarget createConstructorInjectionTarget(ExecutableElement constructorElement) { TypeElement enclosingElement = (TypeElement) constructorElement.getEnclosingElement(); final boolean hasSingletonAnnotation = hasAnnotationWithName(enclosingElement, "Singleton"); final boolean hasProducesSingletonAnnotation = hasAnnotationWithName(enclosingElement, "ProvidesSingleton"); TypeElement superClassWithInjectedMembers = getMostDirectSuperClassWithInjectedMembers(enclosingElement, false); ConstructorInjectionTarget constructorInjectionTarget = new ConstructorInjectionTarget(enclosingElement, hasSingletonAnnotation, hasProducesSingletonAnnotation, superClassWithInjectedMembers); constructorInjectionTarget.parameters.addAll(getParamInjectionTargetList(constructorElement)); return constructorInjectionTarget; } private ConstructorInjectionTarget createConstructorInjectionTarget(VariableElement fieldElement) { final TypeElement fieldTypeElement = (TypeElement) typeUtils.asElement(fieldElement.asType()); final boolean hasSingletonAnnotation = hasAnnotationWithName(fieldTypeElement, "Singleton"); final boolean hasProducesSingletonAnnotation = hasAnnotationWithName(fieldTypeElement, "ProvidesSingleton"); TypeElement superClassWithInjectedMembers = getMostDirectSuperClassWithInjectedMembers(fieldTypeElement, false); List<ExecutableElement> constructorElements = ElementFilter.constructorsIn(fieldTypeElement.getEnclosedElements()); //we just need to deal with the case of the defaul constructor only. //multiple constructors are non-decidable states. //injected constructors will be handled at some point in the compilation cycle if (constructorElements.size() == 1) { ExecutableElement constructorElement = constructorElements.get(0); if (!constructorElement.getParameters().isEmpty()) { warning("The class %s has no default constructor, toothpick can't optimistically create a factory for it.", fieldTypeElement.getQualifiedName().toString()); return null; } if (constructorElement.getModifiers().contains(Modifier.PRIVATE)) { warning("The class %s has a private default constructor, toothpick can't optimistically create a factory for it.", fieldTypeElement.getQualifiedName().toString()); return null; } ConstructorInjectionTarget constructorInjectionTarget = new ConstructorInjectionTarget(fieldTypeElement, hasSingletonAnnotation, hasProducesSingletonAnnotation, superClassWithInjectedMembers); return constructorInjectionTarget; } return null; } private boolean isValidInjectedType(TypeElement fieldTypeElement) { if (isExcludedByFilters(fieldTypeElement)) return false; return !fieldTypeElement.getModifiers().contains(Modifier.ABSTRACT) //the previous line also covers && fieldTypeElement.getKind() != ElementKind.INTERFACE; && !fieldTypeElement.getModifiers().contains(Modifier.PRIVATE); } //used for testing only void setToothpickRegistryPackageName(String toothpickRegistryPackageName) { this.toothpickRegistryPackageName = toothpickRegistryPackageName; } //used for testing only void setToothpickRegistryChildrenPackageNameList(List<String> toothpickRegistryChildrenPackageNameList) { this.toothpickRegistryChildrenPackageNameList = toothpickRegistryChildrenPackageNameList; } }
package uk.ac.ox.ndm.grails.utils.validator; import com.google.common.base.Strings; /** * @since 14/08/2015 */ public class NhsNumberValidator implements Validator<String> { public Object isValid(String nhsNumberStr) { if (!Strings.isNullOrEmpty(nhsNumberStr)) { nhsNumberStr = nhsNumberStr.replaceAll(" ", ""); if (nhsNumberStr.length() != 10) { return "validation.nhsnumber.wronglength"; } try { int checkDigit = 0; int[] nhsNumber = new int[nhsNumberStr.length()]; for (int i = 0; i < nhsNumberStr.length(); i++) { nhsNumber[i] = Integer.parseInt(nhsNumberStr.charAt(i) + ""); } if (nhsNumber.length == 10) { for (int i = 0; i <= 8; i++) { checkDigit += nhsNumber[i] * (10 - i); } checkDigit = (11 - (checkDigit % 11)); if (checkDigit == 11) checkDigit = 0; if (checkDigit != 10) return checkDigit == nhsNumber[9] ? true : "validation.nhsnumber.invalid"; } } catch (NumberFormatException ignored) { return "validation.nhsnumber.not.numeric"; } } return "validation.empty"; } }
package org.xcolab.view.config.rewrite.rules; import org.ocpsoft.rewrite.config.ConfigurationBuilder; import org.ocpsoft.rewrite.config.Direction; import org.ocpsoft.rewrite.servlet.config.Forward; import org.ocpsoft.rewrite.servlet.config.Path; import org.ocpsoft.rewrite.servlet.config.rule.Join; public class ProposalRewriteRules implements RewriteRuleProvider { private static final String CONTEST_PATH = "/contests/{year}/{urlName}"; private static final String PROPOSAL_IN_PHASE_PATH = CONTEST_PATH + "/phase/{phaseId}/{proposalUrlString}/{proposalId}"; private static final String PROPOSAL_PATH = CONTEST_PATH + "/c/{proposalUrlString}/{proposalId}"; @Override public void configure(ConfigurationBuilder configurationBuilder) { configurationBuilder .addRule() .when(Direction.isInbound().and(Path.matches("/challenges{path}") .or(Path.matches("/events{path}")) .or(Path.matches("/trends{path}")) .or(Path.matches("/dialogues{path}")) .or(Path.matches("/contributions{path}")) )) .perform(Forward.to("/contests{path}")) .where("path").matches(".*"); configureEditUrls(configurationBuilder); configureTabUrls(configurationBuilder); configurationBuilder .addRule(Join.path(PROPOSAL_IN_PHASE_PATH) .to(PROPOSAL_PATH)) .addRule(Join.path(PROPOSAL_IN_PHASE_PATH + "/version/{version}") .to(PROPOSAL_PATH)) .addRule(Join.path(PROPOSAL_PATH + "/version/{version}") .to(PROPOSAL_PATH)) .addRule(Join.path(PROPOSAL_PATH + "/voted") .to(PROPOSAL_PATH + "?voted=true")) .addRule(Join.path(PROPOSAL_PATH + "/moveFromContestPhaseId/{moveFromContestPhaseId}/move/{moveType}") .to(PROPOSAL_PATH)); } private void configureEditUrls(ConfigurationBuilder configurationBuilder) { configurationBuilder .addRule(Join.path(PROPOSAL_PATH + "/edit") .to(PROPOSAL_PATH + "?edit=true")) .addRule(Join.path(PROPOSAL_IN_PHASE_PATH + "/edit") .to(PROPOSAL_PATH + "?edit=true")); } private void configureTabUrls(ConfigurationBuilder configurationBuilder) { configurationBuilder .addRule(Join.path(PROPOSAL_IN_PHASE_PATH + "/tab/{tab}") .to(PROPOSAL_PATH)) .addRule(Join.path(PROPOSAL_PATH + "/tab/{tab}") .to(PROPOSAL_PATH)) .addRule(Join.path(PROPOSAL_PATH + "/tab/{tab}/edit") .to(PROPOSAL_PATH + "?edit=true")) .addRule(Join.path(PROPOSAL_IN_PHASE_PATH + "/tab/{tab}/edit") .to(PROPOSAL_PATH + "?edit=true")); } }
package org.project.openbaton.common.vnfm_sdk.utils; import org.project.openbaton.catalogue.mano.common.AutoScalePolicy; import org.project.openbaton.catalogue.mano.common.ConnectionPoint; import org.project.openbaton.catalogue.mano.common.DeploymentFlavour; import org.project.openbaton.catalogue.mano.common.LifecycleEvent; import org.project.openbaton.catalogue.mano.descriptor.*; import org.project.openbaton.catalogue.mano.record.Status; import org.project.openbaton.catalogue.mano.record.VNFCInstance; import org.project.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord; import org.project.openbaton.catalogue.nfvo.*; import org.project.openbaton.common.vnfm_sdk.exception.BadFormatException; import org.project.openbaton.common.vnfm_sdk.exception.NotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.LinkedHashSet; public class VNFRUtils { private static Logger log = LoggerFactory.getLogger(VNFRUtils.class); public static VirtualNetworkFunctionRecord createVirtualNetworkFunctionRecord(VirtualNetworkFunctionDescriptor vnfd, String flavourKey, String nsr_id) throws NotFoundException, BadFormatException { VirtualNetworkFunctionRecord virtualNetworkFunctionRecord = new VirtualNetworkFunctionRecord(); virtualNetworkFunctionRecord.setLifecycle_event_history(new HashSet<LifecycleEvent>()); virtualNetworkFunctionRecord.setParent_ns_id(nsr_id); virtualNetworkFunctionRecord.setName(vnfd.getName()); virtualNetworkFunctionRecord.setType(vnfd.getType()); virtualNetworkFunctionRecord.setCyclicDependency(vnfd.hasCyclicDependency()); Configuration requires = new Configuration(); requires.setName("requires"); requires.setConfigurationParameters(new HashSet<ConfigurationParameter>()); virtualNetworkFunctionRecord.setRequires(requires); if (vnfd.getRequires() != null) { for (String key : vnfd.getRequires()) { ConfigurationParameter configurationParameter = new ConfigurationParameter(); log.debug("Adding " + key + " to requires"); configurationParameter.setConfKey(key); virtualNetworkFunctionRecord.getRequires().getConfigurationParameters().add(configurationParameter); } } Configuration provides = new Configuration(); provides.setConfigurationParameters(new HashSet<ConfigurationParameter>()); provides.setName("provides"); virtualNetworkFunctionRecord.setProvides(provides); if (vnfd.getProvides() != null) { for (String key : vnfd.getProvides()) { ConfigurationParameter configurationParameter = new ConfigurationParameter(); log.debug("Adding " + key + " to provides"); configurationParameter.setConfKey(key); virtualNetworkFunctionRecord.getProvides().getConfigurationParameters().add(configurationParameter); } } if (vnfd.getVnfPackage() != null) { VNFPackage vnfPackage = new VNFPackage(); vnfPackage.setImageLink(vnfd.getVnfPackage().getImageLink()); vnfPackage.setScriptsLink(vnfd.getVnfPackage().getScriptsLink()); vnfPackage.setName(vnfd.getVnfPackage().getName()); //TODO check for ordering vnfPackage.setScripts(new HashSet<Script>()); for (Script script : vnfd.getVnfPackage().getScripts()) { Script s = new Script(); s.setName(script.getName()); s.setPayload(script.getPayload()); vnfPackage.getScripts().add(s); } vnfPackage.setImage(vnfd.getVnfPackage().getImage()); vnfPackage.setExtId(vnfd.getVnfPackage().getExtId()); virtualNetworkFunctionRecord.setVnfPackage(vnfPackage); } if (vnfd.getEndpoint() != null) { virtualNetworkFunctionRecord.setEndpoint(vnfd.getEndpoint()); } else virtualNetworkFunctionRecord.setEndpoint(vnfd.getType()); virtualNetworkFunctionRecord.setMonitoring_parameter(new HashSet<String>()); virtualNetworkFunctionRecord.getMonitoring_parameter().addAll(vnfd.getMonitoring_parameter()); virtualNetworkFunctionRecord.setVendor(vnfd.getVendor()); virtualNetworkFunctionRecord.setAuto_scale_policy(new HashSet<AutoScalePolicy>()); for (AutoScalePolicy autoScalePolicy : vnfd.getAuto_scale_policy()) { AutoScalePolicy newAutoScalePolicy = new AutoScalePolicy(); newAutoScalePolicy.setAction(autoScalePolicy.getAction()); newAutoScalePolicy.setComparisonOperator(autoScalePolicy.getComparisonOperator()); newAutoScalePolicy.setCooldown(autoScalePolicy.getCooldown()); newAutoScalePolicy.setMetric(autoScalePolicy.getMetric()); newAutoScalePolicy.setPeriod(autoScalePolicy.getPeriod()); newAutoScalePolicy.setStatistic(autoScalePolicy.getStatistic()); newAutoScalePolicy.setThreshold(autoScalePolicy.getThreshold()); virtualNetworkFunctionRecord.getAuto_scale_policy().add(newAutoScalePolicy); } // TODO mange the VirtualLinks and links... // virtualNetworkFunctionRecord.setConnected_external_virtual_link(vnfd.getVirtual_link()); virtualNetworkFunctionRecord.setVdu(new HashSet<VirtualDeploymentUnit>()); for (VirtualDeploymentUnit virtualDeploymentUnit : vnfd.getVdu()) { VirtualDeploymentUnit vdu_new = new VirtualDeploymentUnit(); HashSet<VNFComponent> vnfComponents = new HashSet<>(); for (VNFComponent component : virtualDeploymentUnit.getVnfc()) { VNFComponent component_new = new VNFComponent(); HashSet<VNFDConnectionPoint> connectionPoints = new HashSet<>(); for (VNFDConnectionPoint connectionPoint : component.getConnection_point()) { VNFDConnectionPoint connectionPoint_new = new VNFDConnectionPoint(); connectionPoint_new.setVirtual_link_reference(connectionPoint.getVirtual_link_reference()); connectionPoint_new.setType(connectionPoint.getType()); connectionPoints.add(connectionPoint_new); } component_new.setConnection_point(connectionPoints); vnfComponents.add(component_new); } vdu_new.setVnfc(vnfComponents); vdu_new.setVnfc_instance(new HashSet<VNFCInstance>()); HashSet<LifecycleEvent> lifecycleEvents = new HashSet<>(); for (LifecycleEvent lifecycleEvent : virtualDeploymentUnit.getLifecycle_event()) { LifecycleEvent lifecycleEvent_new = new LifecycleEvent(); lifecycleEvent_new.setEvent(lifecycleEvent.getEvent()); lifecycleEvent_new.setLifecycle_events(lifecycleEvent.getLifecycle_events()); lifecycleEvents.add(lifecycleEvent_new); } vdu_new.setLifecycle_event(lifecycleEvents); vdu_new.setVimInstanceName(virtualDeploymentUnit.getVimInstanceName()); vdu_new.setHostname(virtualDeploymentUnit.getHostname()); vdu_new.setHigh_availability(virtualDeploymentUnit.getHigh_availability()); vdu_new.setComputation_requirement(virtualDeploymentUnit.getComputation_requirement()); vdu_new.setScale_in_out(virtualDeploymentUnit.getScale_in_out()); HashSet<String> monitoringParameters = new HashSet<>(); monitoringParameters.addAll(virtualDeploymentUnit.getMonitoring_parameter()); vdu_new.setMonitoring_parameter(monitoringParameters); vdu_new.setVdu_constraint(virtualDeploymentUnit.getVdu_constraint()); HashSet<String> vmImages = new HashSet<>(); vmImages.addAll(virtualDeploymentUnit.getVm_image()); vdu_new.setVm_image(vmImages); vdu_new.setVirtual_network_bandwidth_resource(virtualDeploymentUnit.getVirtual_network_bandwidth_resource()); vdu_new.setVirtual_memory_resource_element(virtualDeploymentUnit.getVirtual_memory_resource_element()); vdu_new.setVimInstance(virtualDeploymentUnit.getVimInstance()); virtualNetworkFunctionRecord.getVdu().add(vdu_new); } virtualNetworkFunctionRecord.setVersion(vnfd.getVersion()); virtualNetworkFunctionRecord.setConnection_point(new HashSet<ConnectionPoint>()); virtualNetworkFunctionRecord.getConnection_point().addAll(vnfd.getConnection_point()); // TODO find a way to choose between deployment flavors and create the new one virtualNetworkFunctionRecord.setDeployment_flavour_key(flavourKey); for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu()) { if (!existsDeploymentFlavor(virtualNetworkFunctionRecord.getDeployment_flavour_key(), virtualDeploymentUnit.getVimInstance())) { throw new BadFormatException("no key " + virtualNetworkFunctionRecord.getDeployment_flavour_key() + " found in vim instance: " + virtualDeploymentUnit.getVimInstance()); } } virtualNetworkFunctionRecord.setDescriptor_reference(vnfd.getId()); virtualNetworkFunctionRecord.setLifecycle_event(new LinkedHashSet<LifecycleEvent>()); HashSet<LifecycleEvent> lifecycleEvents = new HashSet<>(); for (LifecycleEvent lifecycleEvent : vnfd.getLifecycle_event()) { LifecycleEvent lifecycleEvent_new = new LifecycleEvent(); lifecycleEvent_new.setEvent(lifecycleEvent.getEvent()); lifecycleEvent_new.setLifecycle_events(new LinkedHashSet<String>()); for (String event : lifecycleEvent.getLifecycle_events()) { lifecycleEvent_new.getLifecycle_events().add(event); } lifecycleEvents.add(lifecycleEvent_new); } virtualNetworkFunctionRecord.setLifecycle_event(lifecycleEvents); virtualNetworkFunctionRecord.setVirtual_link(new HashSet<InternalVirtualLink>()); HashSet<InternalVirtualLink> internalVirtualLinks = new HashSet<>(); for (InternalVirtualLink internalVirtualLink : vnfd.getVirtual_link()) { InternalVirtualLink internalVirtualLink_new = new InternalVirtualLink(); internalVirtualLink_new.setName(internalVirtualLink.getName()); internalVirtualLink_new.setLeaf_requirement(internalVirtualLink.getLeaf_requirement()); internalVirtualLink_new.setRoot_requirement(internalVirtualLink.getRoot_requirement()); internalVirtualLink_new.setConnection_points_references(new HashSet<String>()); for (String conn : internalVirtualLink.getConnection_points_references()) { internalVirtualLink_new.getConnection_points_references().add(conn); } internalVirtualLink_new.setQos(new HashSet<String>()); for (String qos : internalVirtualLink.getQos()) { internalVirtualLink_new.getQos().add(qos); } internalVirtualLink_new.setTest_access(new HashSet<String>()); for (String test : internalVirtualLink.getTest_access()) { internalVirtualLink_new.getTest_access().add(test); } internalVirtualLink_new.setConnectivity_type(internalVirtualLink.getConnectivity_type()); internalVirtualLinks.add(internalVirtualLink_new); } virtualNetworkFunctionRecord.getVirtual_link().addAll(internalVirtualLinks); virtualNetworkFunctionRecord.setVnf_address(new HashSet<String>()); virtualNetworkFunctionRecord.setStatus(Status.NULL); return virtualNetworkFunctionRecord; } private static boolean existsDeploymentFlavor(String key, VimInstance vimInstance) { log.debug("" + vimInstance); for (DeploymentFlavour deploymentFlavour : vimInstance.getFlavours()) { if (deploymentFlavour.getFlavour_key().equals(key) || deploymentFlavour.getExtId().equals(key) || deploymentFlavour.getId().equals(key)) { return true; } } return false; } }
package org.commcare.suite.model; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.condition.IFunctionHandler; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.utils.DateUtils; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapMap; import org.javarosa.core.util.externalizable.Externalizable; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.xpath.XPathParseTool; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.parser.XPathSyntaxException; /** * <p>Text objects are a model for holding strings which * will be displayed to users. Text's can be defined * in a number of ways, static Strings, localized values, * even xpath expressions. They are dynamically evaluated * at runtime in order to allow for CommCare apps to flexibly * provide rich information from a number of sources.</p> * * <p>There are 4 types of Text sources which can be defined * <ul> * <li>Raw Text</li> * <li>Localized String</li> * <li>XPath Expression</li> * <li>Compound Text</li> * </ul> * </p> * * @author ctsims * */ public class Text implements Externalizable { private int type; private String argument; //Will this maintain order? I don't think so.... private Hashtable<String, Text> arguments; public static final int TEXT_TYPE_FLAT = 1; public static final int TEXT_TYPE_LOCALE = 2; public static final int TEXT_TYPE_XPATH = 4; public static final int TEXT_TYPE_COMPOSITE = 8; /** * For Serialization only; */ public Text() { } /** * @return An empty text object */ private static Text TextFactory() { Text t = new Text(); t.type = -1; t.argument = ""; t.arguments = new Hashtable<String, Text>(); return t; } /** * @param id The locale key. * @return A Text object that evaluates to the * localized value of the ID provided. */ public static Text LocaleText(String id) { Text t = TextFactory(); t.argument = id; t.type = TEXT_TYPE_LOCALE; return t; } /** * @param localeText A Text object which evaluates * to a locale key. * @return A Text object that evaluates to the * localized value of the id returned by evaluating * localeText */ public static Text LocaleText(Text localeText) { Text t = TextFactory(); t.arguments = new Hashtable<String, Text>(); t.arguments.put("id",localeText); t.argument = ""; t.type = TEXT_TYPE_LOCALE; return t; } /** * @param text A text string. * @return A Text object that evaluates to the * string provided. */ public static Text PlainText(String text) { Text t = TextFactory(); t.argument = text; t.type = TEXT_TYPE_FLAT; return t; } /** * * @param function A valid XPath function. * @param arguments A key/value set defining arguments * which, when evaluated, will provide a value for variables * in the provided function. * @return A Text object that evaluates to the * resulting value of the xpath expression defined * by function when presented with a compatible data * model. * @throws XPathSyntaxException If the provided xpath function does * not have valid syntax. */ public static Text XPathText(String function, Hashtable<String, Text> arguments) throws XPathSyntaxException { Text t = TextFactory(); t.argument = function; //Test parse real fast to make sure it's valid text. XPathExpression expression = XPathParseTool.parseXPath("string(" + t.argument + ")"); t.arguments = arguments; t.type = TEXT_TYPE_XPATH; return t; } /** * @param text A vector of Text objects. * @return A Text object that evaluates to the * value of each member of the text vector. */ public static Text CompositeText(Vector<Text> text) { Text t = TextFactory(); int i = 0; for(Text txt : text) { //TODO: Probably a more efficient way to do this... t.arguments.put(Integer.toHexString(i), txt); } t.type = TEXT_TYPE_COMPOSITE; return t; } /** * @return The evaluated string value for this Text object. Note * that if this string is expecting a model in order to evaluate * (like an XPath text), this will likely fail. */ public String evaluate() { return evaluate(null, null); } /** * @param context A data model which is compatible with any * xpath functions in the underlying Text * @return The evaluated string value for this Text object. */ public String evaluate(FormInstance context, EvaluationContext parent) { switch(type) { case TEXT_TYPE_FLAT: return argument; case TEXT_TYPE_LOCALE: String id = argument; if(argument.equals("")) { id = arguments.get("id").evaluate(context,parent); } return Localization.get(id); case TEXT_TYPE_XPATH: try { //Do an XPath cast to a string as part of the operation. XPathExpression expression = XPathParseTool.parseXPath("string(" + argument + ")"); EvaluationContext p = parent == null ? new EvaluationContext() : parent; EvaluationContext temp = new EvaluationContext(p, context == null ? null : context.getRoot().getRef()); temp.addFunctionHandler(new IFunctionHandler() { public Object eval(Object[] args) { String type = (String)args[1]; int format = DateUtils.FORMAT_HUMAN_READABLE_SHORT; if(type.equals("short")) { format = DateUtils.FORMAT_HUMAN_READABLE_SHORT; } else if(type.equals("long")){ format = DateUtils.FORMAT_ISO8601; } return DateUtils.formatDate((Date)args[0], format); } public String getName() { return "format_date"; } public Vector getPrototypes() { Vector format = new Vector(); Class[] prototypes = new Class[] { Date.class, String.class }; format.addElement(prototypes); return format; } public boolean rawArgs() { return false; } public boolean realTime() { return false; } }); temp.addFunctionHandler(new IFunctionHandler() { public Object eval(Object[] args) { Calendar c = Calendar.getInstance(); c.setTime(new Date()); return String.valueOf(c.get(Calendar.DAY_OF_WEEK)); } public String getName() { return "dow"; } public Vector getPrototypes() { Vector format = new Vector(); Class[] prototypes = new Class[] {}; format.addElement(prototypes); return format; } public boolean rawArgs() { return false; } public boolean realTime() { return false; } }); for(Enumeration en = arguments.keys(); en.hasMoreElements() ;) { String key = (String)en.nextElement(); String value = arguments.get(key).evaluate(context, parent); temp.setVariable(key,value); } return (String)expression.eval(context,temp); } catch (XPathSyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } //For testing; return argument; case TEXT_TYPE_COMPOSITE: String ret = ""; for(Enumeration en = arguments.elements() ; en.hasMoreElements() ;) { ret += ((Text)en.nextElement()).evaluate() +""; } return ret; default: return argument; } } /* * (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory) */ public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { type = ExtUtil.readInt(in); argument = ExtUtil.readString(in); arguments = (Hashtable<String, Text>)ExtUtil.read(in, new ExtWrapMap(String.class, Text.class), pf); } /* * (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#writeExternal(java.io.DataOutputStream) */ public void writeExternal(DataOutputStream out) throws IOException { ExtUtil.writeNumeric(out,type); ExtUtil.writeString(out,argument); ExtUtil.write(out, new ExtWrapMap(arguments)); } }
package tech.pinto; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.TreeSet; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; public class Indexer implements Consumer<Table>, Cloneable { private final List<Index> indexes = new ArrayList<>(); private final Pinto pinto; private final String indexString; private final boolean incrementBase; public Indexer(Pinto pinto, String indexString) { this(pinto, indexString, false); } public Indexer(Pinto pinto, String indexString, boolean incrementBase) { indexString = indexString.replaceAll("\\[|\\]", ""); this.pinto = pinto; this.indexString = indexString; this.incrementBase = incrementBase; String[] indexParts = indexString.split(","); for (int n = 0; n < indexParts.length; n++) { Index i = new Index(indexParts[n].trim()); indexes.add(i); } } @Override public void accept(Table t) { LinkedList<Column<?,?>> unused = new LinkedList<>(); LinkedList<LinkedList<Column<?,?>>> indexed = new LinkedList<>(); for (LinkedList<Column<?,?>> stack : t.popStacks()) { List<StackOperation> ops = new ArrayList<>(); indexed.addLast(operate(stack, ops, pinto)); Index last = indexes.get(indexes.size() - 1); while (last.isRepeat() && stack.size() > 0) { try { indexed.addLast(operate(stack, last.index(stack), pinto)); } catch (IllegalArgumentException pse) { break; } } unused.addAll(stack); } t.pushToBase(unused); t.pushStacks(indexed); if (incrementBase) { t.incrementBase(); } } @SuppressWarnings("unchecked") private LinkedList<Column<?,?>> operate(LinkedList<Column<?,?>> stack, List<StackOperation> ops, Pinto pinto) { indexes.stream().map(i -> i.index(stack)).forEach(ops::addAll); List<StackOperation> headerOps = ops.stream().filter(StackOperation::isHeader).collect(Collectors.toList()); List<StackOperation> ordinalOps = ops.stream().filter(so -> ! so.isHeader()).collect(Collectors.toList()); // determine which operations need to be copies LinkedList<StackOperation>[] opsByOrdinal = new LinkedList[stack.size()]; for(List<StackOperation> l : Arrays.asList(headerOps, ordinalOps)) { for (StackOperation op : l) { if (!op.isAlternative()) { if (opsByOrdinal[op.getOrdinal()] != null) { if(opsByOrdinal[op.getOrdinal()].getLast().isHeader() && !opsByOrdinal[op.getOrdinal()].getLast().isHeader()) { op.setSkip(true); // don't include cols index by header in subsequent ordinal indexes } else { opsByOrdinal[op.getOrdinal()].getLast().setNeedsCloning(true); } } else { opsByOrdinal[op.getOrdinal()] = new LinkedList<>(); } if(!op.skip()) { opsByOrdinal[op.getOrdinal()].add(op); } } } } TreeSet<Integer> alreadyUsed = new TreeSet<>(); LinkedList<Column<?,?>> indexed = new LinkedList<>(); for (StackOperation o : ops) { if (o.isAlternative()) { indexed.addAll(pinto.parseSubExpression(o.getAlternativeString())); } else if ((!alreadyUsed.contains(o.getOrdinal())) && !o.skip()) { Column<?,?> c = stack.get(o.getOrdinal()); indexed.add(o.checkType(o.needsCloning() || o.isCopy() ? c.clone() : c)); if (!o.isCopy()) { alreadyUsed.add(o.getOrdinal()); } } } for (int i = opsByOrdinal.length - 1; i >= 0; i if (opsByOrdinal[i] != null) { opsByOrdinal[i].stream().filter(((Predicate<StackOperation>) StackOperation::isCopy).negate()).findAny() .ifPresent(op -> stack.remove(op.getOrdinal())); } } return indexed; } private static boolean isNumeric(String s) { return s.matches("[-+]?\\d*\\.?\\d+"); } public String toString() { return "[" + indexString + "]"; } public Indexer clone() { try { Indexer clone = (Indexer) super.clone(); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } private class Index { private Optional<String> header = Optional.empty(); private Optional<Integer> ordinal = Optional.empty(); private Optional<Integer> sliceStart = Optional.empty(); private Optional<Integer> sliceEnd = Optional.empty(); private Optional<String> or = Optional.empty(); private boolean copy = false; private boolean repeat = false; private boolean optional = false; private boolean everything = false; private boolean checkString = false; private boolean checkConstant = false; public Index(String s) { if (s.contains("=")) { String[] thisOrThat = s.split("="); if (thisOrThat.length != 2) { throw new IllegalArgumentException("Index \"=\" should be followed by alternative expression."); } or = Optional.of(thisOrThat[1] + " {" + thisOrThat[0] + "}"); s = thisOrThat[0]; } if (s.contains("+")) { repeat = true; s = s.replace("+", ""); } if (s.contains("&")) { if (repeat) { throw new PintoSyntaxException( "Cannot copy and repeat an index because it will create an infinite loop."); } copy = true; s = s.replace("&", ""); } if (s.contains("?")) { optional = true; s = s.replace("?", ""); } if (s.contains("@")) { checkString = true; s = s.replace("@", ""); } if (s.contains(" if (checkString) { throw new PintoSyntaxException("Cannot enforce both # and @ types."); } checkConstant = true; s = s.replace(" } if (s.equals("x")) { // none index } else if (s.equals(":") || s.equals("")) { everything = true; } else if (s.contains(":")) { if (s.indexOf(":") == 0) { sliceStart = Optional.of(0); sliceEnd = Optional.of(Integer.parseInt(s.substring(1))); } else if (s.indexOf(":") == s.length() - 1) { sliceEnd = Optional.of(Integer.MAX_VALUE); sliceStart = Optional.of(Integer.parseInt(s.substring(0, s.length() - 1))); } else { String[] parts = s.split(":"); sliceStart = Optional.of(Integer.parseInt(parts[0])); sliceEnd = Optional.of(Integer.parseInt(parts[1])); } } else { if (isNumeric(s)) { ordinal = Optional.of(Integer.parseInt(s)); } else { header = Optional.of(s); } } } public List<StackOperation> index(LinkedList<Column<?,?>> stack) { List<StackOperation> ops = new ArrayList<>(); // if (stack.size() == 0 && ! or.isPresent()) { // return ops; if (everything || sliceStart.isPresent() || ordinal.isPresent()) { int start = 0, end = 0; if (everything) { if(stack.isEmpty()) { return ops; } start = 0; end = stack.size(); } else if (sliceStart.isPresent()) { start = sliceStart.get(); start = start < 0 ? start + stack.size() : start; end = sliceEnd.get(); end = end < 0 ? end + stack.size() : end; } else if (ordinal.isPresent()) { start = ordinal.get(); start = start < 0 ? start + stack.size() : start; end = start + 1; } if (start >= end) { throw new IllegalArgumentException("Invalid index. Start is after end."); } if (start < 0 || start >= stack.size()) { if (!optional) { throw new IllegalArgumentException( "Index [" + start + ":" + end + "] is outside bounds of stack."); } } else { for (int n = start; n < end && n < stack.size(); n++) { ops.add(new StackOperation(n, isCopy(), false, checkString, checkConstant)); } } } else if (header.isPresent()) { final String query = header.get(); Predicate<String> test; if (query.startsWith("*")) { final String toFind = query.substring(1); test = s -> s.endsWith(toFind); } else if (query.endsWith("*")) { final String toFind = query.substring(0, query.length() - 1); test = s -> s.startsWith(toFind); } else if (query.contains("*")) { final String[] toFind = query.split("\\*"); test = s -> s.startsWith(toFind[0]) && s.endsWith(toFind[1]); } else { test = s -> s.equals(query); } boolean found = false; for (int n = 0; n < stack.size(); n++) { if (test.test(stack.get(n).getHeader())) { ops.add(new StackOperation(n, isCopy(), true, checkString, checkConstant)); found = true; } } if (!found && !optional) { if (or.isPresent()) { ops.add(new StackOperation(or.get(), checkString, checkConstant)); } else { throw new IllegalArgumentException("Missing required header \"" + query + "\""); } } } return ops; } public boolean isCopy() { return copy; } public boolean isRepeat() { return repeat; } } private static class StackOperation implements Comparable<StackOperation> { private final int ordinal; private final boolean isHeader; private final boolean checkString; private final boolean checkConstant; private final boolean copy; private boolean skip = false; private boolean needsCloning = false; private Optional<String> alternative = Optional.empty(); public StackOperation(int ordinal, boolean copy, boolean isHeader, boolean checkString, boolean checkConstant) { this.ordinal = ordinal; this.copy = copy; this.checkConstant = checkConstant; this.checkString = checkString; this.isHeader = isHeader; } public StackOperation(String alternative, boolean checkString, boolean checkConstant) { this.alternative = Optional.of(alternative); ordinal = -1; copy = false; this.checkConstant = checkConstant; this.checkString = checkString; this.isHeader = false; } public boolean isAlternative() { return alternative.isPresent(); } public String getAlternativeString() { return alternative.get(); } public int getOrdinal() { return ordinal; } public boolean isCopy() { return copy; } public void setNeedsCloning(boolean needsCloning) { this.needsCloning = needsCloning; } public boolean needsCloning() { return needsCloning; } public void setSkip(boolean skip) { this.skip = skip; } public boolean skip() { return skip; } public boolean isHeader() { return isHeader; } public Column<?,?> checkType(Column<?,?> c) throws PintoSyntaxException { if(checkString && ! (c instanceof Column.OfConstantStrings)) { throw new PintoSyntaxException("String column required."); } else if(checkConstant && ! (c instanceof Column.OfConstantDoubles)) { throw new PintoSyntaxException("Constant column required."); } return c; } // public LinkedList<Column> checkType(LinkedList<Column> l) throws Exception { // for (Column c : l) { // return l; @Override public int compareTo(StackOperation o) { return Integer.valueOf(ordinal).compareTo(Integer.valueOf(o.getOrdinal())); } } }
package org.knowm.xchange.hitbtc.v2; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import org.knowm.xchange.hitbtc.v2.dto.HitbtcException; import org.knowm.xchange.hitbtc.dto.trade.HitbtcExecutionReportResponse; import org.knowm.xchange.hitbtc.v2.dto.HitbtcAddress; import org.knowm.xchange.hitbtc.v2.dto.HitbtcOrder; import org.knowm.xchange.hitbtc.v2.dto.HitbtcOwnTrade; import org.knowm.xchange.hitbtc.v2.dto.HitbtcBalance; import org.knowm.xchange.hitbtc.v2.dto.HitbtcInternalTransferResponse; import org.knowm.xchange.hitbtc.v2.dto.HitbtcTransaction; import si.mazi.rescu.HttpStatusIOException; @Path("/api/2/") public interface HitbtcAuthenticated extends Hitbtc { @GET @Path("account/balance") List<HitbtcBalance> getPaymentBalance() throws IOException, HitbtcException; @GET @Path("account/crypto/address/{currency}") HitbtcAddress getHitbtcDepositAddress(@PathParam("currency") String currency) throws IOException, HitbtcException; @GET @Path("account/transactions") List<HitbtcTransaction> transactions() throws HttpStatusIOException; @GET @Path("account/balance") List<HitbtcBalance> getNewBalance() throws IOException, HitbtcException; @POST @Path("account/transfer") HitbtcInternalTransferResponse transferToTrading(@FormParam("amount") BigDecimal amount, @FormParam("currency") String currency, @FormParam("type") String type) throws IOException; @POST @Path("account/crypto/withdraw") Map payout(@FormParam("amount") BigDecimal amount, @FormParam("currency") String currency, @FormParam("address") String address) throws HttpStatusIOException; //TODO add query params @GET @Path("order") List<HitbtcOrder> getHitbtcActiveOrders() throws IOException, HitbtcException; //TODO remove usage of HitbtcExecutionReportResponse @POST @Path("order") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) HitbtcExecutionReportResponse postHitbtcNewOrder( @FormParam("clientOrderId") String clientOrderId, @FormParam("symbol") String symbol, @FormParam("side") String side, @FormParam("price") BigDecimal price, @FormParam("quantity") BigDecimal quantity, @FormParam("type") String type, @FormParam("timeInForce") String timeInForce) throws IOException, HitbtcException; @DELETE @Path("order") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) List<HitbtcOrder> cancelAllOrders(@FormParam("symbol") String symbol) throws IOException, HitbtcException; @DELETE @Path("order/{clientOrderId}") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) HitbtcExecutionReportResponse cancelSingleOrder(@PathParam("clientOrderId") String clientOrderId) throws IOException, HitbtcException; //TODO Add replace or update order via PATCH with upgrade to JSR311 // PATCH /order/{clientOrderId} @GET @Path("trading/balance") List<HitbtcBalance> getTradingBalance() throws IOException, HitbtcException; //TODO add query params /** * Get historical trades. There can be one to many trades per order. * * @return * @throws IOException * @throws HitbtcException */ @GET @Path("history/trades") List<HitbtcOwnTrade> getHitbtcTrades() throws IOException, HitbtcException; //TODO add query params /** * Get historical orders * * @return * @throws IOException * @throws HitbtcException */ @GET @Path("history/order") List<HitbtcOrder> getHitbtcRecentOrders() throws IOException, HitbtcException; @GET @Path("/history/order/{id}/trades") List<HitbtcOwnTrade> getHistorialTradesByOrder(@PathParam("id") String orderId) throws IOException, HitbtcException; }
package org.knowm.xchart.internal.chartpart; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.text.Format; import java.util.*; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.knowm.xchart.internal.Utils; import org.knowm.xchart.internal.chartpart.Axis.Direction; import org.knowm.xchart.style.AxesChartStyler; import org.knowm.xchart.style.CategoryStyler; import org.knowm.xchart.style.Styler; /** @author timmolter */ public abstract class AxisTickCalculator_ { /** the List of tick label position in pixels */ final List<Double> tickLocations = new LinkedList<Double>(); /** the List of tick label values */ final List<String> tickLabels = new LinkedList<String>(); final Direction axisDirection; final double workingSpace; final double minValue; final double maxValue; List<Double> axisValues; final AxesChartStyler styler; Format axisFormat; /** * Constructor * * @param axisDirection * @param workingSpace * @param minValue * @param maxValue * @param styler */ AxisTickCalculator_( Direction axisDirection, double workingSpace, double minValue, double maxValue, AxesChartStyler styler) { this.axisDirection = axisDirection; this.workingSpace = workingSpace; this.minValue = getAxisMinValue(styler, axisDirection, minValue); this.maxValue = getAxisMaxValue(styler, axisDirection, maxValue); this.styler = styler; } AxisTickCalculator_( Direction axisDirection, double workingSpace, double minValue, double maxValue, List<Double> axisValues, AxesChartStyler styler) { this.axisDirection = axisDirection; this.workingSpace = workingSpace; this.axisValues = axisValues; this.minValue = getAxisMinValue( styler, axisDirection, this.axisValues.stream() .filter(Objects::nonNull) .filter(x -> x <= minValue) .mapToDouble(x -> x) .min() .orElse(minValue)); this.maxValue = getAxisMaxValue( styler, axisDirection, this.axisValues.stream() .filter(Objects::nonNull) .filter(x -> x >= maxValue) .mapToDouble(x -> x) .max() .orElse(maxValue)); this.styler = styler; } /** * Gets the first position * * @param gridStep * @return */ double getFirstPosition(double gridStep) { return minValue - (minValue % gridStep) - gridStep; } public List<Double> getTickLocations() { return tickLocations; } public List<String> getTickLabels() { return tickLabels; } /** * Given the generated tickLabels, will they fit side-by-side without overlapping each other and * looking bad? Sometimes the given tickSpacingHint is simply too small. * * @param tickLabels * @param tickSpacingHint * @return */ boolean willLabelsFitInTickSpaceHint(List<String> tickLabels, int tickSpacingHint) { String sampleLabel = "Y"; if (Direction.X.equals(this.axisDirection)) { // find the longest String in all the labels for (String tickLabel : tickLabels) { if (tickLabel != null && tickLabel.length() > sampleLabel.length()) { sampleLabel = tickLabel; } } } // System.out.println("longestLabel: " + sampleLabel); TextLayout textLayout = new TextLayout( sampleLabel, styler.getAxisTickLabelsFont(), new FontRenderContext(null, true, false)); AffineTransform rot = styler.getXAxisLabelRotation() == 0 ? null : AffineTransform.getRotateInstance( -1 * Math.toRadians(styler.getXAxisLabelRotation())); Shape shape = textLayout.getOutline(rot); Rectangle2D rectangle = shape.getBounds(); double largestLabelWidth = Direction.X.equals(this.axisDirection) ? rectangle.getWidth() : rectangle.getHeight(); // System.out.println("largestLabelWidth: " + largestLabelWidth); // System.out.println("tickSpacingHint: " + tickSpacingHint); // if (largestLabelWidth * 1.1 >= tickSpacingHint) { // System.out.println("WILL NOT FIT!!!"); return (largestLabelWidth * 1.1 < tickSpacingHint); } public Format getAxisFormat() { return axisFormat; } protected void calculate() { // a check if all axis data are the exact same values if (minValue == maxValue) { tickLabels.add(getAxisFormat().format(BigDecimal.valueOf(maxValue).doubleValue())); tickLocations.add(workingSpace / 2.0); return; } // a check for no data if (minValue > maxValue && minValue == Double.MAX_VALUE) { tickLabels.add(getAxisFormat().format(0.0)); tickLocations.add(workingSpace / 2.0); return; } // tick space - a percentage of the working space available for ticks double tickSpace = styler.getPlotContentSize() * workingSpace; // in plot space // this prevents an infinite loop when the plot gets sized really small. if (axisDirection == Direction.X && tickSpace < styler.getXAxisTickMarkSpacingHint()) { return; } if (axisDirection == Direction.Y && tickSpace < styler.getYAxisTickMarkSpacingHint()) { return; } // where the tick should begin in the working space in pixels double margin = Utils.getTickStartOffset( workingSpace, tickSpace); // in plot space double gridStep = getGridStepForDecimal(tickSpace); // the span of the data double span = Math.abs(Math.min((maxValue - minValue), Double.MAX_VALUE - 1)); // in data space if (axisValues != null && areValuesEquallySpaced(axisValues)) { calculateForEquallySpacedAxisValues(tickSpace, margin); return; } int tickSpacingHint = (axisDirection == Direction.X ? styler.getXAxisTickMarkSpacingHint() : styler.getYAxisTickMarkSpacingHint()) - 5; // for very short plots, squeeze some more ticks in than normal into the Y-Axis if (axisDirection == Direction.Y && tickSpace < 160) { tickSpacingHint = 25 - 5; } int gridStepInChartSpace; do { // System.out.println("calculating ticks..."); tickLabels.clear(); tickLocations.clear(); tickSpacingHint += 5; // System.out.println("tickSpacingHint: " + tickSpacingHint); // gridStepHint --> significand * 10 ** exponent // e.g. 724.1 --> 7.241 * 10 ** 2 double significand = span / tickSpace * tickSpacingHint; int exponent = 0; if (significand == 0) { exponent = 1; } else if (significand < 1) { while (significand < 1) { significand *= 10.0; exponent } } else { while (significand >= 10 || significand == Double.NEGATIVE_INFINITY) { significand /= 10.0; exponent++; } } // calculate the grid step width hint. double gridStep; if (significand > 7.5) { // gridStep = 10.0 * 10 ** exponent gridStep = 10.0 * Utils.pow(10, exponent); } else if (significand > 3.5) { // gridStep = 5.0 * 10 ** exponent gridStep = 5.0 * Utils.pow(10, exponent); } else if (significand > 1.5) { // gridStep = 2.0 * 10 ** exponent gridStep = 2.0 * Utils.pow(10, exponent); } else { // gridStep = 1.0 * 10 ** exponent gridStep = Utils.pow(10, exponent); } // System.out.println("gridStep: " + gridStep); gridStepInChartSpace = (int) (gridStep / span * tickSpace); // System.out.println("gridStepInChartSpace: " + gridStepInChartSpace); BigDecimal gridStepBigDecimal = new BigDecimal(gridStep, MathContext.DECIMAL64); // BigDecimal gridStepBigDecimal = BigDecimal.valueOf(gridStep); int scale = Math.min(10, gridStepBigDecimal.scale()); // int scale = gridStepBigDecimal.scale(); // System.out.println("scale: " + scale); // int scale = gridStepBigDecimal.scale(); BigDecimal cleanedGridStep0 = gridStepBigDecimal .setScale(scale, RoundingMode.HALF_UP) .stripTrailingZeros(); // chop off any double imprecision BigDecimal cleanedGridStep = cleanedGridStep0 .setScale(scale, RoundingMode.HALF_DOWN) .stripTrailingZeros(); // chop off any double imprecision // System.out.println("cleanedGridStep: " + cleanedGridStep); BigDecimal firstPosition = null; double firstPositionAsDouble = getFirstPosition(cleanedGridStep.doubleValue()); if (Double.isNaN(firstPositionAsDouble)) { // This happens when the data values are almost the same but differ by a very tiny amount. // The solution for now is to create a single axis label and tick at the average value double averageValue = (maxValue + minValue) / 2.0; String formattedTickLabel = Double.isNaN(averageValue) ? "NaN" : getAxisFormat().format(BigDecimal.valueOf(averageValue)); tickLabels.add(formattedTickLabel); return; } else if (firstPositionAsDouble == Double.NEGATIVE_INFINITY) { firstPosition = BigDecimal.valueOf(-1 * Double.MAX_VALUE); } else { try { firstPosition = BigDecimal.valueOf(firstPositionAsDouble); } catch (java.lang.NumberFormatException e) { System.out.println( "Some debug stuff. This happens once in a blue moon, and I don't know why."); System.out.println("scale: " + scale); System.out.println("exponent: " + exponent); System.out.println("gridStep: " + gridStep); System.out.println("cleanedGridStep: " + cleanedGridStep); System.out.println("cleanedGridStep.doubleValue(): " + cleanedGridStep.doubleValue()); System.out.println( "NumberFormatException caused by this number: " + getFirstPosition(cleanedGridStep.doubleValue())); } } // System.out.println("firstPosition: " + firstPosition); // chop off any double imprecision BigDecimal cleanedFirstPosition = firstPosition .setScale(10, RoundingMode.HALF_UP) .stripTrailingZeros(); // chop off any double imprecision // System.out.println("cleanedFirstPosition: " + cleanedFirstPosition); // generate all tickLabels and tickLocations from the first to last position for (BigDecimal value = cleanedFirstPosition; value.compareTo( BigDecimal.valueOf( (maxValue + 2 * cleanedGridStep.doubleValue()) == Double.POSITIVE_INFINITY ? Double.MAX_VALUE : maxValue + 2 * cleanedGridStep.doubleValue())) < 0; value = value.add(cleanedGridStep)) { // if (value.compareTo(BigDecimal.valueOf(maxValue)) <= 0 && // value.compareTo(BigDecimal.valueOf(minValue)) >= 0) { // System.out.println(value); String tickLabel = getAxisFormat().format(value.doubleValue()); // System.out.println(tickLabel); tickLabels.add(tickLabel); // here we convert tickPosition finally to plot space, i.e. pixels double tickLabelPosition = margin + ((value.doubleValue() - minValue) / (maxValue - minValue) * tickSpace); tickLocations.add(tickLabelPosition); } } while (!areAllTickLabelsUnique(tickLabels) || !willLabelsFitInTickSpaceHint(tickLabels, gridStepInChartSpace)); } private boolean areValuesEquallySpaced(List<Double> values) { if (values.size() < 2) { return false; } double space = values.get(1) - values.get(0); double threshold = .0001; if (threshold > Math.abs(maxValue - minValue)) { return false; } return IntStream.range(1, values.size()) .mapToDouble(i -> values.get(i) - values.get(i - 1)) .allMatch(x -> Math.abs(x - space) < threshold); } /** * Calculates the ticks so that they only appear at positions where data is available. * * @param tickSpace a percentage of the working space available for ticks * @param margin where the tick should begin in the working space in pixels */ private void calculateForEquallySpacedAxisValues(double tickSpace, double margin) { if (axisValues == null) { throw new IllegalStateException("No axis values."); } int gridStepInChartSpace; int tickValuesHint = 0; List<Double> tickLabelValues; double tickLabelMaxValue; double tickLabelMinValue; do { tickValuesHint++; tickLabels.clear(); int finalTickValuesHint = tickValuesHint; tickLabelValues = IntStream.range(0, axisValues.size()) .filter(it -> it % finalTickValuesHint == 0) .mapToDouble(axisValues::get) .boxed() .collect(Collectors.toList()); tickLabelMaxValue = tickLabelValues.stream().mapToDouble(x -> x).max().orElse(maxValue); tickLabelMinValue = tickLabelValues.stream().mapToDouble(x -> x).min().orElse(minValue); tickLabels.addAll( tickLabelValues.stream() .map(x -> getAxisFormat().format(x)) .collect(Collectors.toList())); // the span of the data double span = Math.abs( Math.min( (tickLabelMaxValue - tickLabelMinValue), Double.MAX_VALUE - 1)); // in data space double gridStep = span / (tickLabelValues.size() - 1); gridStepInChartSpace = (int) (gridStep / span * tickSpace); } while (!areAllTickLabelsUnique(tickLabels) || !willLabelsFitInTickSpaceHint(tickLabels, gridStepInChartSpace)); tickLocations.clear(); tickLocations.addAll( tickLabelValues.stream() .map(value -> margin + ((value - minValue) / (maxValue - minValue) * tickSpace)) .collect(Collectors.toList())); } private static boolean areAllTickLabelsUnique(List<?> tickLabels) { return new LinkedHashSet<>(tickLabels).size() == tickLabels.size(); } /** * Determines the axis min value, which may differ from the min value of the respective data (e.g. * for bar charts). * * @param styler the chart {@link Styler} * @param axisDirection the axis {@link Direction} * @param dataMinValue the minimum value of the data corresponding with the axis. * @return the axis min value */ private static double getAxisMinValue( Styler styler, Direction axisDirection, double dataMinValue) { if (Direction.Y.equals(axisDirection) && styler instanceof CategoryStyler && dataMinValue > 0) return 0; return dataMinValue; } /** * Determines the axis max value, which may differ from the max value of the respective data (e.g. * for bar charts). * * @param styler the chart {@link Styler} * @param axisDirection the axis {@link Direction} * @param dataMaxValue the maximum value of the data corresponding with the axis. * @return the axis max value */ private static double getAxisMaxValue( Styler styler, Direction axisDirection, double dataMaxValue) { if (Direction.Y.equals(axisDirection) && styler instanceof CategoryStyler && dataMaxValue < 0) return 0; return dataMaxValue; } }
package be.msec.smartcard; import java.util.Arrays; //import be.msec.client.RandomData; //import be.msec.client.bte; //import java.security.KeyPair; //import java.security.KeyPairGenerator; //import java.security.PrivateKey; //import java.security.PublicKey; //import javax.crypto.Cipher; import javacard.framework.APDU; import javacard.framework.Applet; import javacard.framework.ISO7816; import javacard.framework.ISOException; import javacard.framework.OwnerPIN; import javacard.security.*; import javacard.framework.Util; //// in client not card //import javacard.security.*; //import javacardx.crypto.*; //creating keys for use in symmetric algorithms public class IdentityCard extends Applet { // CLA code in CommandAPDU header private final static byte IDENTITY_CARD_CLA =(byte)0x80; // INS codes private static final byte VALIDATE_PIN_INS = 0x22; private static final byte GET_SERIAL_INS = 0x24; private final static byte PIN_TRY_LIMIT =(byte)0x03; private final static byte PIN_SIZE =(byte)0x04; private final static byte REQ_VALIDATION_INS=(byte)0x16; // //INS codes for different SPs private final static byte GET_eGov_DATA=(byte)0x05; private final static byte GET_Health_DATA=(byte)0x06; private final static byte GET_SN_DATA=(byte)0x07; private final static byte GET_def_DATA=(byte)0x08; // TS_DATA: first check lastVal. time and update, diff . e.g. set at 24 hrs private final static byte GET_TS_DATA=(byte)0x09; //timestamp private final static byte SET_Data=(byte)0x10; private final static byte Set_PIN=(byte)0x15; // private byte reqTime=(byte)0x17; private final static short SW_VERIFICATION_FAILED = 0x6300; private final static short SW_PIN_VERIFICATION_REQUIRED = 0x6301; private static final APDU APDU = null; //// instance variables declaration private byte[] serial = new byte[]{0x30, 0x35, 0x37, 0x36, 0x39, 0x30, 0x31, 0x05}; private OwnerPIN pin; // //individuals identified by a service-specific pseudonym // private byte[] nym_Gov = new byte[]{0x11}; // to have something to test data saving on javacard // private byte[] nym_Health = new byte[]{0x12}; // private byte[] nym_SN = new byte[]{0x13}; // private byte[] nym_def = new byte[]{0x14}; //// instance variables // private byte[] name = new byte[]{0x01,0x02,0x03,0x04}; private byte[] name = {'i', 'n', 's', 'e', 'r', 't',' ', 'c','h','a','r'}; // private byte[] address; // private byte[] country; // private byte[] birthdate; // private byte[] age; // private byte[] gender; // private byte[] picture; // private byte[] bloodType; //personal informationn saved on card //input above instance variables into info below private byte[] info; private short incomingData; // private short newPin; // data for certification and encryption/decryption, time needed for cert verification private byte[] lastValidationTime = new byte[11]; //time format: "yyyy-D HH:mm:ss" private byte[] currentTime = new byte[11]; // private final static byte CertC0=(byte)0x20; //common cert // private final static byte SKC0=(byte)0x21; // private final static byte CertCA=(byte)0x22; //CA // private final static byte CertG=(byte)0x23; //cert for gov timestam // private final static byte SKG=(byte)0x24; // private final static byte CertSP=(byte)0x25; //cert in each domain // private final static byte SKsp=(byte)0x26; // private final static byte Ku=(byte)0x27; private final static byte privKey=(byte)0x28; private final static byte pubKey=(byte)0x29; // allocate all memory applet needs during its lifetime private IdentityCard() { /* * During instantiation of the applet, all objects are created. * In this example, this is the 'pin' object. */ pin = new OwnerPIN(PIN_TRY_LIMIT,PIN_SIZE); pin.update(new byte[]{0x01,0x02,0x03,0x04},(short) 0, PIN_SIZE); /* * This method registers the applet with the JCRE on the card. */ //create placeholder for personal information to be given per service provider //4086 from tutorial, might be too long for this javacard but might work in jcwde // info = new byte[4086]; register(); } // //Create object of keys // RSAPrivateKey thePrivateKey = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE, KeyBuilder.LENGTH_RSA_512, false); // RSAPublicKey thePublickKey = (RSAPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC, KeyBuilder.LENGTH_RSA_512, false); // KeyPair theKeyPair = new KeyPair(thePublickKey, thePrivateKey); /* * This method is called by the JCRE when installing the applet on the card. */ public static void install(byte bArray[], short bOffset, byte bLength) throws ISOException { new IdentityCard(); } /* * If no tries are remaining, the applet refuses selection. * The card can, therefore, no longer be used for identification. */ public boolean select() { if (pin.getTriesRemaining()==0) return false; return true; } /* * This method is called when the applet is selected and an APDU arrives. Processes incoming APDU */ public void process(APDU apdu) throws ISOException { //A reference to the buffer, where the APDU data is stored, is retrieved. byte[] buffer = apdu.getBuffer(); //needed for looping when sending large arrays short LC = apdu.getIncomingLength(); //If the APDU selects the applet, no further processing is required. if(this.selectingApplet()){ return; } //Check whether the indicated class of instructions is compatible with this applet. if (buffer[ISO7816.OFFSET_CLA] != IDENTITY_CARD_CLA)ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); //A switch statement is used to select a method depending on the instruction switch(buffer[ISO7816.OFFSET_INS]){ case VALIDATE_PIN_INS: validatePIN(apdu); break; case REQ_VALIDATION_INS: reqRevalidation(apdu); break; case GET_SERIAL_INS: getSerial(apdu); break; case GET_eGov_DATA: eGov_DATA(apdu); break; case GET_Health_DATA: HealthDATA(apdu); break; case GET_SN_DATA: SNDATA(apdu); break; case GET_def_DATA: defDATA(apdu); break; //update time if validateTIME returnns true case GET_TS_DATA: TSDATA(apdu); break; // //hard code // case SET_Data: // setData(apdu); // break; // //hard code // case Set_PIN: // setPin(apdu); // break; //If no matching instructions are found it is indicated in the status word of the response. //This can be done by using this method. As an argument a short is given that indicates //the type of warning. There are several predefined warnings in the 'ISO7816' class. default: ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); } } /* * This method is used to authenticate the owner of the card using a PIN code. */ private void validatePIN(APDU apdu){ byte[] buffer = apdu.getBuffer(); //The input data needs to be of length 'PIN_SIZE'. //Note that the byte values in the Lc and Le fields represent values between //0 and 255. Therefore, if a short representation is required, the following //code needs to be used: short Lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF); if(buffer[ISO7816.OFFSET_LC]==PIN_SIZE){ //This method is used to copy the incoming data in the APDU buffer. apdu.setIncomingAndReceive(); //Note that the incoming APDU data size may be bigger than the APDU buffer //size and may, therefore, need to be read in portions by the applet. //Most recent smart cards, however, have buffers that can contain the maximum //data size. This can be found in the smart card specifications. //If the buffer is not large enough, the following method can be used: //byte[] buffer = apdu.getBuffer(); //short bytesLeft = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF); //Util.arrayCopy(buffer, START, storage, START, (short)5); //short readCount = apdu.setIncomingAndReceive(); //short i = ISO7816.OFFSET_CDATA; //while ( bytesLeft > 0){ // Util.arrayCopy(buffer, ISO7816.OFFSET_CDATA, storage, i, readCount); // bytesLeft -= readCount; // i+=readCount; // readCount = apdu.receiveBytes(ISO7816.OFFSET_CDATA); if (pin.check(buffer, ISO7816.OFFSET_CDATA,PIN_SIZE)==false) ISOException.throwIt(SW_VERIFICATION_FAILED); } //shouldn't indicate that it was not accepted because of size, keep matter unknown // else ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); else ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } //receive signed time from SP through Client; update card time if client time more recent private boolean reqRevalidation(APDU apdu){ if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED); else{ byte[] buffer = apdu.getBuffer(); //read apdu time data sent from Client //verify time validity from G server through middleware currentTime = Arrays.copyOfRange(buffer, 9,20 ); //within same year, for completeness, if(lastValidationTime != null && Util.arrayCompare(lastValidationTime, (short)0, currentTime, (short)0, (short)4)==0){ //check if within 24 hours, same day of year if((short)(lastValidationTime[4]-currentTime[4])>1&&(short)(lastValidationTime[5]+currentTime[5])<2){ return true; } } else{ return false;// not within 24 hours or same year or lastValidationTime is null } } return false; } // 20 byte challenge private RandomData getRand(){ byte[] buf = new byte[20]; RandomData rand = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM); rand.generateData(buf, (short)0, (short)buf.length); return rand; } private void getSerial(APDU apdu){ //If the pin is not validated, a response APDU with the //'SW_PIN_VERIFICATION_REQUIRED' status word is transmitted. if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED); else{ //This sequence of three methods sends the data contained in //'identityFile' with offset '0' and length 'identityFile.length' //to the host application. apdu.setOutgoing(); apdu.setOutgoingLength((short)serial.length); apdu.sendBytesLong(serial,(short)0,(short)serial.length); } } // working in progress for all INS private void eGov_DATA(APDU apdu){ //If the pin is not validated, a response APDU with the //'SW_PIN_VERIFICATION_REQUIRED' status word is transmitted. if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED); else{ //This sequence of three methods sends the data contained in //'identityFile' with offset '0' and length 'identityFile.length' //to the host application. apdu.setOutgoing(); apdu.setOutgoingLength((short)name.length); apdu.sendBytesLong(name,(short)0,(short)name.length); } } private void HealthDATA(APDU apdu){ //If the pin is not validated, a response APDU with the //'SW_PIN_VERIFICATION_REQUIRED' status word is transmitted. if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED); else{ //This sequence of three methods sends the data contained in //'identityFile' with offset '0' and length 'identityFile.length' //to the host application. apdu.setOutgoing(); apdu.setOutgoingLength((short)name.length); apdu.sendBytesLong(name,(short)0,(short)name.length); } } private void defDATA(APDU apdu){ //If the pin is not validated, a response APDU with the //'SW_PIN_VERIFICATION_REQUIRED' status word is transmitted. if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED); else{ //This sequence of three methods sends the data contained in //'identityFile' with offset '0' and length 'identityFile.length' //to the host application. apdu.setOutgoing(); apdu.setOutgoingLength((short)info.length); apdu.sendBytesLong(info,(short)0,(short)info.length); } } //social network private void SNDATA(APDU apdu){ //If the pin is not validated, a response APDU with the //'SW_PIN_VERIFICATION_REQUIRED' status word is transmitted. if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED); else{ //This sequence of three methods sends the data contained in //'identityFile' with offset '0' and length 'identityFile.length' //to the host application. apdu.setOutgoing(); apdu.setOutgoingLength((short)info.length); apdu.sendBytesLong(info,(short)0,(short)info.length); } } //timeStamp private void TSDATA(APDU apdu){ //If the pin is not validated, a response APDU with the //'SW_PIN_VERIFICATION_REQUIRED' status word is transmitted. if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED); else{ } } //generate keys public PublicKey getPubKey(){ short keySize = 512; KeyPair kp = new KeyPair(KeyPair.ALG_RSA, keySize); kp.genKeyPair(); PrivateKey privKey = kp.getPrivate(); PublicKey pubKey = kp.getPublic(); return pubKey; } // maybe for later if we have the time // //no need for now, hard coded in // //gov initially sets data // private void setData(APDU apdu){ // short dataOffset = apdu.getOffsetCdata(); // short bytes_left = (short) buffer[ISO.OFFSET_LC]; // short readCount = apdu.setIncomingAndReceive(); // while (bytes_left > 0) { // //{process received data in buffer} // bytes_left -= readCount; // //get more data // readCount = apdu.receiveBytes (ISO.OFFSET_CDDATA); // //verification via certificate of // apdu.setIncomingAndReceive(); // apdu.receiveBytes(incomingData); // //no need for now, it's done by the client // //owner of card sets pin // private void setPin(APDU apdu){ // //If the pin is not validated, a response APDU with the // //'SW_PIN_VERIFICATION_REQUIRED' status word is transmitted. // if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED); // else{ // apdu.setIncomingAndReceive(); // apdu.receiveBytes(newPin); // // use: update(byte[] pin, short offset, byte length) // // to update pin object }
package org.yamcs.tctm; import java.io.EOFException; import java.io.IOException; import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import org.yamcs.ConfigurationException; import org.yamcs.TmPacket; import org.yamcs.YConfiguration; import org.yamcs.parameter.ParameterValue; import org.yamcs.utils.YObjectLoader; public class TcpTmDataLink extends AbstractTmDataLink implements Runnable { protected Socket tmSocket; protected String host; protected int port; protected long initialDelay; ParameterValue svConnectionStatus; String packetInputStreamClassName; Object packetInputStreamArgs; PacketInputStream packetInputStream; public TcpTmDataLink(String instance, String name, YConfiguration config) throws ConfigurationException { super(instance, name, config); if (config.containsKey("tmHost")) { // this is when the config is specified in tcp.yaml host = config.getString("tmHost"); port = config.getInt("tmPort"); } else { host = config.getString("host"); port = config.getInt("port"); } initialDelay = config.getLong("initialDelay", -1); if (config.containsKey("packetInputStreamClassName")) { this.packetInputStreamClassName = config.getString("packetInputStreamClassName"); } else { this.packetInputStreamClassName = CcsdsPacketInputStream.class.getName(); } this.packetInputStreamArgs = config.get("packetInputStreamArgs"); initPreprocessor(instance, config); } protected void openSocket() throws IOException { InetAddress address = InetAddress.getByName(host); tmSocket = new Socket(); tmSocket.setKeepAlive(true); tmSocket.connect(new InetSocketAddress(address, port), 1000); try { if (packetInputStreamArgs != null) { packetInputStream = YObjectLoader.loadObject(packetInputStreamClassName, tmSocket.getInputStream(), packetInputStreamArgs); } else { packetInputStream = YObjectLoader.loadObject(packetInputStreamClassName, tmSocket.getInputStream()); } } catch (ConfigurationException e) { log.error("Cannot instantiate the packetInput stream", e); throw e; } } @Override public void doStart() { setupSysVariables(); if (!isDisabled()) { new Thread(this).start(); } notifyStarted(); } @Override public void doStop() { if (sysParamCollector != null) { sysParamCollector.unregisterProducer(this); } if (tmSocket != null) { try { tmSocket.close(); } catch (IOException e) { log.warn("Exception got when closing the tm socket:", e); } tmSocket = null; } notifyStopped(); } @Override public void run() { if (initialDelay > 0) { try { Thread.sleep(initialDelay); initialDelay = -1; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } while (isRunningAndEnabled()) { TmPacket pwrt = getNextPacket(); if (pwrt == null) { break; } tmSink.processPacket(pwrt); } } public TmPacket getNextPacket() { TmPacket pwt = null; while (isRunningAndEnabled()) { try { if (tmSocket == null) { openSocket(); log.info("Link established to {}:{}", host, port); } byte[] packet = packetInputStream.readPacket(); updateStats(packet.length); pwt = packetPreprocessor.process(new TmPacket(timeService.getMissionTime(), packet)); if (pwt != null) { break; } } catch (EOFException e) { log.warn("TM Connection closed"); tmSocket = null; } catch (IOException e) { String exc = (e instanceof ConnectException) ? ((ConnectException) e).getMessage() : e.toString(); log.info("Cannot open or read TM socket {}:{} {}'. Retrying in 10s", host, port, exc); try { tmSocket.close(); } catch (Exception e2) { } tmSocket = null; for (int i = 0; i < 10; i++) { if (!isRunningAndEnabled()) { break; } try { Thread.sleep(1000); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); return null; } } } catch (PacketTooLongException e) { log.warn(e.toString()); try { tmSocket.close(); } catch (Exception e2) { } tmSocket = null; } } return pwt; } @Override public void doDisable() { if (tmSocket != null) { try { tmSocket.close(); } catch (IOException e) { log.warn("Exception got when closing the tm socket:", e); } tmSocket = null; } } @Override public void doEnable() { new Thread(this).start(); } @Override public String getDetailedStatus() { if (isDisabled()) { return String.format("DISABLED (should connect to %s:%d)", host, port); } if (tmSocket == null) { return String.format("Not connected to %s:%d", host, port); } else { return String.format("OK, connected to %s:%d, received %d packets", host, port, packetCount); } } @Override protected Status connectionStatus() { return (tmSocket == null)?Status.UNAVAIL:Status.OK; } }
package org.yamcs.usoctools; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.yamcs.ConfigurationException; import org.yamcs.YConfiguration; import org.yamcs.xtce.Comparison; import org.yamcs.xtce.ComparisonList; import org.yamcs.xtce.MatchCriteria; import org.yamcs.xtce.Parameter; import org.yamcs.xtce.SequenceContainer; import org.yamcs.xtce.XtceDb; import org.yamcs.xtceproc.XtceDbFactory; public class XtceUtil { HashMap<Long,SequenceContainer>apidPacketid2Name=new HashMap<Long,SequenceContainer>(); HashMap<Integer,SequenceContainer>packetid2Name=new HashMap<Integer,SequenceContainer>(); HashMap<String,Map<String,Integer>>name2Packetid=new HashMap<String,Map<String,Integer>>(); HashMap<String,Map<String,Long>> name2ApidPacketid=new HashMap<String,Map<String,Long>>(); HashMap<Long,String>responsePackets=new HashMap<Long,String>(); HashSet<Integer>apids=new HashSet<Integer>(); private final XtceDb xtcedb; static Map<XtceDb, XtceUtil> instances=new HashMap<XtceDb, XtceUtil>(); private XtceUtil(XtceDb xtcedb) { this.xtcedb=xtcedb; buildApidPacketIdMap(); } public synchronized static XtceUtil getInstance(XtceDb xtcedb) { XtceUtil x=instances.get(xtcedb); if(x==null) { x=new XtceUtil(xtcedb); instances.put(xtcedb, x); } return x; } private void buildApidPacketIdMap() { for (SequenceContainer sc:xtcedb.getSequenceContainers()) { int apid=-1; int packetid=-1; MatchCriteria crit = sc.getRestrictionCriteria(); if (crit instanceof ComparisonList) { ComparisonList clist = (ComparisonList)crit; for (Comparison comp:clist.getComparisonList()) { Parameter parameter = comp.getParameter(); String name = parameter.getName(); if (name.equals("ccsds-apid")) { apid = ((Number)comp.getValue()).intValue(); } if (name.equals("col-packet_id") || name.equals("packet-id")) { packetid = ((Number)comp.getValue()).intValue(); } } } // System.out.println("sc:"+sc.getName()+" apid:"+apid+" packetid:"+packetid); if(packetid!=-1) { if((apid!=-1)) { apids.add(apid); long ap=(((long)apid)<<32)+packetid; if("ccsds-response_packet".equals(sc.getBaseContainer().getName())) { responsePackets.put(ap,sc.getName()); } else { apidPacketid2Name.put(ap,sc); Map<String,Long> n2ap=name2ApidPacketid.get(null); if(n2ap==null) { n2ap=new HashMap<String,Long>(); name2ApidPacketid.put(null, n2ap); } n2ap.put(sc.getName(), ap); for(String ns:sc.getAliasSet().getNamespaces()) { n2ap=name2ApidPacketid.get(ns); if(n2ap==null) { n2ap=new HashMap<String,Long>(); name2ApidPacketid.put(ns, n2ap); } n2ap.put(sc.getAlias(ns), ap); } } } packetid2Name.put(packetid, sc); Map<String,Integer> n2p=name2Packetid.get(null); if(n2p==null) { n2p=new HashMap<String,Integer>(); name2Packetid.put(null, n2p); } n2p.put(sc.getName(), packetid); for(String ns:sc.getAliasSet().getNamespaces()) { n2p=name2Packetid.get(ns); if(n2p==null) { n2p=new HashMap<String,Integer>(); name2Packetid.put(ns, n2p); } n2p.put(sc.getAlias(ns), packetid); } } } } public String getPacketNameByApidPacketid(int apid, int packetId, String namespace) { long ap=(((long)apid)<<32)+packetId; if(responsePackets.containsKey(ap)) { return responsePackets.get(ap); } SequenceContainer sc=apidPacketid2Name.get(ap); if(sc==null) return null; if(namespace==null)return sc.getName(); else return sc.getAlias(namespace); } /** * this is to be used only if the previous method returns null. * the xtce files produced by CD-MCS are bogus: they identify packets based on packetId only which is not unique */ public String getPacketNameByPacketId(int packetId, String namespace) { SequenceContainer sc=packetid2Name.get(packetId); if(sc==null) return null; if(namespace==null)return sc.getName(); else return sc.getAlias(namespace); } public Set<Integer> getTmPacketApids() { return apids; } public boolean isResponsePacket(int apid, int packetId) { long ap=(((long)apid)<<32)+packetId; if(responsePackets.containsKey(ap)) return true; else return false; } /** * * @param name - the name of the packet (in the "default" namespace) * @return */ public Long getApidPacketId(String name) { return name2ApidPacketid.get(null).get(name); } public Long getApidPacketId(String name, String namespace) { Map<String,Long> n2ap=name2ApidPacketid.get(namespace); if(n2ap==null)return null; return n2ap.get(name); } public Integer getPacketId(String name, String namespace) { Map<String,Integer> n2p=name2Packetid.get(namespace); if(n2p==null)return null; return n2p.get(name); } public Integer getPacketId(String name) { return name2Packetid.get(null).get(name); } public Collection<String> getTmPacketNames(String namespace) { ArrayList<String> pn=new ArrayList<String>(); for(SequenceContainer sc:xtcedb.getSequenceContainers()){ String alias=sc.getAlias(namespace); if(alias!=null) pn.add(alias); } return pn; } public Collection<String> getResponsePacketNames() { return responsePackets.values(); } private void print(PrintStream out) { out.println("apidPacketid2Name: "); for(Entry<Long,SequenceContainer> entry:apidPacketid2Name.entrySet()) { long ap=entry.getKey(); int apid=(int)(ap>>32); int packetid=(int)(ap&0xFFFFFFFF); out.println(" ("+apid+", "+packetid+"): "+entry.getValue().getQualifiedName()); } } public static void main(String[] args) throws ConfigurationException { YConfiguration.setup(); XtceDb db=XtceDbFactory.getInstanceByConfig("erasmus-busoc"); XtceUtil xtceutil=XtceUtil.getInstance(db); xtceutil.print(System.out); } }
package org.yamcs.simulation; import org.junit.Test; import org.yamcs.ParameterValue; import org.yamcs.protobuf.Pvalue; import org.yamcs.protobuf.Pvalue.MonitoringResult; import org.yamcs.simulation.generated.ObjectFactory; import org.yamcs.simulation.generated.PpSimulation; import org.yamcs.tctm.PpListener; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import org.yamcs.ParameterValue; import org.yamcs.protobuf.Pvalue.MonitoringResult; import org.yamcs.simulation.generated.ObjectFactory; import org.yamcs.simulation.generated.PpSimulation; import org.yamcs.tctm.PpListener; import org.yamcs.utils.TimeEncoding; public class SimulationPpProviderTest { private static final String DATA_SCENARIO1 = "src/test/resources/simulation_data.xml"; private static final String DATA_SCENARIO2 = "src/test/resources/simulation_data2.xml"; private static final String DATA_SCENARIO_DATE = "src/test/resources/simulation_data_date.xml"; @BeforeClass public static void beforeClass() { TimeEncoding.setUp(); } @Test public void LoadSimulationData_loadOk() { // Arrange String fileName = DATA_SCENARIO1; SimulationPpProvider target = new SimulationPpProvider(); // Act PpSimulation ppSimulation = target.LoadSimulationData(fileName); // Assert assertTrue(ppSimulation != null); } @Test public void CreateXml() throws JAXBException { try { // ARRANGE File file = new File("src/test/resources/genTest.xml"); JAXBContext jaxbContext = JAXBContext .newInstance(PpSimulation.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // ACT ObjectFactory of = new ObjectFactory(); PpSimulation ppSimulation = of.createPpSimulation(); PpSimulation.ParameterSequence paramSequence1 = new PpSimulation.ParameterSequence(); PpSimulation.ParameterSequence.Parameter parameter1 = new PpSimulation.ParameterSequence.Parameter(); parameter1.setSpaceSystem("APM"); parameter1.setAquisitionStep(1); parameter1.setGenerationStep(2); parameter1.setParaName("SOLAR_toto"); paramSequence1.getParameter().add(parameter1); ppSimulation.getParameterSequence().add(paramSequence1); jaxbMarshaller.marshal(ppSimulation, file); jaxbMarshaller.marshal(ppSimulation, System.out); } catch (Exception e) { // ASSERT assertFalse(e.toString(), true); } } @Test public void ProcessSimulationData_Scenario1() { // Arrange SimulationPpProvider target = new SimulationPpProvider() { @Override public boolean IsRunning() { return true; } }; target.SetSimulationData(DATA_SCENARIO1); FakePpListener ppListener = new FakePpListener(); target.setPpListener(ppListener); target.enable(); // Act target.ProcessSimulationData(); // Assert assertTrue(ppListener.receivedValue.size() == 21); // check values assertTrue(ppListener.receivedValue.get(0).getEngValue() .getFloatValue() == (float) 1.1); assertTrue(ppListener.receivedValue.get(1).getEngValue() .getFloatValue() == (float) 1.2); assertTrue(ppListener.receivedValue.get(2).getEngValue() .getFloatValue() == (float) 2.1); assertTrue(ppListener.receivedValue.get(3).getEngValue() .getFloatValue() == (float) 3.5); assertTrue(ppListener.receivedValue.get(4).getEngValue() .getFloatValue() == (float) 1.1); assertTrue(ppListener.receivedValue.get(5).getEngValue() .getFloatValue() == (float) 1.2); assertTrue(ppListener.receivedValue.get(6).getEngValue() .getFloatValue() == (float) 2.1); assertTrue(ppListener.receivedValue.get(7).getEngValue() .getFloatValue() == (float) 3.5); // check generation time assertTrue(ppListener.receivedValue.get(0).getGenerationTime() == ppListener.receivedValue .get(1).getGenerationTime()); assertTrue(ppListener.receivedValue.get(4).getGenerationTime() == ppListener.receivedValue .get(5).getGenerationTime()); assertTrue(ppListener.receivedValue.get(2).getGenerationTime() - ppListener.receivedValue.get(1).getGenerationTime() == 2); assertTrue(ppListener.receivedValue.get(2).getGenerationTime() - ppListener.receivedValue.get(1).getGenerationTime() == 2); assertTrue(ppListener.receivedValue.get(18).getGenerationTime() - ppListener.receivedValue.get(1).getGenerationTime() == 30); assertTrue(ppListener.receivedValue.get(20).getGenerationTime() - ppListener.receivedValue.get(1).getGenerationTime() == 42); // check monitoring result assertTrue(ppListener.receivedValue.get(20).monitoringResult == MonitoringResult.WARNING_HIGH); } @Test public void ProcessSimulationData_Scenario2() { // Arrange SimulationPpProvider target = new SimulationPpProvider() { @Override public boolean IsRunning() { return true; } }; target.SetSimulationData(DATA_SCENARIO2); FakePpListener ppListener = new FakePpListener(); target.setPpListener(ppListener); target.enable(); // Act target.ProcessSimulationData(); // Assert assertTrue(ppListener.receivedValue.size() == 52); } @Test public void ProcessSimulationData_Date() { // Arrange SimulationPpProvider target = new SimulationPpProvider() { @Override public boolean IsRunning() { return true; } }; target.SetSimulationData(DATA_SCENARIO_DATE); FakePpListener ppListener = new FakePpListener(); target.setPpListener(ppListener); target.enable(); // Act long dateStart = TimeEncoding.currentInstant(); target.ProcessSimulationData(); long dateEnd = TimeEncoding.currentInstant(); // Assert assertTrue(ppListener.receivedValue.size() == 2); assertTrue(ppListener.receivedValue.get(1).getGenerationTime() == ppListener.receivedValue.get(1).getAcquisitionTime() - 1500); long elapsedTimeGen0 = ppListener.receivedValue.get(0).getGenerationTime() - dateStart; long elapsedTimeAcqu0 = ppListener.receivedValue.get(0).getAcquisitionTime() - dateStart; assertTrue(0 <= elapsedTimeGen0 && elapsedTimeGen0 < 200); assertTrue(1300 < elapsedTimeAcqu0 && elapsedTimeAcqu0 < 1600); long elapsedTimeGen1 = ppListener.receivedValue.get(1).getGenerationTime() - dateStart; long elapsedTimeAcqu1 = ppListener.receivedValue.get(1).getAcquisitionTime() - dateStart; assertTrue(1900 < elapsedTimeGen1 && elapsedTimeGen1 < 2100); assertTrue(3400 < elapsedTimeAcqu1 && elapsedTimeAcqu1 < 3600); assertTrue((dateEnd - dateStart) >= elapsedTimeAcqu1); } class FakePpListener implements PpListener { public List<ParameterValue> receivedValue; public FakePpListener() { receivedValue = new ArrayList<ParameterValue>(); } @Override public void updatePps(long gentime, String group, int seqNum, Collection<ParameterValue> params) { receivedValue.addAll(params); } @Override public void updateParams(long gentime, String group, int seqNum, Collection<Pvalue.ParameterValue> params) { } @Override >>>> added missing method public String toString() { String result = ""; long firstGenerationTime = 0; for (ParameterValue pv : receivedValue) { if (firstGenerationTime == 0) firstGenerationTime = pv.getGenerationTime(); result += "(" + pv.getEngValue().getFloatValue() + ", " + (pv.getGenerationTime() - firstGenerationTime) + ") "; } return result; } } }
package ca.six.kjdemo.proxy.mockito.basic; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; interface IGreet { void sayHello(String name); } class GreetImpl implements IGreet { @Override public void sayHello(String name) { System.out.println("Hello " + name); } } // IGreet, GreetImpl. IGreet obj = new GreetImpl(); // , /GreetImpl. ? (, AOP) // , IGreet. InvocationHandler, invoke() class Greet3 implements InvocationHandler { private Object delegate; public Object bind(Object delegate) { this.delegate = delegate; return Proxy.newProxyInstance( delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this ); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("insert new logic here"); Object result = method.invoke(this.delegate, args); return result; } } class DynamicProxyDemo2 { public static void main(String[] args) { IGreet worker = new GreetImpl(); IGreet obj = (IGreet) new Greet3().bind(worker); obj.sayHello("111"); } }
package suadb.record; import suadb.file.Chunk; import suadb.tx.Transaction; import java.util.ArrayList; import java.util.List; /** * Manages a suadb.file of records. * There are methods for iterating through the records * and accessing their contents. * @author Edward Sciore */ public class CellFile { private ArrayInfo ai; private Transaction tx; private String filename; private String attributename; private CellPage cp; private int currentchunknum = -1; private int numberofblocks; private int numberofchunks; // this variable is needed in order to find out if the current chunk is the last one /** * Constructs an object to manage a suadb.file of records. * If the suadb.file does not exist, it is created. * @param ai the table suadb.metadata * @param tx the transaction */ /** * Constructs an object to manage a suadb.file of records. * If the suadb.file does not exist, it is created. * @param ai the table suadb.metadata * @param tx the transaction * @param chunknum the chunk number of an array * @param attributename the name of attribute (SuaDB adopts separate storage for each attribute) */ public CellFile(ArrayInfo ai, Transaction tx, int chunknum, String attributename, int numberofblocks,int numberofchunks) { this.ai = ai; this.tx = tx; // this.currentchunknum = chunknum; this.attributename = attributename; this.numberofblocks = numberofblocks; this.numberofchunks = numberofchunks; // move to the specified chunk , updates itself moveTo(chunknum); } private String assignName(ArrayInfo ai, String attributename, int currentchunknum){ return ai.arrayName() + "_" + attributename + "_" + currentchunknum; } /** * Closes the suadb.record suadb.file. */ public void close() { cp.close(); } /** * Positions the current suadb.record so that a call to method next * will wind up at the first suadb.record. */ public void beforeFirst() { moveTo(0); } /** * Moves to the next suadb.record. Returns false if there * is no next suadb.record. * @return false if there is no next suadb.record. */ public boolean next() { while (true) { if (cp.next()) return true; if (atLaskChunk()) return false; moveTo(currentchunknum + 1); } } /** * Returns the value of the specified field * in the current suadb.record. * @return the integer value at that field */ public int getInt() { return cp.getInt(); } /** * Returns the value of the specified field * in the current suadb.record. * @return the string value at that field */ public String getString() { return cp.getString(); } /** * Sets the value of the specified field * in the current suadb.record. * @param val the new value for the field */ public void setInt(int val) { cp.setInt(val); } /** * Sets the value of the specified field * in the current suadb.record. * @param val the new value for the field */ public void setString(String val) { cp.setString(val); } /** * Deletes the current suadb.record. * The client must call next() to move to * the next suadb.record. * Calls to methods on a deleted suadb.record * have unspecified behavior. */ public void delete() { cp.delete(); } /** * Positions the current suadb.record as indicated by the * specified RID. * @param offset a offset of the cell in this chunk */ public void moveToId(int offset) { // moveTo(rid.blockNumber()); cp.moveToId(offset); } public void moveToId(int offset, int record) { // moveTo(rid.blockNumber()); cp.moveToId(offset); } /** * Returns the RID of the current suadb.record. * @return a suadb.record identifier */ public RID currentRid() { int id = cp.currentId(); return new RID(currentchunknum, id); } public void moveTo(int c) { if( currentchunknum == c) return; if (cp != null) cp.close(); currentchunknum = c; // Update filename - ILHYUN this.filename = assignName(this.ai,this.attributename,currentchunknum); if (tx.size(filename) == 0) createChunk(c); Chunk blk = new Chunk(filename, currentchunknum,numberofblocks); cp = new CellPage(blk, ai, tx, ai.recordLength(attributename)); } private boolean atLaskChunk() { return currentchunknum == (numberofchunks-1); } private void createChunk(int chunknum) { CellFormatter fmtr = new CellFormatter(ai,attributename); String filename =assignName(this.ai,this.attributename,chunknum); tx.createNewChunk(filename, fmtr,numberofblocks); } /** * Get current CID for identifying dimensions. * @return CID */ public CID getCurrentCID(){ return new CID(getCurrentDimensionValues(),ai); } /** * Get current dimension values. * @return List<Integer> the dimension. */ private List<Integer> getCurrentDimensionValues(){ // chunk == currentchunknum Schema schema = ai.schema(); List<String> dimensions = new ArrayList<String>(ai.schema().dimensions()); int numOfDimensions = dimensions.size(); List<Integer> result = new ArrayList<Integer>(); //Convert logical chunk number to the left bottom cell's coordinate of the chunk. int chunkNum = currentchunknum; int temp = 1; for(int i=0;i<numOfDimensions;i++) temp *= schema.getNumOfChunk(dimensions.get(i)); for(int i=0;i<numOfDimensions;i++){ temp /= schema.getNumOfChunk(dimensions.get(i)); result.add( (chunkNum/temp) * schema.chunkSize(dimensions.get(i))); chunkNum %= temp; } //Calculate the coordinate of the slot in the chunk. temp = 1; for(int i=0;i<numOfDimensions;i++) temp *= schema.chunkSize(dimensions.get(i)); int currentSlotNum = cp.currentId(); for(int i=0;i<numOfDimensions;i++){ temp /= schema.chunkSize(dimensions.get(i)); result.set(i, result.get(i) + (currentSlotNum/temp)); currentSlotNum %= temp; } return result; } /** * Get current chunk number. * @return */ public int getCurrentchunknum() { return currentchunknum; } }
package com.orm.query; import org.junit.Test; import static junit.framework.Assert.assertEquals; public class SelectTest { @Test public void testMergeCondition(){ Select where = Select.from(TestRecord.class).where(Condition.prop("test").eq("satya")); assertEquals("(test = ? )", where.getWhereCond()); assertEquals(1, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); where = Select.from(TestRecord.class).where(Condition.prop("test").eq("satya"), Condition.prop("prop").eq(2)); assertEquals("(test = ? AND prop = ? )", where.getWhereCond()); assertEquals(2, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); assertEquals("2", where.getArgs()[1]); } @Test public void testWhere(){ Select where = Select.from(TestRecord.class).where(Condition.prop("test").eq("satya")); assertEquals("(test = ? )", where.getWhereCond()); assertEquals(1, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); where = Select.from(TestRecord.class).where(Condition.prop("test").eq("satya"), Condition.prop("prop").eq(2)); assertEquals("(test = ? AND prop = ? )", where.getWhereCond()); assertEquals(2, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); assertEquals("2", where.getArgs()[1]); } @Test public void testWhereOr(){ Select where = Select.from(TestRecord.class).whereOr(Condition.prop("test").eq("satya")); assertEquals("(test = ? )", where.getWhereCond()); assertEquals(1, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); where = Select.from(TestRecord.class).whereOr(Condition.prop("test").eq("satya"), Condition.prop("prop").eq(2)); assertEquals("(test = ? OR prop = ? )", where.getWhereCond()); assertEquals(2, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); assertEquals("2", where.getArgs()[1]); } @Test public void testAnd(){ Select where = Select.from(TestRecord.class).whereOr(Condition.prop("test").eq("satya")); assertEquals("(test = ? )", where.getWhereCond()); assertEquals(1, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); where.and(Condition.prop("prop").eq(2)); assertEquals("(test = ? ) AND (prop = ? )", where.getWhereCond()); assertEquals(2, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); assertEquals("2", where.getArgs()[1]); } @Test public void testOr(){ Select where = Select.from(TestRecord.class).whereOr(Condition.prop("test").eq("satya")); assertEquals("(test = ? )", where.getWhereCond()); assertEquals(1, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); where.or(Condition.prop("prop").eq(2)); assertEquals("(test = ? ) OR (prop = ? )", where.getWhereCond()); assertEquals(2, where.getArgs().length); assertEquals("satya", where.getArgs()[0]); assertEquals("2", where.getArgs()[1]); } }
package com.bitgirder.log; import com.bitgirder.validation.Inputs; import com.bitgirder.validation.State; import java.io.PrintStream; public final class CodeLoggers { private static Inputs inputs = new Inputs(); private static State state = new State(); private static CodeLogger defl = createStreamLogger( System.out ); private CodeLoggers() {} public static CodeEventSink getDefaultEventSink() { return defl; } public static CodeLogger createStreamLogger( final PrintStream ps ) { inputs.notNull( ps, "ps" ); return new AbstractCodeLogger() { protected void logCodeImpl( CodeEvent ev ) { ps.println( CodeEvents.format( ev ) ); } }; } // Note: CodeLoggers.defl is not volatile, nor are this method or // getDefault(Logger|EventSink) synchronized. This is to make access of defl // as fast as possible with the understanding that any code which calls // replaceDefault() is likely in a position to make its own guarantees that // its call to replaceDefault() will have a happens-before relationship to // any ensuing accesses to getDefault(Logger|EventSink) that it would care // to guarantee will see its new value. public static void replaceDefaultSink( final CodeEventSink sink ) { inputs.notNull( sink, "sink" ); if ( sink instanceof CodeLogger ) defl = (CodeLogger) sink; else { defl = new AbstractCodeLogger() { protected void logCodeImpl( CodeEvent ev ) { sink.logCode( ev ); } }; } } public static void code( Object... msg ) { defl.code( msg ); } public static void codef( String tmpl, Object... args ) { code( String.format( tmpl, (Object[]) args ) ); } public static void codef( Throwable th, String tmpl, Object... msg ) { code( th, String.format( tmpl, msg ) ); } public static void code( Throwable th, Object... msg ) { defl.code( th, msg ); } public static void warn( Object... msg ) { defl.warn( msg ); } public static void warn( Throwable th, Object... msg ) { defl.warn( th, msg ); } public static void warnf( String tmpl, Object... args ) { warn( String.format( tmpl, (Object[]) args ) ); } public static void warnf( Throwable th, String tmpl, Object... msg ) { warn( th, String.format( tmpl, msg ) ); } public final static class Statics { private Statics() {} public static void code( Object... args ) { CodeLoggers.code( args ); } public static void codef( String tmpl, Object... args ) { CodeLoggers.codef( tmpl, args ); } public static void codef( Throwable th, String tmpl, Object... msg ) { CodeLoggers.codef( th, tmpl, msg ); } public static void code( Throwable th, Object... msg ) { CodeLoggers.code( th, msg ); } public static void warn( Object... args ) { CodeLoggers.warn( args ); } public static void warnf( String tmpl, Object... args ) { CodeLoggers.warnf( tmpl, args ); } public static void warnf( Throwable th, String tmpl, Object... msg ) { CodeLoggers.warnf( th, tmpl, msg ); } public static void warn( Throwable th, Object... msg ) { CodeLoggers.warn( th, msg ); } } }
package florian_haas.lucas.util; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.math.BigDecimal; import java.util.*; import java.util.List; import java.util.function.*; import java.util.logging.*; import javax.enterprise.inject.spi.CDI; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.imageio.ImageIO; import javax.validation.*; import org.apache.shiro.ShiroException; import org.primefaces.model.*; import florian_haas.lucas.model.EntityBase; import florian_haas.lucas.util.converter.CurrencyConverter; public class WebUtils { public static final String DEFAULT_MESSAGE_COMPONENT_ID = "defaultMessage"; public static final String GROWL_MESSAGE_COMPONENT_ID = "growlMessage"; public static final String STICKY_GROWL_MESSAGE_COMPONENT_ID = "stickyGrowlMessage"; public static void addDefaultInformationMessage(String message) { addInformationMessage(message, DEFAULT_MESSAGE_COMPONENT_ID); } public static void addDefaultTranslatedInformationMessage(String message, Object... params) { addTranslatedInformationMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params); } public static void addDefaultWarningMessage(String message) { addWarningMessage(message, DEFAULT_MESSAGE_COMPONENT_ID); } public static void addDefaultTranslatedWarningMessage(String message, Object... params) { addTranslatedWarningMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params); } public static void addDefaultErrorMessage(String message) { addErrorMessage(message, DEFAULT_MESSAGE_COMPONENT_ID); } public static void addDefaultTranslatedErrorMessage(String message, Object... params) { addTranslatedErrorMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params); } public static void addDefaultFatalMessage(String message) { addFatalMessage(message, DEFAULT_MESSAGE_COMPONENT_ID); } public static void addDefaultTranslatedFatalMessage(String message, Object... params) { addTranslatedFatalMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params); } public static void addGrowlInformationMessage(String message) { addInformationMessage(message, GROWL_MESSAGE_COMPONENT_ID); } public static void addGrowlTranslatedInformationMessage(String message, Object... params) { addTranslatedInformationMessage(message, GROWL_MESSAGE_COMPONENT_ID, params); } public static void addGrowlWarningMessage(String message) { addWarningMessage(message, GROWL_MESSAGE_COMPONENT_ID); } public static void addGrowlTranslatedWarningMessage(String message, Object... params) { addTranslatedWarningMessage(message, GROWL_MESSAGE_COMPONENT_ID, params); } public static void addGrowlErrorMessage(String message) { addErrorMessage(message, GROWL_MESSAGE_COMPONENT_ID); } public static void addGrowlTranslatedErrorMessage(String message, Object... params) { addTranslatedErrorMessage(message, GROWL_MESSAGE_COMPONENT_ID, params); } public static void addGrowlFatalMessage(String message) { addFatalMessage(message, GROWL_MESSAGE_COMPONENT_ID); } public static void addGrowlTranslatedFatalMessage(String message, Object... params) { addTranslatedFatalMessage(message, GROWL_MESSAGE_COMPONENT_ID, params); } public static void addStickyGrowlInformationMessage(String message) { addInformationMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID); } public static void addStickyGrowlTranslatedInformationMessage(String message, Object... params) { addTranslatedInformationMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params); } public static void addStickyGrowlWarningMessage(String message) { addWarningMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID); } public static void addStickyGrowlTranslatedWarningMessage(String message, Object... params) { addTranslatedWarningMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params); } public static void addStickyGrowlErrorMessage(String message) { addErrorMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID); } public static void addStickyGrowlTranslatedErrorMessage(String message, Object... params) { addTranslatedErrorMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params); } public static void addStickyGrowlFatalMessage(String message) { addFatalMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID); } public static void addStickyGrowlTranslatedFatalMessage(String message, Object... params) { addTranslatedFatalMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params); } public static void addInformationMessage(String message, String clientComponent) { addMessage(FacesMessage.SEVERITY_INFO, message, clientComponent); } public static void addTranslatedInformationMessage(String message, String clientComponent, Object... params) { addTranslatedMessage(FacesMessage.SEVERITY_INFO, message, clientComponent, params); } public static void addWarningMessage(String message, String clientComponent) { addMessage(FacesMessage.SEVERITY_WARN, message, clientComponent); } public static void addTranslatedWarningMessage(String message, String clientComponent, Object... params) { addTranslatedMessage(FacesMessage.SEVERITY_WARN, message, clientComponent, params); } public static void addErrorMessage(String message, String clientComponent) { addMessage(FacesMessage.SEVERITY_ERROR, message, clientComponent); } public static void addTranslatedErrorMessage(String message, String clientComponent, Object... params) { addTranslatedMessage(FacesMessage.SEVERITY_ERROR, message, clientComponent, params); } public static void addFatalMessage(String message, String clientComponent) { addMessage(FacesMessage.SEVERITY_FATAL, message, clientComponent); } public static void addTranslatedFatalMessage(String message, String clientComponent, Object... params) { addTranslatedMessage(FacesMessage.SEVERITY_FATAL, message, clientComponent, params); } private static void addTranslatedMessage(FacesMessage.Severity severity, String key, String clientComponent, Object... params) { addMessage(severity, getTranslatedMessage(key, params), clientComponent); } private static void addMessage(FacesMessage.Severity severity, String message, String clientComponent) { String titlePrefix = severity == FacesMessage.SEVERITY_WARN ? "warn" : severity == FacesMessage.SEVERITY_ERROR ? "error" : severity == FacesMessage.SEVERITY_FATAL ? "fatal" : "info"; FacesContext.getCurrentInstance().addMessage(clientComponent, new FacesMessage(severity, getTranslatedMessage("lucas.application.message." + titlePrefix), message)); } public static String getTranslatedMessage(String key, Object... params) { String message = getTranslatedMessage(key); for (int i = 0; i < params.length; i++) { if (params[i] != null) message = message.replaceAll("\\?" + i, params[i].toString()); } return message; } public static String getTranslatedMessage(String key) { return FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{msg['" + key + "']}", String.class); } public static boolean executeTask(FailableTask task, String successMessageKey, String warnMessageKey, String failMessageKey, Object... argParams) { return executeTask(task, successMessageKey, warnMessageKey, failMessageKey, WebUtils::addDefaultInformationMessage, WebUtils::addDefaultWarningMessage, WebUtils::addDefaultErrorMessage, WebUtils::addDefaultFatalMessage, argParams); } public static boolean executeTask(FailableTask task, String successMessageKey, String warnMessageKey, String failMessageKey, Consumer<String> informationMessageConsumer, Consumer<String> warnMessageConsumer, Consumer<String> errorMessageConsumer, Consumer<String> fatalMessageConsumer, Object... argParams) { boolean success = false; List<Object> paramsList = new ArrayList<>(); paramsList.addAll(Arrays.asList(argParams)); Object[] params = paramsList.toArray(); try { success = task.executeTask(paramsList); params = paramsList.toArray(); if (success && successMessageKey != null) { informationMessageConsumer.accept(WebUtils.getTranslatedMessage(successMessageKey, params)); } else if (warnMessageKey != null) { warnMessageConsumer.accept(WebUtils.getTranslatedMessage(warnMessageKey, params)); } } catch (ConstraintViolationException e) { for (ConstraintViolation<?> violation : e.getConstraintViolations()) { errorMessageConsumer .accept(getTranslatedMessage(failMessageKey, params) + violation.getPropertyPath() + " " + violation.getMessage()); } } catch (ShiroException e2) { errorMessageConsumer.accept(getTranslatedMessage(failMessageKey, params) + getTranslatedMessage("lucas.application.message.accessDenied") + e2.getLocalizedMessage()); } catch (Exception e3) { Logger.getAnonymousLogger().log(Level.SEVERE, e3, e3::getMessage); fatalMessageConsumer.accept(getTranslatedMessage(failMessageKey, params) + Utils.getStackTraceAsString(e3)); } return success; } public static final String JPEG_MIME = "image/jpeg"; public static final String JPEG_TYPE = "JPEG"; public static final String SVG_MIME = "image/svg+xml"; public static StreamedContent getJPEGImage(InputStream data) { return getDataAsStreamedContent(data, JPEG_MIME); } public static StreamedContent getJPEGImage(byte[] data) { return getDataAsStreamedContent(data, JPEG_MIME); } public static StreamedContent getSVGImage(byte[] data) { return getDataAsStreamedContent(data, SVG_MIME); } public static StreamedContent getSVGImage(InputStream data) { return getDataAsStreamedContent(data, SVG_MIME); } public static StreamedContent getDataAsStreamedContent(byte[] data, String mime) { return getDataAsStreamedContent(data != null ? new ByteArrayInputStream(data) : null, mime); } public static StreamedContent getDataAsStreamedContent(InputStream data, String mime) { if (data != null) return new DefaultStreamedContent(data, mime); return null; } public static BufferedImage getBufferedImageFromBytes(byte[] data) throws Exception { BufferedImage ret = null; ByteArrayInputStream in = new ByteArrayInputStream(data); ret = ImageIO.read(new ByteArrayInputStream(data)); in.close(); return ret; } public static byte[] convertBufferedImageToBytes(BufferedImage image, String type) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, type, out); out.close(); return out.toByteArray(); } public static BufferedImage getBufferedImage(Image image, int type) { BufferedImage tmp = new BufferedImage(image.getWidth(null), image.getHeight(null), type); Graphics g = tmp.createGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return tmp; } public static String getAsString(Object object, String converterId) { FacesContext context = FacesContext.getCurrentInstance(); return context.getApplication().createConverter(converterId).getAsString(context, UIComponent.getCurrentComponent(context), object); } public static <E extends EntityBase> void refreshEntities(List<E> entityList, List<E> selectedEntities, Function<Long, E> entityDao) { for (int i = 0; i < entityList.size(); i++) { E tmp = entityList.get(i); E refreshed = entityDao.apply(tmp.getId()); entityList.set(i, refreshed); if (selectedEntities.contains(tmp)) { selectedEntities.set(selectedEntities.indexOf(tmp), refreshed); } } } public static String getCurrencyAsString(BigDecimal currency) { FacesContext context = FacesContext.getCurrentInstance(); return CDI.current().select(CurrencyConverter.class).get().getAsString(context, UIComponent.getCurrentComponent(context), currency); } }
/** * Exercise the JniRdma native methods and collect micro-benchmarking info. * * Author(s): * azq @qzan9 anzhongqi@ncic.ac.cn */ package ac.ncic.syssw.jni; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Random; import java.util.Properties; import java.util.Date; import sun.nio.ch.DirectBuffer; public class RunJniRdma { public static final int DEFAULT_WARMUP_ITER = 16000; public static final int DEFAULT_BMK_ITER = 1000; public static final int DEFAULT_BUFFER_SIZE = 524288; public static final int DEFAULT_SLICE_SIZE = 131072; private RunJniRdma() { } private static RunJniRdma INSTANCE; public static RunJniRdma getInstance() { if (null == INSTANCE) { INSTANCE = new RunJniRdma(); } return INSTANCE; } public void simpleTestJniVerbs() { long devListAddr = -1; try { MutableInteger devNum = new MutableInteger(-1); devListAddr = JniVerbs.ibvGetDeviceList(devNum); System.out.printf("virtual address of device list: %#x.\n", devListAddr); System.out.printf("%d devices found.\n", devNum.intValue()); for (int i = 0; i < devNum.intValue(); i++) System.out.printf("%d: %s %#x\n", i, JniVerbs.ibvGetDeviceName(devListAddr, i), JniVerbs.ibvGetDeviceGUID(devListAddr, i)); } catch (VerbsException e) { System.out.println("check your IB/OFED configuration!"); } catch (Exception e) { e.printStackTrace(); } finally { if (devListAddr != -1) // this is not safe for Java. JniVerbs.ibvFreeDeviceList(devListAddr); } } public void simpleTestJniRdma(String[] args) { try { RdmaUserConfig userConfig = new RdmaUserConfig(DEFAULT_BUFFER_SIZE, (args.length == 0) ? null : args[0], 9999); ByteBuffer buffer = JniRdma.rdmaInit(userConfig); if (userConfig.getServerName() == null) { // server String data = "it's been a long day without you my friend, and i'll tell you all about it when i see you again ..."; System.out.println("data (String): " + data); buffer.putInt(data.length()); buffer.put(data.getBytes()); System.out.println("server writing to remote client buffer through RDMA ..."); JniRdma.rdmaWrite(); } else { // client System.out.println("client reading local buffer ..."); // while(true) if (buffer.getInt(userConfig.getBufferSize()) > 0) break; while(true) if (buffer.getInt(0) > 0) break; // buffer.position(userConfig.getBufferSize()); byte[] bytes = new byte[buffer.getInt()]; buffer.get(bytes); String data = new String(bytes); System.out.println("data (String): " + data); } } catch (RdmaException e) { System.out.println("RDMA error! check your native IB/OFED/TCP configuration!"); } catch (Exception e) { e.printStackTrace(); } finally { JniRdma.rdmaFree(); } } public void pipelineBenchmarkJniRdma() { try { int bufferSize; int sliceSize; long bufferAddress; byte[] data; long startTime, elapsedTime; RdmaUserConfig userConfig; InputStream is; PrintStream ps; Random random; Properties prop; Date date; ps = new PrintStream(new FileOutputStream("jni_log", true)); date = new Date(); System.out.println(); System.out.println("====== RDMA write benchmarking ======"); ps.println(); ps.println("====== " + date.toString() + " ======"); System.out.println(); System.out.println("Setting up parameters ..."); try { is = new FileInputStream("jni_config"); prop = new Properties(); prop.load(is); is.close(); if (prop.getProperty("bufferSize") != null) { bufferSize = Integer.parseInt(prop.getProperty("bufferSize")); } else { bufferSize = DEFAULT_BUFFER_SIZE; } if (prop.getProperty("sliceSize") != null) { sliceSize = Integer.parseInt(prop.getProperty("sliceSize")); } else { sliceSize = DEFAULT_SLICE_SIZE; } } catch (FileNotFoundException e) { System.out.println("jni_config file not found! using DEFAULT configurations!"); bufferSize = DEFAULT_BUFFER_SIZE; sliceSize = DEFAULT_SLICE_SIZE; }/* catch (Exception e) { e.printStackTrace(); } finally { }*/ System.out.println("Benchmarking configurations:"); System.out.println("- buffer size: " + bufferSize); System.out.println("- slice size: " + sliceSize); ps.println("buffer size: " + bufferSize + ", slice size: " + sliceSize); System.out.println(); System.out.println("initializing RDMA ..."); userConfig = new RdmaUserConfig(bufferSize, null, 9999); ByteBuffer buffer = JniRdma.rdmaInit(userConfig); System.out.println(); System.out.println("RDMA buffer info:"); System.out.println("- capacity: " + buffer.capacity() ); System.out.println("- limit: " + buffer.limit() ); System.out.println("- isDirect: " + buffer.isDirect() ); System.out.println("- order: " + buffer.order() ); System.out.println("- isReadOnly: " + buffer.isReadOnly()); data = new byte[bufferSize]; bufferAddress = ((DirectBuffer) buffer).address(); random = new Random(); System.out.println(); System.out.println("warming up ..."); elapsedTime = System.currentTimeMillis(); for (int t = 0; t < DEFAULT_WARMUP_ITER; t++) { startTime = System.nanoTime(); random.nextBytes(data); buffer.put(data); JniRdma.rdmaWrite(); U2Unsafe.copyByteArrayToDirectBuffer(data, 0, bufferAddress, bufferSize); JniRdma.rdmaWriteAsync(0, bufferSize); JniRdma.rdmaPollCq(1); buffer.clear(); if (t%100 == 0) { System.out.printf("%d: ", t); System.out.println(startTime + ", getting warmer ..."); } } System.out.printf("done! time of warming up is %d ms.", System.currentTimeMillis() - elapsedTime); System.out.println(); System.out.println(); System.out.println("benchmarking ByteBuffer.put (data re-generated each iteration) ..."); elapsedTime = 0; for (int t = 0; t < DEFAULT_BMK_ITER; t++) { random.nextBytes(data); startTime = System.nanoTime(); buffer.put(data); elapsedTime += System.nanoTime() - startTime; buffer.clear(); } System.out.printf("average time of putting %d bytes data into DirectByteBuffer is %.1f ns.", bufferSize, (double) elapsedTime / DEFAULT_BMK_ITER); System.out.println(); System.out.println(); System.out.println("benchmarking Unsafe.copyMemory (data NOT re-generated each iteration) ..."); random.nextBytes(data); startTime = System.nanoTime(); for (int t = 0; t < DEFAULT_BMK_ITER; t++) { U2Unsafe.copyByteArrayToDirectBuffer(data, 0, bufferAddress, bufferSize); } elapsedTime = System.nanoTime() - startTime; System.out.printf("average time of unsafe.copying %d bytes data into DirectByteBuffer is %.1f ns.", bufferSize, (double) elapsedTime / DEFAULT_BMK_ITER); System.out.println(); ps.printf("UNSAFE COPY %d bytes: %.1f ns.", bufferSize, (double) elapsedTime / DEFAULT_BMK_ITER); ps.println(); System.out.println(); System.out.println("benchmarking RDMA-write (data NOT re-generated each iteration) ..."); startTime = System.nanoTime(); for (int t = 0; t < DEFAULT_BMK_ITER; t++) { JniRdma.rdmaWrite(); } elapsedTime = System.nanoTime() - startTime; System.out.printf("average time of RDMA writing %d bytes is %.1f ns.", bufferSize, (double) elapsedTime / DEFAULT_BMK_ITER); System.out.println(); ps.printf("R-WRITE %d bytes: %.1f ns.", bufferSize, (double) elapsedTime / DEFAULT_BMK_ITER); ps.println(); for (sliceSize = 2048; sliceSize < bufferSize; sliceSize *= 2) { System.out.println(); System.out.println("benchmarking Unsafe.copyMemory (data NOT re-generated each iteration) ..."); startTime = System.nanoTime(); for (int t = 0; t < DEFAULT_BMK_ITER; t++) { U2Unsafe.copyByteArrayToDirectBuffer(data, 0, bufferAddress, sliceSize); } elapsedTime = System.nanoTime() - startTime; System.out.printf("average time of %dB unsafe.copying into DirectByteBuffer is %.1f ns.", sliceSize, (double) elapsedTime / DEFAULT_BMK_ITER); System.out.println(); ps.printf("UNSAFE COPY %d bytes: %.1f ns.", sliceSize, (double) elapsedTime / DEFAULT_BMK_ITER); ps.println(); System.out.println(); System.out.println("benchmarking sliced RDMA-write (data NOT re-generated each iteration) ..."); startTime = System.nanoTime(); for (int t = 0; t < DEFAULT_BMK_ITER; t++) { for (int i = 0; i < bufferSize / sliceSize; i++) { JniRdma.rdmaWriteAsync(sliceSize * i, sliceSize); JniRdma.rdmaPollCq(1); } } elapsedTime = System.nanoTime() - startTime; System.out.printf("average time of %dB-sliced RDMA writing %d bytes is %.1f ns.", sliceSize, bufferSize, (double) elapsedTime / DEFAULT_BMK_ITER); System.out.println(); ps.printf("R-WRITE %d bytes sliced: %.1f ns.", sliceSize, (double) elapsedTime / DEFAULT_BMK_ITER); ps.println(); System.out.println(); System.out.println("benchmarking async sliced RDMA-write (data NOT re-generated each iteration) ..."); startTime = System.nanoTime(); for (int t = 0; t < DEFAULT_BMK_ITER; t++) { for (int i = 0; i < bufferSize / sliceSize; i++) { JniRdma.rdmaWriteAsync(sliceSize * i, sliceSize); } for (int i = 0; i < bufferSize / sliceSize; i++) { JniRdma.rdmaPollCq(1); } } elapsedTime = System.nanoTime() - startTime; System.out.printf("average time of %dB-sliced async RDMA writing %d bytes is %.1f ns.", sliceSize, bufferSize, (double) elapsedTime / DEFAULT_BMK_ITER); System.out.println(); ps.printf("R-WRITE %d bytes sliced and async: %.1f ns.", sliceSize, (double) elapsedTime / DEFAULT_BMK_ITER); ps.println(); System.out.println(); System.out.println("benchmarking fully pipelined RDMA-write (data NOT re-generated each iteration) ..."); startTime = System.nanoTime(); for (int t = 0; t < DEFAULT_BMK_ITER; t++) { for (int i = 0; i < bufferSize / sliceSize; i++) { U2Unsafe.copyByteArrayToDirectBuffer(data, sliceSize * i, bufferAddress + sliceSize * i, sliceSize); JniRdma.rdmaWriteAsync(sliceSize * i, sliceSize); } for (int i = 0; i < bufferSize / sliceSize; i++) { JniRdma.rdmaPollCq(1); } } elapsedTime = System.nanoTime() - startTime; System.out.printf("average time of %dB-sliced pipelined RDMA writing %d bytes is %.1f ns.", sliceSize, bufferSize, (double) elapsedTime / DEFAULT_BMK_ITER); System.out.println(); ps.printf("R-WRITE %d bytes sliced and pipelined: %.1f ns.", sliceSize, (double) elapsedTime / DEFAULT_BMK_ITER); ps.println(); } System.out.println(); System.out.println("benchmarking x-stage pipelined RDMA-write (data NOT re-generated each iteration) ..."); startTime = System.nanoTime(); for (int t = 0; t < DEFAULT_BMK_ITER; t++) { U2Unsafe.copyByteArrayToDirectBuffer(data, 0, bufferAddress, 2048); JniRdma.rdmaWriteAsync(0, 2048); U2Unsafe.copyByteArrayToDirectBuffer(data, 2048, bufferAddress + 2048, 16384); JniRdma.rdmaWriteAsync(2048, 16384); U2Unsafe.copyByteArrayToDirectBuffer(data, 18432, bufferAddress + 18432, 32768); JniRdma.rdmaWriteAsync(18432, 32768); U2Unsafe.copyByteArrayToDirectBuffer(data, 51200, bufferAddress + 51200, 65536); JniRdma.rdmaWriteAsync(51200, 65536); U2Unsafe.copyByteArrayToDirectBuffer(data, 116736, bufferAddress + 116736, 131072); JniRdma.rdmaWriteAsync(116736, 131072); U2Unsafe.copyByteArrayToDirectBuffer(data, 247808, bufferAddress + 247808, 262144); JniRdma.rdmaWriteAsync(247808, 262144); U2Unsafe.copyByteArrayToDirectBuffer(data, 509952, bufferAddress + 509952, 14336); JniRdma.rdmaWriteAsync(509952, 14336); JniRdma.rdmaPollCq(1); JniRdma.rdmaPollCq(1); JniRdma.rdmaPollCq(1); JniRdma.rdmaPollCq(1); JniRdma.rdmaPollCq(1); JniRdma.rdmaPollCq(1); JniRdma.rdmaPollCq(1); } elapsedTime = System.nanoTime() - startTime; System.out.printf("average time of x-stage pipelined RDMA writing %d bytes is %.1f ns.\n", bufferSize, (double) elapsedTime / DEFAULT_BMK_ITER); ps.printf("R-WRITE x-staged pipelined: %.1f ns.\n", (double) elapsedTime / DEFAULT_BMK_ITER); System.out.println("\ntell client to shutdown ..."); buffer.clear(); buffer.order(ByteOrder.nativeOrder()); buffer.putInt(Integer.MAX_VALUE); JniRdma.rdmaWriteAsync(0, buffer.position()); JniRdma.rdmaPollCq(1); ps.println(); ps.close(); } catch (RdmaException e) { System.out.println("RDMA error! check your native IB/OFED/TCP configuration!"); } catch (Exception e) { e.printStackTrace(); } finally { JniRdma.rdmaFree(); } } }
package almost.functional; import almost.functional.utils.Iterables; /** * Utility operations on predicates. */ public class Predicates { private Predicates(){} /** * Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object). * @param targetRef the object reference with which to compare for equality, which may be null * @param <T> the type of arguments to the predicate * @return a predicate that tests if two arguments are equal according to Objects.equals(Object, Object) */ public static <T> Predicate<T> isEqual(final T targetRef) { return new Predicate<T>() { @Override public boolean test(T t) { return t.equals(targetRef); } }; } /** * Returns a predicate that that tests if an iterable contains an argument. * @param iterable the iterable, may not be null * @param <T> the type of the argument to the predicate * @return a predicate that that tests if an iterable contains an argument */ public static <T> Predicate<T> contains(final Iterable<T> iterable) { return new Predicate<T>() { @Override public boolean test(T t) { return Iterables.contains(iterable, t); } }; } /** * Negate an existing predicate's test result. * @param predicate An existing predicate. * @param <T> type of the predicate. * @return new predicate. * @since 1.5 */ public static <T> Predicate<T> negate(final Predicate<? super T> predicate) { return new Predicate<T>() { @Override public boolean test(T t) { return !predicate.test(t); } }; } /** * Create a predicate which is a logical and of two existing predicate. * @param first first predicate. * @param second second predicate. * @param <T> type of the predicates * @return resultant predicate * @since 1.5 */ public static <T> Predicate<T> and(final Predicate<? super T> first, final Predicate<? super T> second) { return new Predicate<T>() { @Override public boolean test(T t) { return first.test(t) && second.test(t); } }; } /** * Create a predicate which is a logical or of two existing predicate. * @param first first predicate. * @param second second predicate. * @param <T> type of the predicates * @return resultant predicate * @since 1.5 */ public static <T> Predicate<T> or(final Predicate<? super T> first, final Predicate<? super T> second) { return new Predicate<T>() { @Override public boolean test(T t) { return first.test(t) || second.test(t); } }; } }
package browserview; import java.awt.*; import java.io.*; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.*; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import com.sun.jna.platform.win32.User32; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinUser; import javafx.concurrent.Task; import ui.UI; import util.GitHubURL; import util.PlatformSpecific; /** * An abstraction for the functions of the Selenium web driver. * It depends minimally on UI for width adjustments. */ public class BrowserComponent { private static final Logger logger = LogManager.getLogger(BrowserComponent.class.getName()); private static final boolean USE_MOBILE_USER_AGENT = false; private static boolean isTestChromeDriver; // Chrome, Android 4.2.2, Samsung Galaxy S4 private static final String MOBILE_USER_AGENT = "Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39)" + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36"; private static final String CHROME_DRIVER_LOCATION = "browserview/"; private static final String CHROME_DRIVER_BINARY_NAME = determineChromeDriverBinaryName(); private String pageContentOnLoad = ""; private static final int SWP_NOSIZE = 0x0001; private static final int SWP_NOMOVE = 0x0002; private static HWND browserWindowHandle; private static User32 user32; private final UI ui; private ChromeDriverEx driver = null; // We want browser commands to be run on a separate thread, but not to // interfere with each other. This executor is limited to a single instance, // so it ensures that browser commands are queued and executed in sequence. // The alternatives would be to: // - allow race conditions // - interrupt the blocking WebDriver::get method // The first is not desirable and the second does not seem to be possible // at the moment. private Executor executor; public BrowserComponent(UI ui, boolean isTestChromeDriver) { this.ui = ui; executor = Executors.newSingleThreadExecutor(); BrowserComponent.isTestChromeDriver = isTestChromeDriver; setupJNA(); setupChromeDriverExecutable(); } /** * Called on application startup. Blocks until the driver is created. * Guaranteed to only happen once. */ public void initialise() { assert driver == null; executor.execute(() -> { driver = createChromeDriver(); logger.info("Successfully initialised browser component and ChromeDriver"); }); login(); } /** * Called when application quits. Guaranteed to only happen once. */ public void onAppQuit() { quit(); removeChromeDriverIfNecessary(); } /** * Quits the browser component. */ private void quit() { logger.info("Quitting browser component"); // The application may quit before the browser is initialised. // In that case, do nothing. if (driver != null) { try { driver.quit(); } catch (WebDriverException e) { // Chrome was closed; do nothing } } } /** * Creates, initialises, and returns a ChromeDriver. * @return */ private ChromeDriverEx createChromeDriver() { ChromeOptions options = new ChromeOptions(); if (USE_MOBILE_USER_AGENT) { options.addArguments(String.format("user-agent=\"%s\"", MOBILE_USER_AGENT)); } ChromeDriverEx driver = new ChromeDriverEx(options, isTestChromeDriver); if (!isTestChromeDriver) { driver.manage().window().setPosition(new Point((int) ui.getCollapsedX(), 0)); Rectangle availableDimensions = ui.getAvailableDimensions(); driver.manage().window().setSize(new Dimension( (int) availableDimensions.getWidth(), (int) availableDimensions.getHeight())); initialiseJNA(); } return driver; } private void removeChromeDriverIfNecessary() { if (ui.getCommandLineArgs().containsKey(UI.ARG_UPDATED_TO)) { new File(CHROME_DRIVER_BINARY_NAME).delete(); } } /** * Executes Javascript in the currently-active driver window. * Run on the UI thread (will block until execution is complete, * i.e. change implementation if long-running scripts must be run). * @param script */ private void executeJavaScript(String script) { driver.executeScript(script); logger.info("Executed JavaScript " + script.substring(0, Math.min(script.length(), 10))); } /** * Navigates to the New Label page on GitHub. * Run on a separate thread. */ public void newLabel() { logger.info("Navigating to New Label page"); runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForNewLabel(ui.logic.getDefaultRepo()))) { driver.get(GitHubURL.getPathForNewLabel(ui.logic.getDefaultRepo())); } }); } /** * Navigates to the New Milestone page on GitHub. * Run on a separate thread. */ public void newMilestone() { logger.info("Navigating to New Milestone page"); runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForNewMilestone(ui.logic.getDefaultRepo()))) { driver.get(GitHubURL.getPathForNewMilestone(ui.logic.getDefaultRepo())); } }); bringToTop(); } /** * Navigates to the New Issue page on GitHub. * Run on a separate thread. */ public void newIssue() { logger.info("Navigating to New Issue page"); runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForNewIssue(ui.logic.getDefaultRepo()))) { driver.get(GitHubURL.getPathForNewIssue(ui.logic.getDefaultRepo())); } }); bringToTop(); } /** * Navigates to the HubTurbo documentation page. * Run on a separate thread. */ public void showDocs() { logger.info("Showing documentation page"); runBrowserOperation(() -> driver.get(GitHubURL.getPathForDocsPage())); } /** * Navigates to the GitHub changelog page. * Run on a separate thread. */ // public void showChangelog(String version) { // logger.info("Showing changelog for version " + version); // runBrowserOperation(() -> driver.get(GitHubURL.getChangelogForVersion(version))); /** * Navigates to the GitHub page for the given issue in the currently-active * driver window. * Run on a separate thread. */ public void showIssue(String repoId, int id) { logger.info("Showing issue runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForIssue(repoId, id))) { driver.get(GitHubURL.getPathForIssue(repoId, id)); } }); } public void jumpToComment(){ WebElement comment = driver.findElementById("new_comment_field"); comment.click(); bringToTop(); } private boolean isBrowserActive(){ // if (isTestChromeDriver) { // return true; if (driver == null) { logger.info("Initializing ChromeDriver"); return false; } try { // Throws an exception if unable to switch to original HT tab // which then triggers a browser reset when called from runBrowserOperation driver.switchTo().window(driver.getWindowHandle()); // When the HT tab is closed (but the window is still alive), // a lot of the operations on the driver (such as getCurrentURL) // will hang (without throwing an exception, the thread will just freeze the UI forever), // so we cannot use getCurrentURL/getTitle to check if the original HT tab // is still open. The above line does not hang the driver but still throws // an exception, thus letting us detect that the HT tab is not active any more. return true; } catch (WebDriverException e) { logger.warn("Unable to reach bview. Resetting."); return false; } } // A helper function for reseting browser. private void resetBrowser(){ logger.info("Relaunching chrome."); quit(); // if the driver hangs driver = createChromeDriver(); login(); } /** * A helper function for running browser operations. * Takes care of running it on a separate thread, and normalises error-handling across * all types of code. */ private void runBrowserOperation (Runnable operation) { executor.execute(() -> { if (isBrowserActive()) { try { operation.run(); pageContentOnLoad = getCurrentPageSource(); } catch (WebDriverException e) { switch (BrowserComponentError.fromErrorMessage(e.getMessage())) { case NoSuchWindow: resetBrowser(); runBrowserOperation(operation); // Recurse and repeat break; case NoSuchElement: logger.info("Warning: no such element! " + e.getMessage()); break; default: break; } } } else { logger.info("Chrome window not responding."); resetBrowser(); runBrowserOperation(operation); } }); } /** * Logs in the currently-active driver window using the credentials * supplied by the user on login to the app. * Run on a separate thread. */ public void login() { logger.info("Logging in on GitHub..."); focus(ui.getMainWindowHandle()); runBrowserOperation(() -> { driver.get(GitHubURL.LOGIN_PAGE); try { WebElement searchBox = driver.findElement(By.name("login")); searchBox.sendKeys(ui.logic.credentials.username); searchBox = driver.findElement(By.name("password")); searchBox.sendKeys(ui.logic.credentials.password); searchBox.submit(); } catch (NoSuchElementException e) { // Already logged in; do nothing } }); } /** * One-time JNA setup. */ private static void setupJNA() { if (PlatformSpecific.isOnWindows()) { user32 = User32.INSTANCE; } } /** * JNA initialisation. Should happen whenever the Chrome window is recreated. */ private void initialiseJNA() { if (PlatformSpecific.isOnWindows()) { browserWindowHandle = user32.FindWindow(null, "data:, - Google Chrome"); } } private static String determineChromeDriverBinaryName() { return PlatformSpecific.isOnMac() ? "chromedriver" : PlatformSpecific.isOnWindows() ? "chromedriver.exe" : "chromedriver_linux"; } /** * Ensures that the chromedriver executable is in the project root before * initialisation. Since executables are packaged for all platforms, this also * picks the right version to use. */ private static void setupChromeDriverExecutable() { File f = new File(CHROME_DRIVER_BINARY_NAME); if (!f.exists()) { InputStream in = BrowserComponent.class.getClassLoader() .getResourceAsStream(CHROME_DRIVER_LOCATION + CHROME_DRIVER_BINARY_NAME); assert in != null : "Could not find " + CHROME_DRIVER_BINARY_NAME + " at " + CHROME_DRIVER_LOCATION + "; this path must be updated if the executables are moved"; OutputStream out; try { out = new FileOutputStream(CHROME_DRIVER_BINARY_NAME); IOUtils.copy(in, out); out.close(); f.setExecutable(true); } catch (IOException e) { logger.error("Could not load Chrome driver binary! " + e.getLocalizedMessage(), e); } logger.info("Could not find " + CHROME_DRIVER_BINARY_NAME + "; extracted it from jar"); } else { logger.info("Located " + CHROME_DRIVER_BINARY_NAME); } System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_BINARY_NAME); } /** * Resizes the browser window based on the given width. * Executed on another thread. */ public void resize(double width) { executor.execute(() -> { driver.manage().window().setPosition(new Point((int) width, 0)); driver.manage().window().setSize(new Dimension( (int) ui.getAvailableDimensions().getWidth(), (int) ui.getAvailableDimensions().getHeight())); }); } private void bringToTop(){ if (PlatformSpecific.isOnWindows()) { user32.ShowWindow(browserWindowHandle, WinUser.SW_RESTORE); user32.SetForegroundWindow(browserWindowHandle); } } public void focus(HWND mainWindowHandle){ if (PlatformSpecific.isOnWindows()) { user32.ShowWindow(browserWindowHandle, WinUser.SW_SHOWNOACTIVATE); user32.SetWindowPos(browserWindowHandle, mainWindowHandle, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); user32.SetForegroundWindow(mainWindowHandle); } } private String getCurrentPageSource() { return StringEscapeUtils.escapeHtml4( (String) driver.executeScript("return document.documentElement.outerHTML")); } public boolean hasBviewChanged() { if (isBrowserActive()) { if (getCurrentPageSource().equals(pageContentOnLoad)){ return false; } pageContentOnLoad = getCurrentPageSource(); return true; } return false; } public void scrollToTop() { String script = "window.scrollTo(0, 0)"; executeJavaScript(script); } public void scrollToBottom() { String script = "window.scrollTo(0, document.body.scrollHeight)"; executeJavaScript(script); } public void scrollPage(boolean isDownScroll) { String script; if (isDownScroll) script = "window.scrollBy(0,100)"; else script = "window.scrollBy(0, -100)"; executeJavaScript(script); } private void sendKeysToBrowser(String keyCode) { WebElement body; try { body = driver.findElementByTagName("body"); body.sendKeys(keyCode); } catch (Exception e) { logger.error("No such element" + e.getLocalizedMessage(), e); } } public void manageLabels(String keyCode) { sendKeysToBrowser(keyCode.toLowerCase()); bringToTop(); } public void manageAssignees(String keyCode) { sendKeysToBrowser(keyCode.toLowerCase()); bringToTop(); } public void manageMilestones(String keyCode) { sendKeysToBrowser(keyCode.toLowerCase()); bringToTop(); } public void showIssues() { logger.info("Navigating to Issues page"); runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForAllIssues(ui.logic.getDefaultRepo()))) { driver.get(GitHubURL.getPathForAllIssues(ui.logic.getDefaultRepo())); } }); } public void showPullRequests() { logger.info("Navigating to Pull requests page"); runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForPullRequests(ui.logic.getDefaultRepo()))) { driver.get(GitHubURL.getPathForPullRequests(ui.logic.getDefaultRepo())); } }); } public void showKeyboardShortcuts() { logger.info("Navigating to Keyboard Shortcuts"); runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForKeyboardShortcuts())) { driver.get(GitHubURL.getPathForKeyboardShortcuts()); } }); } public void showMilestones() { logger.info("Navigating to Milestones page"); runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForMilestones(ui.logic.getDefaultRepo()))) { driver.get(GitHubURL.getPathForMilestones(ui.logic.getDefaultRepo())); } }); } public void showContributors() { logger.info("Navigating to Contributors page"); runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForContributors(ui.logic.getDefaultRepo()))) { driver.get(GitHubURL.getPathForContributors(ui.logic.getDefaultRepo())); } }); } public boolean isCurrentUrlIssue() { return driver != null && GitHubURL.isUrlIssue(driver.getCurrentUrl()); } }
package cat.nyaa.nyaautils; import cat.nyaa.nyaautils.commandwarpper.Teleport; import cat.nyaa.nyaautils.dropprotect.DropProtectListener; import cat.nyaa.nyaautils.elytra.ElytraEnhanceListener; import cat.nyaa.nyaautils.elytra.FuelManager; import cat.nyaa.nyaautils.exhibition.ExhibitionListener; import cat.nyaa.nyaautils.lootprotect.LootProtectListener; import cat.nyaa.nyaautils.mailbox.MailboxListener; import cat.nyaa.nyaautils.realm.RealmListener; import cat.nyaa.nyaautils.timer.TimerListener; import cat.nyaa.nyaautils.timer.TimerManager; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import org.bukkit.command.TabCompleter; import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; public class NyaaUtils extends JavaPlugin { public static NyaaUtils instance; public I18n i18n; public CommandHandler commandHandler; public Configuration cfg; public LootProtectListener lpListener; public DropProtectListener dpListener; public DamageStatListener dsListener; public ExhibitionListener exhibitionListener; public MailboxListener mailboxListener; public ElytraEnhanceListener elytraEnhanceListener; public Teleport teleport; public FuelManager fuelManager; public TimerManager timerManager; public TimerListener timerListener; public WorldEditPlugin worldEditPlugin; public RealmListener realmListener; @Override public void onEnable() { instance = this; cfg = new Configuration(this); cfg.load(); i18n = new I18n(this, cfg.language); commandHandler = new CommandHandler(this, i18n); getCommand("nyaautils").setExecutor(commandHandler); getCommand("nyaautils").setTabCompleter((TabCompleter) commandHandler); lpListener = new LootProtectListener(this); dpListener = new DropProtectListener(this); dsListener = new DamageStatListener(this); elytraEnhanceListener = new ElytraEnhanceListener(this); teleport = new Teleport(this); exhibitionListener = new ExhibitionListener(this); mailboxListener = new MailboxListener(this); fuelManager = new FuelManager(this); timerManager = new TimerManager(this); timerListener = new TimerListener(this); worldEditPlugin = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); realmListener=new RealmListener(this); } @Override public void onDisable() { getServer().getScheduler().cancelTasks(this); getCommand("nyaautils").setExecutor(null); getCommand("nyaautils").setTabCompleter(null); HandlerList.unregisterAll(this); cfg.save(); } }
package cn.janescott; import cn.janescott.common.Constants; import cn.janescott.common.MyFilter; import org.jasypt.encryption.StringEncryptor; import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; @MapperScan("cn.janescott.repository.mapper") @SpringBootApplication public class ZoneApplication extends AbstractSecurityWebApplicationInitializer{ public static void main(String[] args) { SpringApplication.run(ZoneApplication.class, args); } @Bean public FilterRegistrationBean myFilterRegistration(){ FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new MyFilter());
package cn.net.communion.core; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import cn.net.communion.helper.FileHelper; import cn.net.communion.helper.PropsReader; import cn.net.communion.helper.RandomData; public class Parser { private String value; private Map<String, String> map; private Pattern varPattern; private Pattern rulePattern; private Pattern poolPattern; private Pattern datePattern; private PropsReader props; private Map<String, String> poolFileMap = new HashMap<String, String>(); static private Parser instance = null; private Random rand = new Random(); private Parser() { varPattern = Pattern.compile("\\$var\\{(\\w+)\\}"); rulePattern = Pattern.compile("\\$rule\\{([0-9a-zA-Z,]+)\\}"); poolPattern = Pattern.compile("\\$pool\\{([0-9a-zA-Z.]+)\\}"); datePattern = Pattern.compile("\\$date\\{([^\\s,]+),([^\\s,]+),([^\\s,]+)\\}"); props = PropsReader.getInstance(); } static Parser getInstance(String value, Map<String, String> map) { if (instance == null) { instance = new Parser(); } instance.setValue(value); instance.setMap(map); return instance; } static public boolean checkGrammar(String value) { return value.contains("$var") || value.contains("$rule") || value.contains("$pool") || value.contains("$date"); } public String execute() { parseVar().parseRule().parsePool().parseDate(); return value; } private Parser parseVar() { Matcher m = varPattern.matcher(value); if (m.find()) { String name = m.group(1); String propValue = props.getProperty("var." + name); value = value.replace(m.group(0), propValue != null ? propValue : this.map.get(name)); } return this; } private Parser parseRule() { Matcher m = rulePattern.matcher(value); if (m.find()) { value = value.replace(m.group(0), getRuleData(m.group(1).split(","))); } return this; } private String getRuleData(String[] arr) { String content = props.getProperty("rule." + arr[0]); if (content != null) { return RandomData.getRuleData(content, arr.length < 2 ? 6 : Integer.parseInt(arr[1])); } return null; } private Parser parsePool() { Matcher m = poolPattern.matcher(value); if (m.find()) { value = value.replace(m.group(0), getPoolData(m.group(1))); } return this; } private String getPoolData(String name) { String content = props.getProperty("pool." + name); if (content != null) { return RandomData.getPoolData(content.split(",")); } else { String poolContent = poolFileMap.get(name); if (poolContent == null) { poolContent = FileHelper.read("pool/" + name); if (poolContent == null) { return null; } poolFileMap.put(name, poolContent); } return RandomData.getPoolData(poolContent.split(",")); } } private Parser parseDate() { Matcher m = datePattern.matcher(value); if (m.find()) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(m.group(3)); LocalDate startDate = m.group(1).trim().equals("now") ? LocalDate.now() : LocalDate.parse(m.group(1).trim()); LocalDate endDate = m.group(2).trim().equals("now") ? LocalDate.now() : LocalDate.parse(m.group(2).trim()); int length = (int) startDate.until(endDate, ChronoUnit.DAYS); LocalDate randDate = length > 0 ? startDate.plusDays(rand.nextInt(length + 1)) : startDate.minusDays(rand.nextInt(1 - length)); value = value.replace(m.group(), randDate.format(formatter)); } return this; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Map<String, String> getMap() { return map; } public void setMap(Map<String, String> map) { this.map = map; } // public static void main(String [] args){ // Pattern datePattern = Pattern.compile("\\$date\\{([^\\s,]+),([^\\s,]+),([^\\s,]+)\\}"); // Matcher m = datePattern.matcher("$date{2017-02-01,now,yyyy/MM/dd}"); // if(m.find()){ // System.out.println(m.group(3)); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern(m.group(3)); // String start = m.group(1).trim(); // String end = m.group(2).trim(); // LocalDate startDate = start.equals("now") ? LocalDate.now() : LocalDate.parse(start); // LocalDate endDate = end.equals("now") ? LocalDate.now() : LocalDate.parse(end); // int length = (int) startDate.until(endDate, ChronoUnit.DAYS); // System.out.println(startDate.plusDays(rand.nextInt(length)).format(formatter)); }
package com.ajlopez.templie; import java.util.ArrayList; import java.util.List; class Compiler { private String text; private int length; private List<Step> steps = new ArrayList<Step>(); private int from = 0; Compiler(String text) { this.text = text; this.length = text.length(); } Template compile() { for (int k = 0; k < this.length - 1; k++) { if (this.text.charAt(k) != '$') continue; if (this.text.charAt(k + 1) != '{') continue; if (k > 0 && text.charAt(k - 1) == '\\') { if (k - 1> from) { this.steps.add(new StringStep(this.text.substring(this.from, k - 1))); } this.from = k; continue; } if (k > this.from) { this.steps.add(new StringStep(this.text.substring(this.from, k))); } this.from = k + 2; for (k++; k < this.length; k++) if (this.text.charAt(k) == '}') break; String name = this.text.substring(from, k).trim(); this.steps.add(new VariableStep(name)); this.from = k + 1; } if (this.length > this.from) this.steps.add(new StringStep(this.text.substring(this.from, this.length))); return new Template(this.steps); } }
package Controladores; import Controladores.exceptions.IllegalOrphanException; import Controladores.exceptions.NonexistentEntityException; import Controladores.exceptions.PreexistingEntityException; import Negocio.Cuenta; import java.io.Serializable; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import Negocio.Grupo; import Negocio.Usuario; import Negocio.Deuda; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; /** * * @author Pablo */ public class CuentaJpaController implements Serializable { public CuentaJpaController(EntityManagerFactory emf) { this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public void create(Cuenta cuenta) throws PreexistingEntityException, Exception { if (cuenta.getDeudaList() == null) { cuenta.setDeudaList(new ArrayList<Deuda>()); } EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Grupo grupoId = cuenta.getGrupoId(); if (grupoId != null) { grupoId = em.getReference(grupoId.getClass(), grupoId.getId()); cuenta.setGrupoId(grupoId); } Usuario usuarioId = cuenta.getUsuarioId(); if (usuarioId != null) { usuarioId = em.getReference(usuarioId.getClass(), usuarioId.getId()); cuenta.setUsuarioId(usuarioId); } List<Deuda> attachedDeudaList = new ArrayList<Deuda>(); for (Deuda deudaListDeudaToAttach : cuenta.getDeudaList()) { deudaListDeudaToAttach = em.getReference(deudaListDeudaToAttach.getClass(), deudaListDeudaToAttach.getDeudaPK()); attachedDeudaList.add(deudaListDeudaToAttach); } cuenta.setDeudaList(attachedDeudaList); em.persist(cuenta); if (grupoId != null) { grupoId.getCuentaList().add(cuenta); grupoId = em.merge(grupoId); } if (usuarioId != null) { usuarioId.getCuentaList().add(cuenta); usuarioId = em.merge(usuarioId); } for (Deuda deudaListDeuda : cuenta.getDeudaList()) { Cuenta oldCuentaOfDeudaListDeuda = deudaListDeuda.getCuenta(); deudaListDeuda.setCuenta(cuenta); deudaListDeuda = em.merge(deudaListDeuda); if (oldCuentaOfDeudaListDeuda != null) { oldCuentaOfDeudaListDeuda.getDeudaList().remove(deudaListDeuda); oldCuentaOfDeudaListDeuda = em.merge(oldCuentaOfDeudaListDeuda); } } em.getTransaction().commit(); } catch (Exception ex) { if (findCuenta(cuenta.getId()) != null) { throw new PreexistingEntityException("Cuenta " + cuenta + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } } public void edit(Cuenta cuenta) throws IllegalOrphanException, NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Cuenta persistentCuenta = em.find(Cuenta.class, cuenta.getId()); Grupo grupoIdOld = persistentCuenta.getGrupoId(); Grupo grupoIdNew = cuenta.getGrupoId(); Usuario usuarioIdOld = persistentCuenta.getUsuarioId(); Usuario usuarioIdNew = cuenta.getUsuarioId(); List<Deuda> deudaListOld = persistentCuenta.getDeudaList(); List<Deuda> deudaListNew = cuenta.getDeudaList(); List<String> illegalOrphanMessages = null; for (Deuda deudaListOldDeuda : deudaListOld) { if (!deudaListNew.contains(deudaListOldDeuda)) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add("You must retain Deuda " + deudaListOldDeuda + " since its cuenta field is not nullable."); } } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } if (grupoIdNew != null) { grupoIdNew = em.getReference(grupoIdNew.getClass(), grupoIdNew.getId()); cuenta.setGrupoId(grupoIdNew); } if (usuarioIdNew != null) { usuarioIdNew = em.getReference(usuarioIdNew.getClass(), usuarioIdNew.getId()); cuenta.setUsuarioId(usuarioIdNew); } List<Deuda> attachedDeudaListNew = new ArrayList<Deuda>(); for (Deuda deudaListNewDeudaToAttach : deudaListNew) { deudaListNewDeudaToAttach = em.getReference(deudaListNewDeudaToAttach.getClass(), deudaListNewDeudaToAttach.getDeudaPK()); attachedDeudaListNew.add(deudaListNewDeudaToAttach); } deudaListNew = attachedDeudaListNew; cuenta.setDeudaList(deudaListNew); cuenta = em.merge(cuenta); if (grupoIdOld != null && !grupoIdOld.equals(grupoIdNew)) { grupoIdOld.getCuentaList().remove(cuenta); grupoIdOld = em.merge(grupoIdOld); } if (grupoIdNew != null && !grupoIdNew.equals(grupoIdOld)) { grupoIdNew.getCuentaList().add(cuenta); grupoIdNew = em.merge(grupoIdNew); } if (usuarioIdOld != null && !usuarioIdOld.equals(usuarioIdNew)) { usuarioIdOld.getCuentaList().remove(cuenta); usuarioIdOld = em.merge(usuarioIdOld); } if (usuarioIdNew != null && !usuarioIdNew.equals(usuarioIdOld)) { usuarioIdNew.getCuentaList().add(cuenta); usuarioIdNew = em.merge(usuarioIdNew); } for (Deuda deudaListNewDeuda : deudaListNew) { if (!deudaListOld.contains(deudaListNewDeuda)) { Cuenta oldCuentaOfDeudaListNewDeuda = deudaListNewDeuda.getCuenta(); deudaListNewDeuda.setCuenta(cuenta); deudaListNewDeuda = em.merge(deudaListNewDeuda); if (oldCuentaOfDeudaListNewDeuda != null && !oldCuentaOfDeudaListNewDeuda.equals(cuenta)) { oldCuentaOfDeudaListNewDeuda.getDeudaList().remove(deudaListNewDeuda); oldCuentaOfDeudaListNewDeuda = em.merge(oldCuentaOfDeudaListNewDeuda); } } } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Long id = cuenta.getId(); if (findCuenta(id) == null) { throw new NonexistentEntityException("The cuenta with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Cuenta cuenta; try { cuenta = em.getReference(Cuenta.class, id); cuenta.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The cuenta with id " + id + " no longer exists.", enfe); } List<String> illegalOrphanMessages = null; List<Deuda> deudaListOrphanCheck = cuenta.getDeudaList(); for (Deuda deudaListOrphanCheckDeuda : deudaListOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add("This Cuenta (" + cuenta + ") cannot be destroyed since the Deuda " + deudaListOrphanCheckDeuda + " in its deudaList field has a non-nullable cuenta field."); } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } Grupo grupoId = cuenta.getGrupoId(); if (grupoId != null) { grupoId.getCuentaList().remove(cuenta); grupoId = em.merge(grupoId); } Usuario usuarioId = cuenta.getUsuarioId(); if (usuarioId != null) { usuarioId.getCuentaList().remove(cuenta); usuarioId = em.merge(usuarioId); } em.remove(cuenta); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public List<Cuenta> findCuentaEntities() { return findCuentaEntities(true, -1, -1); } public List<Cuenta> findCuentaEntities(int maxResults, int firstResult) { return findCuentaEntities(false, maxResults, firstResult); } private List<Cuenta> findCuentaEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(Cuenta.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public Cuenta findCuenta(Long id) { EntityManager em = getEntityManager(); try { return em.find(Cuenta.class, id); } finally { em.close(); } } public int getCuentaCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<Cuenta> rt = cq.from(Cuenta.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } public List<String> RealizarBalanceCuentasdeUsuario(int idGrupo, int idUsu) { EntityManager em = getEntityManager(); Query buscarCuentas; Query buscarDeudas; Query buscarTransaccion; Query buscarDuenoCuenta; UsuarioJpaController controUsu = new UsuarioJpaController(emf); int i, j, z; BigDecimal total, devolverID; List<String> listaDevolver = new ArrayList<String>(); //IF IMPORTANTE if (controUsu.fechaSalidaUsuario(idUsu, idGrupo) == true) { buscarCuentas = em.createNativeQuery("Select c.id,c.nombre from Cuenta c Where c.Grupo_id=? ").setParameter(1, idGrupo); List<Object[]> listaCuentas = buscarCuentas.getResultList(); List<BigDecimal> idCuentas = new ArrayList<BigDecimal>(); String devolver = ""; for (i = 0; i < listaCuentas.size(); i++) { BigDecimal id_cuenta = (BigDecimal) listaCuentas.get(i)[0]; idCuentas.add(id_cuenta); //System.out.println(id_cuenta); devolver = (String) listaCuentas.get(i)[1]; devolverID = (BigDecimal) listaCuentas.get(i)[0]; //System.out.println(devolver); buscarDeudas = em.createNativeQuery("Select d.cantidad,d.Id_Deuda from Deuda d Where d.Usuario_id=? and d.Cuenta_id=? ").setParameter(1, idUsu).setParameter(2, idCuentas.get(i)); List<Object[]> deuda_cuenta = buscarDeudas.getResultList(); if (deuda_cuenta.size() > 0) { BigDecimal deuda_cantidad = (BigDecimal) deuda_cuenta.get(0)[0]; BigDecimal id_deuda = (BigDecimal) deuda_cuenta.get(0)[1]; buscarTransaccion = em.createNativeQuery("Select t.cantidad,t.id from Transaccion t Where t.Deuda_Usuario_id=? and t.Deuda_Cuenta_id=? and t.Deuda_Id_Deuda= ? ").setParameter(1, idUsu).setParameter(2, idCuentas.get(i)).setParameter(3, id_deuda); // Un posible error cuando pase este codigo al proyecto, verificar el nombre de los atributos en la busqueda de la Transaccion como t.Deuda_Id_Deuda List<Object[]> listaTransacciones = buscarTransaccion.getResultList(); BigDecimal sumaTransacciones = new BigDecimal("0"); BigDecimal mult = new BigDecimal("-1"); total = deuda_cantidad.multiply(mult); for (j = 0; j < listaTransacciones.size(); j++) { BigDecimal cant_Transaccion = (BigDecimal) listaTransacciones.get(j)[0]; sumaTransacciones = sumaTransacciones.add(cant_Transaccion); total = sumaTransacciones.subtract(deuda_cantidad); } devolver = devolver + "$" + total + "$" + devolverID; //Devuelve el nombre de la cuenta, su balance total y el ID de la cuenta System.out.println("Esto es total : " + devolver); listaDevolver.add(devolver); } if (deuda_cuenta.size() == 0) { buscarDuenoCuenta = em.createNativeQuery("Select c.costo,c.nombre from Cuenta c Where c.Grupo_id=? and c.Usuario_id=?").setParameter(1, idGrupo).setParameter(2, idUsu); List<Object[]> listaCosto = buscarDuenoCuenta.getResultList(); if (listaCosto.size() == 0) { System.out.println("XD"); total= new BigDecimal(0) ; devolver = devolver + "$" + total + "$" + devolverID; } else { BigDecimal costoCuenta = (BigDecimal) listaCosto.get(0)[0]; total = costoCuenta; devolver = devolver + "$" + total + "$" + devolverID; listaDevolver.add(devolver); System.out.println(" Esto es el costo de la cuenta en la que es dueño : " + devolver); } } } } return listaDevolver; } public List<String> TablaUsuarioCuentaGrupo(int idUsu) { // Busco los grupos del usuario // Le mando el id del grupo y el id del usuario al metodo RealizarBalanceCuentasdeUsuario //Esto me manda una lista de las cuentas junto con su balance EntityManager em = getEntityManager(); UsuarioJpaController controUsu = new UsuarioJpaController(emf); // Si ocurre un error puede ser que el emf este en un null, tocaria volver a asignarle el EntityManagerFactory List<BigDecimal> gruposUsu = controUsu.GruposdeUsuario(idUsu); List<String> listaDevolver = new ArrayList<String>(); String devolver; for (int i = 0; i < gruposUsu.size(); i++) { if (controUsu.fechaSalidaUsuario(idUsu, gruposUsu.get(i).intValueExact()) == true) { List<String> cuentaUsu = RealizarBalanceCuentasdeUsuario(gruposUsu.get(i).intValueExact(), idUsu); for (int j = 0; j < cuentaUsu.size(); j++) { Query nombreGrupo = em.createNativeQuery("Select g.nombre,g.id from Grupo g Where g.id=? ").setParameter(1, gruposUsu.get(i)); List<Object[]> nGrupo = nombreGrupo.getResultList(); String grupo = (String) nGrupo.get(0)[0]; BigDecimal decgrupo = (BigDecimal) nGrupo.get(0)[1]; int id_grupo = decgrupo.intValueExact(); System.out.println("Esto es el nombre del grupo : " + grupo); devolver = cuentaUsu.get(j) + "$" + grupo + "$" + id_grupo; System.out.println("Esto es el devolver de tablas " + devolver); listaDevolver.add(devolver); } } } return listaDevolver; } }
package com.almasb.fxgl.util; import com.almasb.fxgl.logging.Logger; import com.almasb.fxgl.logging.SystemLogger; import java.util.ResourceBundle; /** * Holds version info about various frameworks used in FXGL. * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ public final class Version { private static final Logger log = SystemLogger.INSTANCE; private static final String FXGL_VERSION; private static final String JAVAFX_VERSION; private static final String JBOX_VERSION; private static final String KOTLIN_VERSION; static { ResourceBundle resources = ResourceBundle.getBundle("com.almasb.fxgl.util.version"); FXGL_VERSION = resources.getString("fxgl.version"); JAVAFX_VERSION = resources.getString("javafx.version"); JBOX_VERSION = resources.getString("jbox.version"); KOTLIN_VERSION = resources.getString("kotlin.version"); } public static void print() { log.info("FXGL-" + getAsString()); log.info("Source code and latest versions at: https://github.com/AlmasB/FXGL"); log.info(" Join the FXGL chat at: https://gitter.im/AlmasB/FXGL"); } /** * @return compile time version of FXGL */ public static String getAsString() { return FXGL_VERSION; } /** * @return compile time version of JavaFX */ public static String getJavaFXAsString() { return JAVAFX_VERSION; } /** * @return compile time version of JBox2D */ public static String getJBox2DAsString() { return JBOX_VERSION; } /** * @return compile time version of Kotlin */ public static String getKotlinAsString() { return KOTLIN_VERSION; } }
package com.aphyr.riemann.client; import java.io.*; import java.net.InetSocketAddress; import java.security.cert.*; import java.security.Key; import java.security.KeyFactory; import java.security.KeyManagementException; import java.security.KeyPair; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.*; import java.security.UnrecoverableKeyException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; import javax.net.ssl.*; import javax.xml.bind.DatatypeConverter; public class SSL { // You know, a mandatory password stored in memory so we can... encrypt... // data stored in memory. public static char[] keyStorePassword = "GheesBetDyPhuvwotNolofamLydMues9".toCharArray(); // The X.509 certificate factory public static CertificateFactory X509CertFactory() throws CertificateException { return CertificateFactory.getInstance("X.509"); } // An RSA key factory public static KeyFactory RSAKeyFactory() throws NoSuchAlgorithmException { return KeyFactory.getInstance("RSA"); } // Parses a base64-encoded string to a byte array public static byte[] base64toBinary(final String string) { return DatatypeConverter.parseBase64Binary(string); } // Turns a filename into an inputstream public static FileInputStream inputStream(final String fileName) throws FileNotFoundException { return new FileInputStream(new File(fileName)); } // Reads a filename into a string public static String slurp(final String file) throws FileNotFoundException { return new Scanner(new File(file)).useDelimiter("\\Z").next(); } // Loads an X.509 certificate from a file. public static X509Certificate loadCertificate(final String file) throws IOException, CertificateException { FileInputStream stream = null; try { stream = inputStream(file); return (X509Certificate) X509CertFactory().generateCertificate(stream); } finally { if (stream != null) { stream.close(); } } } // Loads a public key from a .crt file. public static PublicKey publicKey(final String file) throws IOException, CertificateException { return loadCertificate(file).getPublicKey(); } // Loads a private key from a PKCS8 file. public static PrivateKey privateKey(final String file) throws FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException { final Pattern p = Pattern.compile( "^ Pattern.MULTILINE | Pattern.DOTALL); final Matcher matcher = p.matcher(slurp(file)); matcher.find(); return RSAKeyFactory().generatePrivate( new PKCS8EncodedKeySpec( base64toBinary( matcher.group(1)))); } // Makes a KeyStore from a PKCS8 private key file, a public cert file, and the // signing CA certificate. public static KeyStore keyStore(final String keyFile, final String certFile, final String caCertFile) throws FileNotFoundException, IOException, KeyStoreException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { final Key key = privateKey(keyFile); final Certificate cert = loadCertificate(certFile); final Certificate caCert = loadCertificate(caCertFile); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); // alias, private key, password, certificate chain keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert }); return keyStore; } // Makes a trust store, suitable for backing a TrustManager, out of a CA cert // file. public static KeyStore trustStore(final String caCertFile) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setCertificateEntry("cacert", loadCertificate(caCertFile)); return keyStore; } // An X.509 trust manager for a KeyStore. public static TrustManager trustManager(final KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException { final TrustManagerFactory factory = TrustManagerFactory.getInstance("SunX509", "SunJSSE"); synchronized(factory) { factory.init(keyStore); for (TrustManager tm : factory.getTrustManagers()) { if (tm instanceof X509TrustManager) { return tm; } } return null; } } // An X.509 key manager for a KeyStore public static KeyManager keyManager(final KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { final KeyManagerFactory factory = KeyManagerFactory.getInstance("PKIX", "SunJSSE"); synchronized(factory) { factory.init(keyStore, keyStorePassword); for (KeyManager km : factory.getKeyManagers()) { if (km instanceof X509KeyManager) { return km; } } return null; } } // Builds an SSL Context from a PKCS8 key file, a certificate file, and a // trusted CA certificate used to verify peers. public static SSLContext sslContext(final String keyFile, final String certFile, final String caCertFile) throws KeyManagementException, NoSuchAlgorithmException, FileNotFoundException, KeyStoreException, IOException, InvalidKeySpecException, CertificateException, NoSuchProviderException, UnrecoverableKeyException { final KeyManager keyManager = keyManager( keyStore(keyFile, certFile, caCertFile)); final TrustManager trustManager = trustManager(trustStore(caCertFile)); final SSLContext context = SSLContext.getInstance("TLS"); context.init(new KeyManager[] { keyManager }, new TrustManager[] { trustManager }, null); return context; } public static SSLContext uncheckedSSLContext(final String keyFile, final String certFile, final String caCertFile) { // hack hack hack try { return sslContext(keyFile, certFile, caCertFile); } catch (KeyManagementException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { throw new RuntimeException(e); } catch (CertificateException e) { throw new RuntimeException(e); } catch (NoSuchProviderException e) { throw new RuntimeException(e); } catch (UnrecoverableKeyException e) { throw new RuntimeException(e); } } }
package com.techtalk4geeks.blogspot; public class Bean extends Item { public Bean(String name) { super(name); } }
package com.bio4j.model; import com.bio4j.angulillos.*; import com.bio4j.angulillos.Arity.*; public final class UniProtGraph<V,E> extends TypedGraph<UniProtGraph<V,E>,V,E> { public UniProtGraph(UntypedGraph<V,E> graph) { super(graph); } @Override public final UniProtGraph<V,E> self() { return this; } /* ## Proteins The first thing to point out as clearly as possible is: `Protein`s **do not** correspond to UniProt entries; we create a protein for every isoform present in any UniProt entry. The protein which is usually identified with the entry has true `isCanonical`. */ public final class Protein extends Vertex<Protein> { private Protein(V vertex) { super(vertex, protein); } @Override public final Protein self() { return this; } } public final ProteinType protein = new ProteinType(); public final class ProteinType extends VertexType<Protein> { @Override public final Protein fromRaw(V vertex) { return new Protein(vertex); } public final Accession accession = new Accession(); public final class Accession extends Property<String> implements FromAtMostOne, ToOne { private Accession() { super(String.class); } public final Index index = new Index(); public final class Index extends UniqueIndex<Accession, String> { private Index() { super(accession); } } } public final IsCanonical isCanonical = new IsCanonical(); public final class IsCanonical extends Property<Boolean> implements FromAtLeastOne, ToOne { private IsCanonical() { super(Boolean.class); } } public final FullName fullName = new FullName(); public final class FullName extends Property<String> implements FromAny, ToOne { private FullName() { super(String.class); } } public final Dataset dataset = new Dataset(); public final class Dataset extends Property<Datasets> implements FromAny, ToOne { private Dataset() { super(Datasets.class); } } public final Existence existence = new Existence(); public final class Existence extends Property<ExistenceEvidence> implements FromAny { private Existence() { super(ExistenceEvidence.class); } } public final Sequence sequence = new Sequence(); public final class Sequence extends Property<String> implements FromAny, ToOne { private Sequence() { super(String.class); } } public final Mass mass = new Mass(); public final class Mass extends Property<Integer> implements FromAny, ToOne { private Mass() { super(Integer.class); } } } public final class Isoforms extends Edge<Protein, Isoforms, Protein> { private Isoforms(E edge) { super(edge, isoforms); } @Override public final Isoforms self() { return this; } } public final IsoformsType isoforms = new IsoformsType(); public final class IsoformsType extends EdgeType<Protein, Isoforms, Protein> implements FromAny, ToAny { private IsoformsType() { super(protein, protein); } @Override public final Isoforms fromRaw(E edge) { return new Isoforms(edge); } } public final class GeneProducts extends Edge<GeneName, GeneProducts, Protein> { private GeneProducts(E edge) { super(edge, geneProducts); } @Override public final GeneProducts self() { return this; } } public final GeneProductsType geneProducts = new GeneProductsType(); public final class GeneProductsType extends EdgeType<GeneName, GeneProducts, Protein> implements FromAny, ToAny { private GeneProductsType() { super(geneName, protein); } @Override public final GeneProducts fromRaw(E edge) { return new GeneProducts(edge); } } public final class GeneName extends Vertex<GeneName> { private GeneName(V vertex) { super(vertex, geneName); } @Override public final GeneName self() { return this; } } public final GeneNameType geneName = new GeneNameType(); public final class GeneNameType extends VertexType<GeneName> { @Override public final GeneName fromRaw(V vertex) { return new GeneName(vertex); } } public static enum GeneLocations { chromosome, // TODO this the default case, which is missing in UniProt. Please fix/improve this name. apicoplast, chloroplast, organellar_chromatophore, cyanelle, hydrogenosome, mitochondrion, non_photosynthetic_plastid, nucleomorph, plasmid, plastid; } public static enum Datasets { swissProt, trEMBL; } public static enum ExistenceEvidence { proteinLevel, transcriptLevel, homologyInferred, predicted, uncertain; } public final class Keyword extends Vertex<Keyword> { private Keyword(V vertex) { super(vertex, keyword); } @Override public final Keyword self() { return this; } } public final KeywordType keyword = new KeywordType(); public final class KeywordType extends VertexType<Keyword> { @Override public final Keyword fromRaw(V vertex) { return new Keyword(vertex); } public final Name name = new Name(); public final class Name extends Property<String> implements FromAny, ToOne { private Name() { super(String.class); } } public final Definition definition = new Definition(); public final class Definition extends Property<String> implements FromAny, ToOne { private Definition() { super(String.class); } } public final Category category = new Category(); public final class Category extends Property<KeywordCategories> implements FromAny, ToOne { private Category() { super(KeywordCategories.class); } } } public static enum KeywordCategories { biologicalProcess, cellularComponent, codingSequenceDiversity, developmentalStage, disease, domain, ligand, molecularFunction, PTM, technicalTerm; } public final class Keywords extends Edge<Protein, Keywords, Keyword> { private Keywords(E edge) { super(edge, keywords); } @Override public final Keywords self() { return this; } } public final KeywordsType keywords = new KeywordsType(); public final class KeywordsType extends EdgeType<Protein, Keywords, Keyword> implements FromAtLeastOne, ToAny { private KeywordsType() { super(protein, keyword); } @Override public final Keywords fromRaw(E edge) { return new Keywords(edge); } } public final class Annotation extends Vertex<Annotation> { private Annotation(V vertex) { super(vertex, annotation); } @Override public final Annotation self() { return this; } } public final AnnotationType annotation = new AnnotationType(); public final class AnnotationType extends VertexType<Annotation> { @Override public final Annotation fromRaw(V vertex) { return new Annotation(vertex); } public final FeatureType featureType = new FeatureType(); public final class FeatureType extends Property<FeatureTypes> implements FromAtLeastOne, ToOne { private FeatureType() { super(FeatureTypes.class); } } } public final class Annotations extends Edge<Protein, Annotations, Annotation> { private Annotations(E edge) { super(edge, annotations); } @Override public final Annotations self() { return this; } } public final AnnotationsType annotations = new AnnotationsType(); public final class AnnotationsType extends EdgeType<Protein, Annotations, Annotation> implements FromAtLeastOne, ToAny { private AnnotationsType() { super(protein, annotation); } @Override public final Annotations fromRaw(E edge) { return new Annotations(edge); } public final Begin begin = new Begin(); public final class Begin extends Property<Integer> implements FromAny, ToOne { private Begin() { super(Integer.class); } } public final End end = new End(); public final class End extends Property<Integer> implements FromAny, ToOne { private End() { super(Integer.class); } } } public static enum FeatureTypes { activeSite, bindingSite, calciumBindingRegion, chain, coiledCoilRegion, compositionallyBiasedRegion, crosslink, disulfideBond, DNABindingRegion, domain, glycosylationSite, helix, initiatorMethionine, lipidMoietyBindingRegion, metalIonBindingSite, modifiedResidue, mutagenesisSite, nonConsecutiveResidues, nonTerminalResidue, nucleotidePhosphateBindingRegion, peptide, propeptide, regionOfInterest, repeat, nonstandardAminoAcid, sequenceConflict, sequenceVariant, shortSequenceMotif, signalPeptide, site, spliceVariant, strand, topologicalDomain, transitPeptide, transmembraneRegion, turn, unsureResidue, zincFingerRegion, intramembraneRegion; } public final class Comment extends Vertex<Comment> { private Comment(V vertex) { super(vertex, comment); } @Override public final Comment self() { return this; } } public final CommentType comment = new CommentType(); public final class CommentType extends VertexType<Comment> { @Override public final Comment fromRaw(V vertex) { return new Comment(vertex); } public final Topic topic = new Topic(); public final class Topic extends Property<CommentTopics> implements FromAtLeastOne, ToOne { private Topic() { super(CommentTopics.class); } } public final Text text = new Text(); public final class Text extends Property<String> implements FromAny, ToOne { private Text() { super(String.class); } } } /* This enum only contains those topics which do *not* give rise to specific vertex types. */ public static enum CommentTopics { allergen, alternativeProducts, // TODO remove, isoforms biotechnology, biophysicochemicalProperties, catalyticActivity, caution, cofactor, developmentalStage, disease, domain, disruptionPhenotype, enzymeRegulation, function, induction, miscellaneous, pathway, pharmaceutical, polymorphism, PTM, RNAEditing, similarity, subcellularLocation, sequenceCaution, subunit, tissueSpecificity, toxicDose, onlineInformation, massSpectrometry, interaction; } }
package com.db.prisma.droolspoc; import com.db.prisma.droolspoc.generation.Pain00100108Generator; import com.db.prisma.droolspoc.pain001.Document; import org.xml.sax.SAXException; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.Date; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicLong; public class Main { private static int sleep = 0; public static void main(String[] args) throws IOException, SAXException, JAXBException { final AtomicLong instructionsTotal = new AtomicLong(); final AtomicLong generatedTotal = new AtomicLong(); final AtomicLong marshalledTotal = new AtomicLong(); final AtomicLong validatedTotal = new AtomicLong(); long startTime = new Date().getTime(); final ConcurrentLinkedQueue<Document> generated = new ConcurrentLinkedQueue<>(); final ConcurrentLinkedQueue<String> marshalled = new ConcurrentLinkedQueue<>(); Thread generatorThread = new Thread(new Runnable() { Pain00100108Generator generator; { generator = new Pain00100108Generator(); generator.maxInBatch = 5; generator.batchMax = 5; } @Override public void run() { Thread.currentThread().setName("Generator thread"); while (true) { if (generated.size() > 1000) { try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("Generator thread exiting"); } } Document pain = generator.generate(); instructionsTotal.addAndGet(Long.parseLong(pain.getCstmrCdtTrfInitn().getGrpHdr().getNbOfTxs())); generated.add(pain); generatedTotal.incrementAndGet(); } } }); Thread marshallerThread = new Thread(new Runnable() { JAXBContext jc = JAXBContext.newInstance("com.db.prisma.droolspoc.pain001"); Marshaller marshaller = jc.createMarshaller(); @Override public void run() { Thread.currentThread().setName("Marshaller thread"); while (true) { if (marshalled.size() > 1000) { try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("Marshaller thread exiting"); break; } } Document poll = null; try { poll = generated.poll(); if (poll != null) { StringWriter xml = new StringWriter(); marshaller.marshal(poll, xml); marshalled.add(xml.toString()); marshalledTotal.incrementAndGet(); } } catch (Exception e) { if (poll != null) System.out.println("Could not marshall document:" + poll.getCstmrCdtTrfInitn().getGrpHdr().getMsgId()); } } } }); Thread validatorThread = new Thread(new Runnable() { Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new StreamSource(new File("xsd/pain.001.001.08.xsd"))); Validator validator = schema.newValidator(); @Override public void run() { Thread.currentThread().setName("Validator thread"); while (true) { try { String poll = marshalled.poll(); if (poll != null) { validator.validate(new StreamSource(new StringReader(poll))); validatedTotal.incrementAndGet(); } Thread.sleep(sleep); } catch (Exception e) { System.out.println("Validator thread exiting"); } } } }); Thread infoThread = new Thread(() -> { Thread.currentThread().setName("Info thread"); while (true) { try { System.out.println(); System.out.println("Time passed:" + (new Date().getTime() - startTime) / 60000.0 + " min"); System.out.println("Generated queue size:" + generated.size()); System.out.println("Marshalled queue size:" + marshalled.size()); System.out.println("generatedTotal = " + generatedTotal.get()); System.out.println("marshalledTotal = " + marshalledTotal.get()); System.out.println("validatedTotal = " + validatedTotal.get()); System.out.println("instructionsTota = " + instructionsTotal.get()); Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("Info thread exiting"); } } }); generatorThread.start(); marshallerThread.start(); validatorThread.start(); infoThread.start(); } }
package com.filestack.model; import com.filestack.model.transform.base.ImageTransform; import com.filestack.util.FilestackException; import com.filestack.util.FilestackService; import com.filestack.util.Networking; import io.reactivex.Completable; import io.reactivex.Single; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.concurrent.Callable; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okio.BufferedSink; import okio.BufferedSource; import okio.Okio; import org.apache.tika.Tika; import retrofit2.Response; /** * References a file in Filestack. */ public class FileLink { private String apiKey; private String handle; private Security security; private FilestackService.Cdn cdnService; private FilestackService.Api apiService; /** * Constructs an instance without security. * * @param apiKey account key from the dev portal * @param handle id for a file, first path segment in dev portal urls */ public FileLink(String apiKey, String handle) { this(apiKey, handle, null); } public FileLink(String apiKey, String handle, Security security) { this.apiKey = apiKey; this.handle = handle; this.security = security; this.cdnService = Networking.getCdnService(); this.apiService = Networking.getApiService(); } /** * Directly returns the content of a file. * * @return byte[] of file content * @throws IOException for network failures, invalid handles, or invalid security */ public byte[] getContent() throws IOException { String policy = security != null ? security.getPolicy() : null; String signature = security != null ? security.getSignature() : null; return cdnService.get(this.handle, policy, signature) .execute() .body() .bytes(); } /** * Saves the file to the specified directory using the name it was uploaded with. * * @param directory location to save the file in * @return {@link File File} object pointing to new file * @throws IOException for network failures, invalid handles, or invalid security */ public File download(String directory) throws IOException { return download(directory, null); } /** * Saves the file to the specified directory overriding the name it was uploaded with. * * @param directory location to save the file in * @param filename local name for the file * @return {@link File File} object pointing to new file * @throws IOException for network failures, invalid handles, or invalid security */ public File download(String directory, String filename) throws IOException { String policy = security != null ? security.getPolicy() : null; String signature = security != null ? security.getSignature() : null; Response<ResponseBody> response = cdnService.get(this.handle, policy, signature).execute(); if (filename == null) { filename = response.headers().get("x-file-name"); } File file = new File(directory + "/" + filename); file.createNewFile(); BufferedSource source = response.body().source(); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(source); sink.close(); return file; } /** * Replace the content of an existing file handle. * Does not update the filename or MIME type. * * @param pathname path to the file, can be local or absolute * @throws IOException for network failures, invalid handles, or invalid security * @throws FileNotFoundException if the given pathname isn't a file or doesn't exist */ public void overwrite(String pathname) throws IOException { if (security == null) { throw new FilestackException("Overwrite requires security to be set"); } File file = new File(pathname); if (!file.isFile()) { throw new FileNotFoundException(pathname); } Tika tika = new Tika(); String mimeType = tika.detect(file); RequestBody body = RequestBody.create(MediaType.parse(mimeType), file); apiService.overwrite(handle, security.getPolicy(), security.getSignature(), body).execute(); } /** * Deletes a file handle. * Requires security to be set. * * @throws IOException for network failures, invalid handles, or invalid security */ public void delete() throws IOException { if (security == null) { throw new FilestackException("Delete requires security to be set"); } apiService.delete(handle, apiKey, security.getPolicy(), security.getSignature()).execute(); } // Async method wrappers /** * Async, observable version of {@link #getContent()}. * Throws same exceptions. */ public Single<byte[]> getContentAsync() { return Single.fromCallable(new Callable<byte[]>() { @Override public byte[] call() throws IOException { return getContent(); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Async, observable version of {@link #download(String)}. * Throws same exceptions. */ public Single<File> downloadAsync(final String directory) { return downloadAsync(directory, null); } /** * Async, observable version of {@link #download(String, String)}. * Throws same exceptions. */ public Single<File> downloadAsync(final String directory, final String filename) { return Single.fromCallable(new Callable<File>() { @Override public File call() throws IOException { return download(directory, filename); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Async, observable version of {@link #overwrite(String)}. * Throws same exceptions. */ public Completable overwriteAsync(final String pathname) { return Completable.fromAction(new Action() { @Override public void run() throws IOException { overwrite(pathname); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Async, observable version of {@link #delete()}. * Throws same exceptions. */ public Completable deleteAsync() { return Completable.fromAction(new Action() { @Override public void run() throws IOException { delete(); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Creates an image transformation object for this file. * A transformation call isn't made directly by this method. * * @return {@link ImageTransform ImageTransform} instance configured for this file */ public ImageTransform imageTransform() { return new ImageTransform(this); } public String getHandle() { return handle; } public Security getSecurity() { return security; } }
package com.gengo.client; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.gengo.client.GengoConstants; import com.gengo.client.enums.HttpMethod; import com.gengo.client.enums.JobStatus; import com.gengo.client.enums.Rating; import com.gengo.client.enums.RejectReason; import com.gengo.client.exceptions.GengoException; import com.gengo.client.payloads.Approval; import com.gengo.client.payloads.FileJob; import com.gengo.client.payloads.Payload; import com.gengo.client.payloads.TranslationJob; import com.gengo.client.payloads.Payloads; import com.gengo.client.payloads.Rejection; public class GengoClient extends JsonHttpApi { /** Strings used to represent TRUE and FALSE in requests */ public static final String MYGENGO_TRUE = "1"; public static final String MYGENGO_FALSE = "0"; final private boolean usesSandbox; /** * Initialize the client. * @param publicKey your Gengo.com public API key * @param privateKey your Gengo.com private API key */ public GengoClient(String publicKey, String privateKey) { this(publicKey, privateKey, false); } /** * Initialize the client with the option to use the sandbox. * @param publicKey your Gengo.com public API key * @param privateKey your Gengo.com private API key * @param useSandbox true to use the sandbox, false to use the live service */ public GengoClient(String publicKey, String privateKey, boolean useSandbox) { super(publicKey, privateKey); this.usesSandbox = useSandbox; } /** * Get URL which requests are sent for. */ private String getBaseUrl() { if (usesSandbox) { return GengoConstants.BASE_URL_SANDBOX; } else { return GengoConstants.BASE_URL_STANDARD; } } /** * Get account statistics. * @return the response from the server * @throws GengoException */ public JSONObject getAccountStats() throws GengoException { String url = getBaseUrl() + "account/stats"; return call(url, HttpMethod.GET); } /** * Get account balance. * @return the response from the server * @throws GengoException */ public JSONObject getAccountBalance() throws GengoException { String url = getBaseUrl() + "account/balance"; return call(url, HttpMethod.GET); } /** * Get preferred translators in array by langs and tier * @return the response from the server * @throws GengoException */ public JSONObject getAccountPreferredTranslators() throws GengoException { String url = getBaseUrl() + "account/preferred_translators"; return call(url, HttpMethod.GET); } /** * Submit multiple jobs for translation. * @param jobs TranslationJob payload objects * @param processAsGroup true iff the jobs should be processed as a group * @return the response from the server * @throws GengoException */ public JSONObject postTranslationJobs(List<TranslationJob> jobs, boolean processAsGroup) throws GengoException { try { String url = getBaseUrl() + "translate/jobs"; JSONObject data = new JSONObject(); /* We can safely cast our list of jobs into a list of the payload base type */ @SuppressWarnings({ "rawtypes", "unchecked" }) List<Payload> p = (List)jobs; data.put("jobs", (new Payloads(p)).toJSONArray()); data.put("as_group", processAsGroup ? MYGENGO_TRUE : MYGENGO_FALSE); JSONObject rsp = call(url, HttpMethod.POST, data); return rsp; } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Submit multiple file jobs for translation. * @param jobs FileJob payload objects * @return the response from the server * @throws GengoException */ public JSONObject postFileJobs(List<FileJob> jobs) throws GengoException { try { String url = getBaseUrl() + "translate/jobs"; JSONObject data = new JSONObject(); /* We can safely cast our list of jobs into a list of the payload base type */ @SuppressWarnings({ "rawtypes", "unchecked" }) List<Payload> p = (List)jobs; data.put("jobs", (new Payloads(p)).toJSONArray()); JSONObject rsp = call(url, HttpMethod.POST, data); return rsp; } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Request revisions for a job. * @param id The job ID * @param comments Comments for the translator * @return the response from the server * @throws GengoException */ public JSONObject reviseTranslationJob(int id, String comments) throws GengoException { try { String url = getBaseUrl() + "translate/job/" + id; JSONObject data = new JSONObject(); data.put("action", "revise"); data.put("comment", comments); return call(url, HttpMethod.PUT, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Approve a translation. * @param id The job ID * @param ratingTime Rating of the translation time/speed * @param ratingQuality Rating of the translation quality * @param ratingResponse Rating of the translator responsiveness * @param feedbackForTranslator Feedback for the translator * @param feedbackForGengo Feedback for Gengo * @param feedbackIsPublic Whether the src/tgt text & feedback can be shared publicly * @return Response from the server * @throws GengoException */ public JSONObject approveTranslationJob(int id, Rating ratingTime, Rating ratingQuality, Rating ratingResponse, String commentsForTranslator, String commentsForGengo, boolean feedbackIsPublic) throws GengoException { try { String url = getBaseUrl() + "translate/job/" + id; JSONObject data = new JSONObject(); data.put("action", "approve"); if (commentsForTranslator != null) { data.put("for_translator", commentsForTranslator); } if (commentsForGengo != null) { data.put("for_mygengo", commentsForGengo); } if (ratingTime != null) { data.put("rating_time", ratingTime.toString()); } if (ratingQuality != null) { data.put("rating_quality", ratingQuality.toString()); } if (ratingResponse != null) { data.put("rating_response", ratingResponse.toString()); } data.put("public", feedbackIsPublic ? MYGENGO_TRUE : MYGENGO_FALSE); return call(url, HttpMethod.PUT, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Approve a translation. * * @deprecated {@link GengoClient#approveTranslationJob(int, Rating, Rating, Rating, String, String, boolean)} * * @param id The job ID * @param rating Rating of the translation * @param feedbackForTranslator Feedback for the translator * @param feedbackForGengo Feedback for Gengo * @param feedbackIsPublic Whether the src/tgt text & feedback can be shared publicly * @return Response from the server * @throws GengoException */ public JSONObject approveTranslationJob(int id, Rating rating, String commentsForTranslator, String commentsForGengo, boolean feedbackIsPublic) throws GengoException { return approveTranslationJob(id, rating, rating, rating, commentsForTranslator, commentsForGengo, feedbackIsPublic); } /** * Approve a translation. The feedback will be private. * @param id The job ID * @param ratingTime Rating of the translation time/speed * @param ratingQuality Rating of the translation quality * @param ratingResponse Rating of the translator responsiveness * @param feedbackForTranslator Feedback for the translator * @param feedbackForGengo Feedback for Gengo * @return Response from the server * @throws GengoException */ public JSONObject approveTranslationJob(int id, Rating ratingTime, Rating ratingQuality, Rating ratingResponse, String commentsForTranslator, String commentsForGengo) throws GengoException { return approveTranslationJob(id, ratingTime, ratingQuality, ratingResponse, commentsForTranslator, commentsForGengo, false); } /** * Approve a translation. The feedback will be private. * * @deprecated {@link GengoClient#approveTranslationJob(int, Rating, Rating, Rating, String, String)} * * @param id The job ID * @param rating Rating of the translation * @param feedbackForTranslator Feedback for the translator * @param feedbackForGengo Feedback for Gengo * @return Response from the server * @throws GengoException */ public JSONObject approveTranslationJob(int id, Rating rating, String commentsForTranslator, String commentsForGengo) throws GengoException { return approveTranslationJob(id, rating, rating, rating, commentsForTranslator, commentsForGengo, false); } /** * Reject a translation. * @param id the job ID * @param reason reason for rejection * @param comments comments for Gengo * @param captcha the captcha image text * @param requeue true iff the job should be passed on to another translator * @return the response from the server * @throws GengoException */ public JSONObject rejectTranslationJob(int id, RejectReason reason, String comments, String captcha, boolean requeue) throws GengoException { try { String url = getBaseUrl() + "translate/job/" + id; JSONObject data = new JSONObject(); data.put("action", "reject"); data.put("reason", reason.toString().toLowerCase()); data.put("comment", comments); data.put("captcha", captcha); data.put("follow_up", requeue ? "requeue" : "cancel"); return call(url, HttpMethod.PUT, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Archive a translation. * @deprecated * @param id the job ID * @return the response from the server * @throws GengoException */ public JSONObject archiveTranslationJob(int id) throws GengoException { try { String url = getBaseUrl() + "translate/job/" + id; JSONObject data = new JSONObject(); data.put("action", "archive"); // Todo: Archive functionality parameters are not documented. return call(url, HttpMethod.PUT, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Get a translation job * @param id the job id * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJob(int id) throws GengoException { String url = getBaseUrl() + "translate/job/" + id; return call(url, HttpMethod.GET); } /** * Get all translation jobs * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobs() throws GengoException { return getTranslationJobs(null, null, null, null); } /** * Get selected translation jobs * @param ids a list of job ids to retrieve * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobs(List<Integer> ids) throws GengoException { return getTranslationJobs(ids, null, null, null); } /** * Get specific translation jobs. * @param ids a list of job ids to retrieve * @param status one of the JobStatus * @param timestampAfter Unix epoch seconds from which to filter submitted jobs * @param count limit count of jobs(default 10, maximum 200) * @throws GengoException */ public JSONObject getTranslationJobs(List<Integer> ids, JobStatus status, Integer timestampAfter, Integer count) throws GengoException { String url = getBaseUrl() + "translate/jobs/"; JSONObject data = new JSONObject(); if (ids != null && ids.size() > 0) { url += join(ids, ","); } if (status != null) { try { data.put("status", status.getStatusString()); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } if (timestampAfter != null && timestampAfter > 0) { try { data.put("timestamp_after", timestampAfter); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } if (count != null && count > 0) { try { data.put("count", count); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } return call(url, HttpMethod.GET, data); } /** * Revise jobs with revision comment. * @param HashMap instance which consists of job ID and comment text * @throws GengoException */ public JSONObject reviseTranslationJobs(HashMap<Integer, String> jobs) throws GengoException { try { String url = getBaseUrl() + "translate/jobs"; JSONObject data = new JSONObject(); data.put("action", "revise"); // [begin] Generate 'job_ids' parameter. JSONArray job_ids = new JSONArray(); for (Entry<Integer, String> iJob : jobs.entrySet()) { HashMap<String, Object> job = new HashMap<String, Object>(); job.put("job_id", iJob.getKey()); job.put("comment", iJob.getValue()); job_ids.put(job); } // [end] Generate 'job_ids' parameter. data.put("job_ids", job_ids); return call(url, HttpMethod.PUT, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Approve jobs with collateral attributes. * @param jobs list of Approval instance * @throws GengoException */ public JSONObject approveTranslationJobs(List<Approval> jobs) throws GengoException { try { String url = getBaseUrl() + "translate/jobs"; JSONObject data = new JSONObject(); data.put("action", "approve"); JSONArray iJobs = new JSONArray(); for (Approval job : jobs) { iJobs.put(job.toJSONObject()); } data.put("job_ids", iJobs); return call(url, HttpMethod.PUT, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Reject jobs with collateral attributes. * @param jobs list of Rejection instance * @throws GengoException */ public JSONObject rejectTranslationJobs(List<Rejection> jobs) throws GengoException { try { String url = getBaseUrl() + "translate/jobs"; JSONObject data = new JSONObject(); data.put("action", "reject"); JSONArray iJobs = new JSONArray(); for (Rejection job : jobs) { iJobs.put(job.toJSONObject()); } data.put("job_ids", iJobs); return call(url, HttpMethod.PUT, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Archive jobs. * @param jobs list of job ID * @return * @throws GengoException */ public JSONObject archiveTranslationJobs(List<Integer> jobs) throws GengoException { try { String url = getBaseUrl() + "translate/jobs"; JSONObject data = new JSONObject(); data.put("action", "archive"); data.put("job_ids", jobs); return call(url, HttpMethod.PUT, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Post a comment for a translation job * @param id the ID of the job to comment on * @param comment the comment * @return the response from the server * @throws GengoException */ public JSONObject postTranslationJobComment(int id, String comment) throws GengoException { try { String url = getBaseUrl() + "translate/job/" + id + "/comment"; JSONObject data = new JSONObject(); data.put("body", comment); return call(url, HttpMethod.POST, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Get comments for a translation job * @param id the job ID * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobComments(int id) throws GengoException { String url = getBaseUrl() + "translate/job/" + id + "/comments/"; return call(url, HttpMethod.GET); } /** * Get feedback for a translation job * @param id the job ID * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobFeedback(int id) throws GengoException { String url = getBaseUrl() + "translate/job/" + id + "/feedback"; return call(url, HttpMethod.GET); } /** * Get all revisions for a translation job * @param id the job ID * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobRevisions(int id) throws GengoException { String url = getBaseUrl() + "translate/job/" + id + "/revisions"; return call(url, HttpMethod.GET); } /** * Get a specific revision for a translation job * @param id the job ID * @param revisionId the ID of the revision to retrieve * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobRevision(int id, int revisionId) throws GengoException { String url = getBaseUrl() + "translate/job/" + id + "/revision/" + revisionId; return call(url, HttpMethod.GET); } /** * Cancel a translation job. It can only be deleted if it has not been started by a translator. * @param id the job ID * @return the response from the server * @throws GengoException */ public JSONObject deleteTranslationJob(int id) throws GengoException { String url = getBaseUrl() + "translate/job/" + id; return call(url, HttpMethod.DELETE); } /** * Get a list of supported languages and their language codes. * @return the response from the server * @throws GengoException */ public JSONObject getServiceLanguages() throws GengoException { String url = getBaseUrl() + "translate/service/languages"; return call(url, HttpMethod.GET); } /** * Get a list of supported language pairs, tiers, and credit prices. * @return the response from the server * @throws GengoException */ public JSONObject getServiceLanguagePairs() throws GengoException { String url = getBaseUrl() + "translate/service/language_pairs"; return call(url, HttpMethod.GET); } /** * Get a list of supported language pairs, tiers and credit prices for a specific source language. * @param sourceLanguageCode the language code for the source language * @return the response from the server * @throws GengoException */ public JSONObject getServiceLanguagePairs(String sourceLanguageCode) throws GengoException { try { String url = getBaseUrl() + "translate/service/language_pairs"; JSONObject data = new JSONObject(); data.put("lc_src", sourceLanguageCode); return call(url, HttpMethod.GET, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Get a quote for text translation jobs. * @param jobs a list of TranslationJob instance * @return * @throws GengoException */ public JSONObject determineTranslationCostText(List<TranslationJob> jobs) throws GengoException { try { String url = getBaseUrl() + "translate/service/quote"; JSONObject data = new JSONObject(); JSONArray _jobs = new JSONArray(); data.put("jobs", _jobs); for (TranslationJob iJob : jobs) { _jobs.put(iJob.toJSONObject()); } return call(url, HttpMethod.POST, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Get a quote for translation jobs. * @deprecated {@link GengoClient#determineTranslationCostText(List)}} * @param jobs Translation job objects to be quoted for * @return the response from the server * @throws GengoException */ public JSONObject determineTranslationCost(Payloads jobs) throws GengoException { try { String url = getBaseUrl() + "translate/service/quote/"; JSONObject data = new JSONObject(); data.put("jobs", jobs.toJSONArray()); return call(url, HttpMethod.POST, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Get translation jobs which were previously submitted together by their order id. * * @param orderId * @return the response from the server * @throws GengoException */ public JSONObject getOrderJobs(int orderId) throws GengoException { String url = getBaseUrl() + "translate/order/"; url += orderId; return call(url, HttpMethod.GET); } /** * Delete translation job. * @param orderId * @return * @throws GengoException */ public JSONObject deleteTranslationOrder(int orderId) throws GengoException { String url = getBaseUrl() + "translate/order/"; url += orderId; return call(url, HttpMethod.DELETE); } /** * Get entire comments for the specific order. * @param orderId * @return * @throws GengoException */ public JSONObject getOrderComments(int orderId) throws GengoException { String url = getBaseUrl() + "translate/order/"; url += orderId; url += "/comments"; return call(url, HttpMethod.GET); } /** * Register comment for the specific order. * @param orderId * @param comment * @return * @throws GengoException */ public JSONObject postOrderComment(int orderId, String comment) throws GengoException { try { String url = getBaseUrl() + "translate/order/"; url += orderId; url += "/comment"; JSONObject data = new JSONObject(); data.put("body", comment); return call(url, HttpMethod.POST, data); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Get glossary list. * @return * @throws GengoException */ public JSONObject getGlossaryList() throws GengoException { String url = getBaseUrl() + "translate/glossary"; return call(url, HttpMethod.GET); } /** * Get the specific glossary. * @param glossaryId * @return * @throws GengoException */ public JSONObject getGlossary(int glossaryId) throws GengoException { String url = getBaseUrl() + "translate/glossary/"; url += glossaryId; return call(url, HttpMethod.GET); } /** * Get a quote for file jobs. * @param jobs Translation job objects to be quoted * @param filePaths map of file keys to filesystem paths * @return the response from the server * @throws GengoException */ public JSONObject determineTranslationCostFiles(List<FileJob> jobs, Map<String, String> filePaths) throws GengoException { try { JSONObject theJobs = new JSONObject(); if (jobs.size() != filePaths.size()) { throw new GengoException("Deference of length between 'jobs' and 'filePaths' found."); } if (jobs.size() > 50 || filePaths.size() > 50) { throw new GengoException("Requested collection's size is overflowed.(maximum is 50)"); } for (int i = 0; i < jobs.size(); i++) { theJobs.put(String.format("job_%s", i), jobs.get(i).toJSONObject()); } //API Reference is back to date. 'translate/service/quote/file' is deprecated. String url = getBaseUrl() + "translate/service/quote"; JSONObject data = new JSONObject(); data.put("jobs", theJobs); return httpPostFileUpload(url, data, filePaths); } catch (JSONException e) { throw new GengoException(e.getMessage(), e); } } /** * Utility function. */ private String join(Iterable<? extends Object> pColl, String separator) { Iterator<? extends Object> oIter; if (pColl == null || (!(oIter = pColl.iterator()).hasNext())) { return ""; } StringBuffer oBuilder = new StringBuffer(String.valueOf(oIter.next())); while (oIter.hasNext()) { oBuilder.append(separator).append(oIter.next()); } return oBuilder.toString(); } }
package main.java.com.graphics.shapes; import main.java.com.graphics.shapes.utils.GraphicsObject; import main.java.com.graphics.shapes.utils.Point; /** * * @author Richard Coan */ public class Triangle extends GraphicsObject { public Triangle(Point p1, Point p2, Point p3) { points.addAll(new Line(p1, p2).getPoints()); points.addAll(new Line(p2, p3).getPoints()); points.addAll(new Line(p1, p3).getPoints()); } }
package com.iobeam.api.client; import com.iobeam.api.ApiException; import com.iobeam.api.RestException; import com.iobeam.api.auth.AuthHandler; import com.iobeam.api.auth.DefaultAuthHandler; import com.iobeam.api.resource.DataPoint; import com.iobeam.api.resource.DataStore; import com.iobeam.api.resource.Device; import com.iobeam.api.resource.Import; import com.iobeam.api.resource.ImportBatch; import com.iobeam.api.service.DeviceService; import com.iobeam.api.service.ImportService; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.logging.Logger; /** * The Iobeam client. Handles device registration and importing/sending of data to iobeam. */ public class Iobeam { private static final Logger logger = Logger.getLogger(Iobeam.class.getName()); public static final String DEFAULT_API_URL = "https://api.iobeam.com"; @Deprecated public static final String API_URL = DEFAULT_API_URL; static final String DEVICE_FILENAME = "iobeam-device-id"; /** * Exception when actions involving the network (registration, sending data) are called before * initializing the client. */ public static class NotInitializedException extends ApiException { public NotInitializedException() { super("iobeam client not initialized."); } } /** * Exception for when the device ID could not successfully be saved to disk. */ public static class CouldNotPersistException extends ApiException { public CouldNotPersistException() { super("iobeam client could not save device id"); } } /** * SendCallback used when autoRetry is set. */ private static final class ReinsertSendCallback extends SendCallback { private final Iobeam client; public ReinsertSendCallback(Iobeam iobeam) { this.client = iobeam; } @Override public void onSuccess(ImportBatch data) { } @Override public void onFailure(Throwable exc, ImportBatch data) { client.addBulkData(data); } } private static final class IgnoreDupeRegisterCallback extends RegisterCallback { private final RegisterCallback userCB; private final Iobeam client; public IgnoreDupeRegisterCallback(Iobeam client, RegisterCallback userCB) { this.client = client; this.userCB = userCB; } @Override public void onSuccess(String deviceId) { if (userCB != null) { userCB.onSuccess(deviceId); } } @Override public void onFailure(Throwable exc, RestRequest req) { if (exc instanceof RestException) { if (((RestException) exc).getError() == DeviceService.ERR_DUPLICATE_ID) { Device d = (Device) req.getBuilder().getContent(); this.getInnerCallback(client).completed(d, req); return; } } if (userCB != null) { userCB.getInnerCallback(client).failed(exc, req); } } } public static class Builder { private final long projectId; private final String token; private String savePath; private String backendUrl; private String deviceId; private boolean autoRetry; public Builder(long projectId, String projectToken) { this.projectId = projectId; this.token = projectToken; this.savePath = null; this.backendUrl = DEFAULT_API_URL; this.deviceId = null; this.autoRetry = false; } public Builder saveIdToPath(String path) { this.savePath = path; return this; } public Builder setDeviceId(String id) { this.deviceId = id; return this; } @Deprecated public Builder setBackend(String url) { return this.backend(url); } public Builder backend(String url) { this.backendUrl = url; return this; } public Builder autoRetry() { return this.autoRetry(true); } public Builder autoRetry(boolean retry) { this.autoRetry = retry; return this; } public Iobeam build() { try { Iobeam client = new Iobeam(this.projectId, this.token, this.savePath, this.deviceId, this.backendUrl); client.setAutoRetry(this.autoRetry); return client; } catch (ApiException e) { e.printStackTrace(); return null; } } } String path = null; long projectId = -1; String projectToken = null; String deviceId = null; private RestClient client = null; private final Object dataStoreLock = new Object(); @Deprecated private Import dataStore; private final List<DataStore> dataBatches = new ArrayList<DataStore>(); private Map<String, DataStore> seriesToBatch = new HashMap<String, DataStore>(); private boolean autoRetry = false; private Iobeam(long projectId, String projectToken, String path, String deviceId, String url) throws ApiException { init(path, projectId, projectToken, deviceId, url); } /** * (Re-)initializes the iobeam client. * * @param path Directory where the device ID file, iobeam-device-id, should be written. * If null, the device ID is <b>not</b> persisted. * @param projectId The numeric project ID to associate with. * @param projectToken The token to use when communicating with iobeam cloud. * @param deviceId The device ID that should be used by the iobeam client. * @param backendUrl The base URL of API services to talk to * @throws ApiException Thrown if something goes wrong with initializing the device ID. */ void init(String path, long projectId, String projectToken, String deviceId, String backendUrl) throws ApiException { this.path = path; this.projectId = projectId; this.projectToken = projectToken; if (deviceId == null && path != null) { deviceId = localDeviceIdCheck(); } setDeviceId(deviceId); client = new RestClient(backendUrl, Executors.newSingleThreadExecutor()); File dir = path != null ? new File(path) : null; AuthHandler handler = new DefaultAuthHandler(client, projectId, projectToken, dir); client.setAuthenticationHandler(handler); } /** * Tells whether the iobeam client has been initialized. * * @return True if initialized; otherwise, false. */ public boolean isInitialized() { return projectId > 0 && projectToken != null && client != null; } /** * Resets the iobeam client to an uninitialized state including clearing all added data. */ void reset() { reset(true); } /** * Resets the iobeam client to uninitialized state, including removing any added data. * * @param deleteFile Whether or not to delete the on-disk device ID. Tests use false sometimes. */ void reset(boolean deleteFile) { String path = this.path; this.path = null; this.projectId = -1; this.projectToken = null; this.deviceId = null; this.client = null; synchronized (dataStoreLock) { dataStore = null; dataBatches.clear(); } if (deleteFile) { File f = new File(path, DEVICE_FILENAME); if (f.exists()) { f.delete(); } } } public boolean getAutoRetry() { return this.autoRetry; } /** * Sets whether this Iobeam object automatically tries to resend data that fails. * * @param retry Whether to retry or not. */ public void setAutoRetry(boolean retry) { this.autoRetry = retry; } private void persistDeviceId() throws CouldNotPersistException { File f = new File(this.path, DEVICE_FILENAME); try { FileWriter fw = new FileWriter(f); fw.write(this.deviceId); fw.close(); } catch (IOException e) { e.printStackTrace(); throw new CouldNotPersistException(); } } private String localDeviceIdCheck() { File f = new File(this.path, DEVICE_FILENAME); try { if (f.exists()) { BufferedReader br = new BufferedReader(new FileReader(f)); String line = br.readLine(); br.close(); return line; } } catch (Exception e) { e.printStackTrace(); } return null; } private DeviceService.Add prepareDeviceRequest(Device device) throws NotInitializedException { if (!isInitialized()) { throw new NotInitializedException(); } DeviceService service = new DeviceService(client); final Device d; if (device != null) { // Copy to make sure project id is set right. d = new Device.Builder(projectId) .id(device.getId()) .name(device.getName()) .type(device.getType()) .created(device.getCreated()) .build(); } else { d = new Device.Builder(projectId).build(); } return service.add(d); } /** * Registers a device and assigns it a random device ID and name. This call is <b>BLOCKING</b> * and should not be called on UI threads. * * See {@link #registerDevice(Device)} for more details. * * @return The new device id for this device. * @throws ApiException Thrown if the iobeam client is not initialized or there are problems * writing the device ID. * @throws IOException Thrown if network errors occur while trying to register. */ public String registerDevice() throws ApiException, IOException { return registerDevice((Device) null); } /** * Registers a device with the provided device ID. This call is <b>BLOCKING</b> and should not * be called on UI threads. * * See {@link #registerDevice(Device)} for more details. * * @param deviceId The desired id for this device. * @return The device id provided * @throws ApiException Thrown if the iobeam client is not initialized or there are problems * writing the device ID. * @throws IOException Thrown if network errors occur while trying to register. * @deprecated Use {@link #registerDevice(String)} instead. Will be removed after 0.6.x */ @Deprecated public String registerDeviceWithId(String deviceId) throws ApiException, IOException { return registerDevice(deviceId); } /** * Registers a device with the provided device ID. This call is <b>BLOCKING</b> and should not * be called on UI threads. * * See {@link #registerDevice(Device)} for more details. * * @param deviceId The desired id for this device; if null, a random one is assigned. * @return The new device id for this device. * @throws ApiException Thrown if the iobeam client is not initialized or there are problems * writing the device ID. * @throws IOException Thrown if network errors occur while trying to register. */ public String registerDevice(String deviceId) throws ApiException, IOException { return registerDevice(new Device.Builder(projectId).id(deviceId).build()); } /** * Registers a device with the provided device ID or sets it if already registered. This call is * <b>BLOCKING</b> and should not be called on UI threads. * * See {@link #registerDevice(Device)} for more details. * * @param deviceId The desired id for this device. * @return The device id provided * @throws ApiException Thrown if the iobeam client is not initialized or there are problems * writing the device ID. * @throws IOException Thrown if network errors occur while trying to register. */ public String registerOrSetDevice(final String deviceId) throws ApiException, IOException { return registerOrSetDevice(new Device.Builder(projectId).id(deviceId).build()); } /** * Registers a device with the provided device ID or sets it if already registered. This call is * <b>BLOCKING</b> and should not be called on UI threads. * * See {@link #registerDevice(Device)} for more details. * * @param device The desired id for this device. * @return The device id provided by the device * @throws ApiException Thrown if the iobeam client is not initialized or there are problems * writing the device ID. * @throws IOException Thrown if network errors occur while trying to register. */ public String registerOrSetDevice(final Device device) throws ApiException, IOException { try { return registerDevice(device); } catch (RestException e) { if (e.getError() == DeviceService.ERR_DUPLICATE_ID) { setDevice(device); return device.getId(); } throw e; } } /** * Registers a device with the provided device ID and device name. This call is <b>BLOCKING</b> * and should not be called on UI threads. * * See {@link #registerDevice(Device)} for more details. * * @param deviceId The desired id for this device; if null, a random one is assigned. * @param deviceName The desired name for this device; if null, a random one is assigned. * @return The new device id for this device. * @throws ApiException Thrown if the iobeam client is not initialized or there are problems * writing the device ID. * @throws IOException Thrown if network errors occur while trying to register. * @deprecated Use {@link #registerDevice(Device)} instead. Will be removed after 0.6.x */ @Deprecated public String registerDeviceWithId(String deviceId, String deviceName) throws ApiException, IOException { final Device d = new Device.Builder(projectId).id(deviceId).name(deviceName).build(); return registerDevice(d); } /** * Registers a device with the same parameters as the provided {@link Device}. This call is * <b>BLOCKING</b> and should not be called on UI threads. It will make a network call and not * return until it finishes. If device is null, a new {@link Device} with a random ID and name * will be generated and its ID returned. If the client already has a device ID set, a null * device parameter will return the current ID. * * @param device A {@link Device} to be registered with iobeam. If ID is not set, a random one * will be assigned. Its name will also be randomly generated if unassigned, or * set to the ID if ID is provided but not name. * @return The device ID associated with this client. * @throws ApiException Thrown if the iobeam client is not initialized or there are problems * writing the device ID. * @throws IOException Thrown if network errors occur while trying to register. */ public String registerDevice(Device device) throws ApiException, IOException { boolean alreadySet = this.deviceId != null; // If device ID is set and not explicitly asking for a different one, return current ID. if (alreadySet && (device == null || this.deviceId.equals(device.getId()))) { setDeviceId(this.deviceId); return this.deviceId; } // Make sure to unset before attempting, so as not to reuse old ID if it fails. this.deviceId = null; DeviceService.Add req = prepareDeviceRequest(device); String id = req.execute().getId(); setDeviceId(id); return this.deviceId; } /** * Registers a device asynchronously with a randomly assigned ID. * * See {@link #registerDeviceAsync(Device, RegisterCallback)} for more details. * * @throws ApiException Thrown if the iobeam client is not initialized. */ public void registerDeviceAsync() throws ApiException { registerDeviceAsync((Device) null, null); } /** * Registers a device asynchronously with a randomly assigned ID. * * See {@link #registerDeviceAsync(Device, RegisterCallback)} for more details. * * @param callback Callback for result of the registration. * @throws ApiException Thrown if the iobeam client is not initialized. */ public void registerDeviceAsync(RegisterCallback callback) throws ApiException { registerDeviceAsync((Device) null, callback); } /** * Registers a device asynchronously with the provided device ID. * * See {@link #registerDeviceAsync(Device, RegisterCallback)} for more details. * * @param deviceId Desired device ID. * @throws ApiException Thrown if the iobeam client is not initialized. * @deprecated Use {@link #registerDeviceAsync(String)} instead. */ @Deprecated public void registerDeviceWithIdAsync(String deviceId) throws ApiException { registerDeviceAsync(deviceId, null); } /** * Registers a device asynchronously with the provided device ID. * * See {@link #registerDeviceAsync(Device, RegisterCallback)} for more details. * * @param deviceId Desired device ID. * @throws ApiException Thrown if the iobeam client is not initialized. */ public void registerDeviceAsync(String deviceId) throws ApiException { registerDeviceAsync(deviceId, null); } /** * Registers a device asynchronously with the provided device ID and name. * * See {@link #registerDeviceAsync(Device, RegisterCallback)} for more details. * * @param deviceId Desired device ID. * @throws ApiException Thrown if the iobeam client is not initialized. * @deprecated Use {@link #registerDeviceAsync(Device)} instead. Will be removed after 0.6.x */ @Deprecated public void registerDeviceWithIdAsync(String deviceId, String deviceName) throws ApiException { final Device d = new Device.Builder(projectId).id(deviceId).name(deviceName).build(); registerDeviceAsync(d, null); } /** * Registers a device asynchronously with the provided device ID. * * See {@link #registerDeviceAsync(Device, RegisterCallback)} for more details. * * @param deviceId Desired device ID. * @param callback Callback for result of the registration. * @throws ApiException Thrown if the iobeam client is not initialized. * @deprecated Use {@link #registerDeviceAsync(String, RegisterCallback)} instead. */ @Deprecated public void registerDeviceWithIdAsync(String deviceId, RegisterCallback callback) throws ApiException { registerDeviceAsync(deviceId, callback); } /** * Registers a device asynchronously with the provided device ID. * * See {@link #registerDeviceAsync(Device, RegisterCallback)} for more details. * * @param deviceId Desired device ID. * @param callback Callback for result of the registration. * @throws ApiException Thrown if the iobeam client is not initialized. */ public void registerDeviceAsync(String deviceId, RegisterCallback callback) throws ApiException { final Device d = new Device.Builder(projectId).id(deviceId).build(); registerDeviceAsync(d, callback); } /** * Registers a device asynchronously with the provided device ID and name. * * See {@link #registerDeviceAsync(Device, RegisterCallback)} for more details. * * @param deviceId Desired device ID. * @param callback Callback for result of the registration. * @param deviceName Desired device name. * @throws ApiException Thrown if the iobeam client is not initialized. * @deprecated Use {@link #registerDeviceAsync(Device, RegisterCallback)} instead. Will be * removed after 0.6.x */ @Deprecated public void registerDeviceWithIdAsync(String deviceId, String deviceName, RegisterCallback callback) throws ApiException { final Device d = new Device.Builder(projectId).id(deviceId).name(deviceName).build(); registerDeviceAsync(d, callback); } /** * Registers a device asynchronously with parameters of the provided {@link Device}. * * See {@link #registerDeviceAsync(Device, RegisterCallback)} for more details. * * @param device Desired device parameters to register. * @throws ApiException Thrown if the iobeam client is not initialized. */ public void registerDeviceAsync(Device device) throws ApiException { registerDeviceAsync(device, null); } public void registerOrSetDeviceAsync(final Device device) throws ApiException { registerDeviceAsync(device, new IgnoreDupeRegisterCallback(this, null)); } public void registerOrSetDeviceAsync(final Device device, RegisterCallback callback) throws ApiException { registerDeviceAsync(device, new IgnoreDupeRegisterCallback(this, callback)); } public void registerOrSetDeviceAsync(final String id) throws ApiException { registerOrSetDeviceAsync(new Device.Builder(projectId).id(id).build()); } public void registerOrSetDeviceAsync(final String id, RegisterCallback callback) throws ApiException { registerOrSetDeviceAsync(new Device.Builder(projectId).id(id).build(), callback); } /** * Registers a device asynchronously with parameters of the provided {@link Device}. This will * not block the calling thread. If successful, the device ID of this client will be set (either * to the id provided, or if not provided, a randomly generated one). Any provided callback will * be run on a background thread. If the client already has a device ID set, registration will * only happen for a non-null device. Otherwise, the callback will be called with a {@link * Device} with the current ID. * * @param device Desired device parameters to register. * @param callback Callback for result of the registration. * @throws ApiException Thrown if the iobeam client is not initialized. */ public void registerDeviceAsync(Device device, RegisterCallback callback) throws ApiException { RestCallback<Device> cb; if (callback == null) { cb = RegisterCallback.getEmptyCallback().getInnerCallback(this); } else { cb = callback.getInnerCallback(this); } // If device ID is set and not explicitly asking for a different one, return current ID. boolean alreadySet = this.deviceId != null; if (alreadySet && (device == null || this.deviceId.equals(device.getId()))) { cb.completed(device, null); return; } // Make sure to unset before attempting, so as not to reuse old ID if it fails. this.deviceId = null; DeviceService.Add req = prepareDeviceRequest(device); req.executeAsync(cb); } /** * Gets the current device id. * * @return The current device id. */ public String getDeviceId() { return this.deviceId; } /** * Sets the current device id that the iobeam client is associated with. * * @param deviceId Device id to be associated with the iobeam client. * @throws CouldNotPersistException Thrown if there are problems saving the device id to disk. */ public void setDeviceId(String deviceId) throws CouldNotPersistException { this.deviceId = deviceId; if (deviceId != null && path != null) { persistDeviceId(); } } public void setDevice(Device device) throws CouldNotPersistException { setDeviceId(device.getId()); } @Deprecated Import getDataStore() { return dataStore; } /* A lock should always be acquired before calling this method! */ private void _addDataWithoutLock(String seriesName, DataPoint dataPoint) { if (dataStore == null) { dataStore = new Import(deviceId, projectId); } dataStore.addDataPoint(seriesName, dataPoint); DataStore store = seriesToBatch.get(seriesName); if (store == null) { store = new DataStore(seriesName); seriesToBatch.put(seriesName, store); dataBatches.add(store); } store.add(dataPoint.getTime(), seriesName, dataPoint.getValue()); } /** * Adds a data value to a particular series in the data store. * * @param seriesName The name of the series that the data belongs to. * @param dataPoint The DataPoint representing a data value at a particular time. * @deprecated Use DataStore and `trackDataStore()` instead. */ @Deprecated public void addData(String seriesName, DataPoint dataPoint) { synchronized (dataStoreLock) { _addDataWithoutLock(seriesName, dataPoint); } } /** * Adds a list of data points to a list of series in the data store. This is essentially a 'zip' * operation on the points and series names, where the first point is put in the first series, * the second point in the second series, etc. Both lists MUST be the same size. * * @param points List of DataPoints to be added * @param seriesNames List of corresponding series for the datapoints. * @return True if the points are added; false if the lists are not the same size, or adding * fails. * @deprecated Use {@link DataStore} and {@link #createDataStore(Collection)} instead. */ @Deprecated public boolean addDataMapToSeries(String[] seriesNames, DataPoint[] points) { if (seriesNames == null || points == null || points.length != seriesNames.length) { return false; } synchronized (dataStoreLock) { for (int i = 0; i < seriesNames.length; i++) { _addDataWithoutLock(seriesNames[i], points[i]); } } return true; } private void addBulkData(ImportBatch data) { if (data == null) { return; } if (data.isFromLegacy()) { synchronized (dataStoreLock) { if (dataStore == null) { dataStore = new Import(deviceId, projectId); } String key = data.getData().getColumns().get(0); DataStore db = seriesToBatch.get(key); db.merge(data.getData()); } } else { for (DataStore db : dataBatches) { if (db.hasSameColumns(data.getData())) { db.merge(data.getData()); } } } } /** * Creates a DataStore with a given set of columns, and tracks it so that any data added will be * sent on a subsequent send calls. * * @param columns Columns in the DataStore * @return DataStore for storing data for a given set of columns. */ public DataStore createDataStore(Collection<String> columns) { DataStore b = new DataStore(columns); trackDataStore(b); return b; } /** * Creates a DataStore with a given set of columns, and tracks it so that any data added will be * sent on a subsequent send calls. * * @param columns Columns in the DataStore * @return DataStore for storing data for a given set of columns. */ public DataStore createDataStore(String... columns) { return createDataStore(Arrays.asList(columns)); } /** * Track a DataStore so that any data stored in it will be sent on subsequent send calls. * * @param batch Data stored in a batch/table format. * @deprecated Use {@link #trackDataStore(DataStore)} instead. */ @Deprecated public void trackDataBatch(DataStore batch) { trackDataStore(batch); } /** * Track a DataStore so that any data stored in it will be sent on subsequent send calls. * * @param store DataStore to be tracked by this client. */ public void trackDataStore(DataStore store) { synchronized (dataStoreLock) { dataBatches.add(store); } } /** * Returns the size of all of the data in all the series. * * @return Size of the data store, or 0 if it has not been made yet. */ public long getDataSize() { long size = 0; synchronized (dataStoreLock) { for (DataStore b : dataBatches) { size += b.getDataSize(); } } return size; } /** * Returns the size of the data set in a particular series. * * @param series The series to query * @return Size of the data set, or 0 if series does not exist. * @deprecated Use batch methods instead. */ @Deprecated public int getDataSize(String series) { return getSeriesSize(series); } /** * Returns the size of the data set in a particular series. * * @param series The series to query * @return Size of the data set, or 0 if series does not exist. */ private int getSeriesSize(String series) { synchronized (dataStoreLock) { if (dataStore == null) { return 0; } if (seriesToBatch.containsKey(series)) { return (int) seriesToBatch.get(series).getDataSize(); } else { return 0; } } } List<ImportService.Submit> prepareDataRequests() throws ApiException { if (!isInitialized()) { throw new NotInitializedException(); } if (deviceId == null) { throw new ApiException("Device id not set, cannot send data."); } // Synchronize so no more data is added to this object while we send. final List<DataStore> stores; synchronized (dataStoreLock) { dataStore = null; if (dataBatches != null) { stores = new ArrayList<DataStore>(dataBatches.size()); for (DataStore b : dataBatches) { if (b.getRows().size() > 0) { stores.add(DataStore.snapshot(b)); b.reset(); } } } else { stores = Collections.<DataStore>emptyList(); } } // No data to send, log a warning and return an empty list. if (stores.size() == 0) { logger.warning("No data to send."); return new ArrayList<ImportService.Submit>(); } List<ImportBatch> impBatches = new ArrayList<ImportBatch>(); for (final DataStore store : stores) { boolean legacy = store.getColumns().size() == 1 && seriesToBatch.containsKey(store.getColumns().get(0)); if (legacy) { impBatches.add(ImportBatch.createLegacy(projectId, deviceId, store)); } else { impBatches.add(new ImportBatch(projectId, deviceId, store)); } } ImportService service = new ImportService(client); return service.submit(impBatches); } /** * Sends the stored data to the iobeam cloud. This call is <b>BLOCKING</b>, which means the * caller thread will not return until the network call is complete. Do not call on UI threads. * This call will take a snapshot of the data store at this moment and send it; future data adds * will be to a NEW data store. * * If `autoRetry` is set, failed requests will add the previous data to the new data store. * * @throws ApiException Thrown is the client is not initialized or if the device id has not been * set. * @throws IOException Thrown if there are network issues connecting to iobeam cloud. */ public void send() throws ApiException, IOException { List<ImportService.Submit> reqs = prepareDataRequests(); for (ImportService.Submit req : reqs) { try { req.execute(); } catch (Exception e) { if (autoRetry) { ReinsertSendCallback cb = new ReinsertSendCallback(this); cb.innerCallback.failed(e, req); } // TODO: When we target Java7, we can just do a multi-exception catch if (e instanceof ApiException) { throw (ApiException) e; } else if (e instanceof IOException) { throw (IOException) e; } } } } /** * Asynchronous version of send() that will not block the calling thread. No callback provided, * same as calling sendAsync(null). * * If `autoRetry` is set, failed requests will add the previous data to the new data store. * * @throws ApiException Thrown is the client is not initialized or if the device id has not been * set. */ public void sendAsync() throws ApiException { sendAsync(null); } /** * Asynchronous version of send() that will not block the calling thread. Any provided callback * will be run on the background thread when the operation completes. * * If `autoRetry` is set, failed requests will add the previous data to the new data store. * * @param callback Callback for when the operation completes. * @throws ApiException Thrown is the client is not initialized or if the device id has not been * set. */ public void sendAsync(SendCallback callback) throws ApiException { List<ImportService.Submit> reqs = prepareDataRequests(); for (ImportService.Submit req : reqs) { if (callback == null && !autoRetry) { req.executeAsync(); } else if (callback == null) { req.executeAsync(new ReinsertSendCallback(this).innerCallback); } else { req.executeAsync(callback.innerCallback); } } } }
package com.joelhockey.jacknji11; import java.math.BigInteger; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sun.jna.Memory; import com.sun.jna.NativeLong; import com.sun.jna.Pointer; import com.sun.jna.ptr.ByteByReference; import com.sun.jna.ptr.NativeLongByReference; /** * CKA_? constants and wrapper for CK_ATTRIBUTE struct. * @author Joel Hockey (joel.hockey@gmail.com) */ public class CKA { private static final Log log = LogFactory.getLog(CKA.class); public static final int CKF_ARRAY_ATTRIBUTE = 0x40000000; public static final int CLASS = 0x00000000; public static final int TOKEN = 0x00000001; public static final int PRIVATE = 0x00000002; public static final int LABEL = 0x00000003; public static final int APPLICATION = 0x00000010; public static final int VALUE = 0x00000011; public static final int OBJECT_ID = 0x00000012; public static final int CERTIFICATE_TYPE = 0x00000080; public static final int ISSUER = 0x00000081; public static final int SERIAL_NUMBER = 0x00000082; public static final int AC_ISSUER = 0x00000083; public static final int OWNER = 0x00000084; public static final int ATTR_TYPES = 0x00000085; public static final int TRUSTED = 0x00000086; public static final int CERTIFICATE_CATEGORY = 0x00000087; public static final int JAVA_MIDP_SECURITY_DOMAIN = 0x00000088; public static final int URL = 0x00000089; public static final int HASH_OF_SUBJECT_PUBLIC_KEY = 0x0000008a; public static final int HASH_OF_ISSUER_PUBLIC_KEY = 0x0000008b; public static final int CHECK_VALUE = 0x00000090; public static final int KEY_TYPE = 0x00000100; public static final int SUBJECT = 0x00000101; public static final int ID = 0x00000102; public static final int SENSITIVE = 0x00000103; public static final int ENCRYPT = 0x00000104; public static final int DECRYPT = 0x00000105; public static final int WRAP = 0x00000106; public static final int UNWRAP = 0x00000107; public static final int SIGN = 0x00000108; public static final int SIGN_RECOVER = 0x00000109; public static final int VERIFY = 0x0000010a; public static final int VERIFY_RECOVER = 0x0000010b; public static final int DERIVE = 0x0000010c; public static final int START_DATE = 0x00000110; public static final int END_DATE = 0x00000111; public static final int MODULUS = 0x00000120; public static final int MODULUS_BITS = 0x00000121; public static final int PUBLIC_EXPONENT = 0x00000122; public static final int PRIVATE_EXPONENT = 0x00000123; public static final int PRIME_1 = 0x00000124; public static final int PRIME_2 = 0x00000125; public static final int EXPONENT_1 = 0x00000126; public static final int EXPONENT_2 = 0x00000127; public static final int COEFFICIENT = 0x00000128; public static final int PRIME = 0x00000130; public static final int SUBPRIME = 0x00000131; public static final int BASE = 0x00000132; public static final int PRIME_BITS = 0x00000133; public static final int SUBPRIME_BITS = 0x00000134; public static final int VALUE_BITS = 0x00000160; public static final int VALUE_LEN = 0x00000161; public static final int EXTRACTABLE = 0x00000162; public static final int LOCAL = 0x00000163; public static final int NEVER_EXTRACTABLE = 0x00000164; public static final int ALWAYS_SENSITIVE = 0x00000165; public static final int MODIFIABLE = 0x00000170; public static final int EC_PARAMS = 0x00000180; public static final int EC_POINT = 0x00000181; public static final int SECONDARY_AUTH = 0x00000200; public static final int AUTH_PIN_FLAGS = 0x00000201; public static final int ALWAYS_AUTHENTICATE = 0x00000202; public static final int WRAP_WITH_TRUSTED = 0x00000210; public static final int WRAP_TEMPLATE = (CKF_ARRAY_ATTRIBUTE|0x00000211); public static final int UNWRAP_TEMPLATE = (CKF_ARRAY_ATTRIBUTE|0x00000212); public static final int OTP_FORMAT = 0x00000220; public static final int OTP_LENGTH = 0x00000221; public static final int OTP_TIME_INTERVAL = 0x00000222; public static final int OTP_USER_FRIENDLY_MODE = 0x00000223; public static final int OTP_CHALLENGE_REQUIREMENT = 0x00000224; public static final int OTP_TIME_REQUIREMENT = 0x00000225; public static final int OTP_COUNTER_REQUIREMENT = 0x00000226; public static final int OTP_PIN_REQUIREMENT = 0x00000227; public static final int OTP_COUNTER = 0x0000022e; public static final int OTP_TIME = 0x0000022f; public static final int OTP_USER_IDENTIFIER = 0x0000022a; public static final int OTP_SERVICE_IDENTIFIER = 0x0000022b; public static final int OTP_SERVICE_LOGO = 0x0000022c; public static final int OTP_SERVICE_LOGO_TYPE = 0x0000022d; public static final int HW_FEATURE_TYPE = 0x00000300; public static final int RESET_ON_INIT = 0x00000301; public static final int HAS_RESET = 0x00000302; public static final int PIXEL_X = 0x00000400; public static final int PIXEL_Y = 0x00000401; public static final int RESOLUTION = 0x00000402; public static final int CHAR_ROWS = 0x00000403; public static final int CHAR_COLUMNS = 0x00000404; public static final int COLOR = 0x00000405; public static final int BITS_PER_PIXEL = 0x00000406; public static final int CHAR_SETS = 0x00000480; public static final int ENCODING_METHODS = 0x00000481; public static final int MIME_TYPES = 0x00000482; public static final int MECHANISM_TYPE = 0x00000500; public static final int REQUIRED_CMS_ATTRIBUTES = 0x00000501; public static final int DEFAULT_CMS_ATTRIBUTES = 0x00000502; public static final int SUPPORTED_CMS_ATTRIBUTES = 0x00000503; public static final int ALLOWED_MECHANISMS = (CKF_ARRAY_ATTRIBUTE|0x00000600); // Vendor defined values // Eracom PTK public static final int VENDOR_PTK_USAGE_COUNT = 0x80000101; public static final int VENDOR_PTK_TIME_STAMP = 0x80000102; public static final int VENDOR_PTK_CHECK_VALUE = 0x80000103; public static final int VENDOR_PTK_MECHANISM_LIST = 0x80000104; public static final int VENDOR_PTK_SIGN_LOCAL_CERT = 0x80000127; public static final int VENDOR_PTK_EXPORT = 0x80000128; public static final int VENDOR_PTK_EXPORTABLE = 0x80000129; public static final int VENDOR_PTK_DELETABLE = 0x8000012a; public static final int VENDOR_PTK_IMPORT = 0x8000012b; public static final int VENDOR_PTK_KEY_SIZE = 0x8000012c; public static final int VENDOR_PTK_ISSUER_STR = 0x80000130; public static final int VENDOR_PTK_SUBJECT_STR = 0x80000131; public static final int VENDOR_PTK_SERIAL_NUMBER_INT = 0x80000132; public static final int VENDOR_PTK_RECORD_COUNT = 0x80000136; public static final int VENDOR_PTK_RECORD_NUMBER = 0x80000137; public static final int VENDOR_PTK_PURGE = 0x80000139; public static final int VENDOR_PTK_EVENT_LOG_FULL = 0x8000013a; public static final int VENDOR_PTK_SECURITY_MODE = 0x80000140; public static final int VENDOR_PTK_TRANSPORT_MODE = 0x80000141; public static final int VENDOR_PTK_BATCH = 0x80000142; public static final int VENDOR_PTK_HW_STATUS = 0x80000143; public static final int VENDOR_PTK_FREE_MEM = 0x80000144; public static final int VENDOR_PTK_TAMPER_CMD = 0x80000145; public static final int VENDOR_PTK_DATE_OF_MANUFACTURE = 0x80000146; public static final int VENDOR_PTK_HALT_CMD = 0x80000147; public static final int VENDOR_PTK_APPLICATION_COUNT = 0x80000148; public static final int VENDOR_PTK_FW_VERSION = 0x80000149; public static final int VENDOR_PTK_RESCAN_PERIPHERALS_CMD = 0x8000014a; public static final int VENDOR_PTK_RTC_AAC_ENABLED = 0x8000014b; public static final int VENDOR_PTK_RTC_AAC_GUARD_SECONDS = 0x8000014c; public static final int VENDOR_PTK_RTC_AAC_GUARD_COUNT = 0x8000014d; public static final int VENDOR_PTK_RTC_AAC_GUARD_DURATION = 0x8000014e; public static final int VENDOR_PTK_HW_EXT_INFO_STR = 0x8000014f; public static final int VENDOR_PTK_SLOT_ID = 0x80000151; public static final int VENDOR_PTK_MAX_SESSIONS = 0x80000155; public static final int VENDOR_PTK_MIN_PIN_LEN = 0x80000156; public static final int VENDOR_PTK_MAX_PIN_FAIL = 0x80000158; public static final int VENDOR_PTK_FLAGS = 0x80000159; public static final int VENDOR_PTK_VERIFY_OS = 0x80000170; public static final int VENDOR_PTK_VERSION = 0x80000181; public static final int VENDOR_PTK_MANUFACTURER = 0x80000182; public static final int VENDOR_PTK_BUILD_DATE = 0x80000183; public static final int VENDOR_PTK_FINGERPRINT = 0x80000184; public static final int VENDOR_PTK_ROM_SPACE = 0x80000185; public static final int VENDOR_PTK_RAM_SPACE = 0x80000186; public static final int VENDOR_PTK_FM_STATUS = 0x80000187; public static final int VENDOR_PTK_DELETE_FM = 0x80000188; public static final int VENDOR_PTK_FM_STARTUP_STATUS = 0x80000189; public static final int VENDOR_PTK_CERTIFICATE_START_TIME = 0x80000190; public static final int VENDOR_PTK_CERTIFICATE_END_TIME = 0x80000191; public static final int VENDOR_PTK_PKI_ATTRIBUTE_BER_ENCODED = 0x80000230; public static final int VENDOR_PTK_HIFACE_MASTER = 0x80000250; public static final int VENDOR_PTK_CKA_SEED = 0x80000260; public static final int VENDOR_PTK_CKA_COUNTER = 0x80000261; public static final int VENDOR_PTK_CKA_H_VALUE = 0x80000262; public static final int VENDOR_PTK_ENUM_ATTRIBUTE = 0x0000ffff; /** Maps from int value to String description (variable name). */ private static final Map<Integer, String> I2S = C.createI2SMap(CKA.class); /** * Convert int constant value to name. * @param cka value * @return name */ public static final String I2S(int cka) { return C.i2s(I2S, CKA.class.getSimpleName(), cka); } public int type; public Pointer pValue; public int ulValueLen; // disallow zero-arg constructor private CKA() { } /** * PKCS#11 CK_ATTRIBUTE struct constructor. * @param type CKA_? type. Use one of the public static final int fields in this class. * @param value supports java types Boolean, byte[], Number (int, long), String */ public CKA(int type, Object value) { this.type = type; if (value == null) { pValue = null; ulValueLen = 0; } else if (value instanceof Boolean) { pValue = new ByteByReference((Boolean) value ? (byte) 1 : (byte) 0).getPointer(); ulValueLen = 1; } else if (value instanceof byte[]) { byte[] v = (byte[]) value; pValue = new Memory(v.length); pValue.write(0, v, 0, v.length); ulValueLen = v.length; } else if (value instanceof BigInteger) { byte[] v = ((BigInteger) value).toByteArray(); pValue = new Memory(v.length); pValue.write(0, v, 0, v.length); ulValueLen = v.length; } else if (value instanceof Number) { pValue = new NativeLongByReference(new NativeLong(((Number) value).longValue())).getPointer(); ulValueLen = NativeLong.SIZE; } else if (value instanceof String) { byte[] v = ((String) value).getBytes(); pValue = new Memory(v.length); pValue.write(0, v, 0, v.length); ulValueLen = v.length; } else { throw new RuntimeException("Unknown att type: " + value.getClass()); } } /** * PKCS#11 CK_ATTRIBUTE struct constructor with null value. * @param type CKA_? type. Use one of the public static final int fields in this class. */ public CKA(int type) { this(type, null); } /** @return value as byte[] */ public byte[] getValue() { return pValue == null ? null : pValue.getByteArray(0, ulValueLen); } /** @return value as String */ public String getValueStr() { return pValue == null ? null : new String(pValue.getByteArray(0, ulValueLen)); } /** @return value as int */ public Integer getValueInt() { if (ulValueLen == 0 || pValue == null) { return null; } if (ulValueLen != NativeLong.SIZE) { throw new IllegalStateException(String.format( "Method getValueInt called when value is not int type of length %d. Got length: %d, CKA type: 0x%08x(%s), value: %s", NativeLong.SIZE, ulValueLen, type, CKA.I2S.get(type), Hex.b2s(getValue()))); } return NativeLong.SIZE == 4 ? pValue.getInt(0) : (int) pValue.getLong(0); } /** @return value as boolean */ public Boolean getValueBool() { if (ulValueLen == 0 || pValue == null) { return null; } if (ulValueLen != 1) { throw new IllegalStateException(String.format( "Method getValueBool called when value is not boolean type of length 1. Got length: %d, CKA type: 0x%08x(%s), value: %s", ulValueLen, type, CKA.I2S.get(type), Hex.b2s(getValue()))); } return pValue.getByte(0) != 0; } /** @return value as BigInteger */ public BigInteger getValueBigInt() { return ulValueLen == 0 || pValue == null ? null : new BigInteger(getValue()); } /** * Dump for debug. * @param sb write to */ public void dump(StringBuilder sb) { sb.append(String.format("type=0x%08x{%s} valueLen=%d", type, I2S(type), ulValueLen)); try { switch (type) { case CLASS: // lookup CKO Integer cko = getValueInt(); sb.append(String.format(" value=0x%08x{%s}", type, cko != null ? CKO.I2S(cko) : "null")); return; case TOKEN: // boolean case PRIVATE: case TRUSTED: case SENSITIVE: case ENCRYPT: case DECRYPT: case WRAP: case UNWRAP: case SIGN: case SIGN_RECOVER: case VERIFY: case VERIFY_RECOVER: case DERIVE: case EXTRACTABLE: case LOCAL: case NEVER_EXTRACTABLE: case ALWAYS_SENSITIVE: case MODIFIABLE: case ALWAYS_AUTHENTICATE: case WRAP_WITH_TRUSTED: case RESET_ON_INIT: case HAS_RESET: case VENDOR_PTK_SIGN_LOCAL_CERT: case VENDOR_PTK_EXPORT: case VENDOR_PTK_EXPORTABLE: case VENDOR_PTK_DELETABLE: case VENDOR_PTK_IMPORT: case VENDOR_PTK_EVENT_LOG_FULL: case VENDOR_PTK_VERIFY_OS: Boolean b = getValueBool(); sb.append(" value=").append(b != null ? b ? "TRUE" : "FALSE" : "null"); return; case LABEL: // escaped printable string case APPLICATION: case URL: case START_DATE: case END_DATE: case VENDOR_PTK_TIME_STAMP: case VENDOR_PTK_ISSUER_STR: case VENDOR_PTK_SUBJECT_STR: case VENDOR_PTK_DATE_OF_MANUFACTURE: case VENDOR_PTK_RTC_AAC_ENABLED: case VENDOR_PTK_HW_EXT_INFO_STR: case VENDOR_PTK_MANUFACTURER: case VENDOR_PTK_BUILD_DATE: case VENDOR_PTK_CERTIFICATE_START_TIME: case VENDOR_PTK_CERTIFICATE_END_TIME: sb.append(" value=").append(Buf.escstr(getValue())); return; case CERTIFICATE_TYPE: // lookup CKC Integer ckc = getValueInt(); sb.append(String.format(" value=0x%08x{%s}", type, ckc != null ? CKC.I2S(ckc) : "null")); return; case KEY_TYPE: // lookup CKK Integer ckk = getValueInt(); sb.append(String.format(" value=0x%08x{%s}", type, ckk != null ? CKK.I2S(ckk) : "null")); return; case MODULUS_BITS: // int case PRIME_BITS: case SUBPRIME_BITS: case VALUE_BITS: case VALUE_LEN: case OTP_LENGTH: case OTP_TIME_INTERVAL: case PIXEL_X: case PIXEL_Y: case RESOLUTION: case CHAR_ROWS: case CHAR_COLUMNS: case BITS_PER_PIXEL: case VENDOR_PTK_USAGE_COUNT: case VENDOR_PTK_KEY_SIZE: case VENDOR_PTK_RECORD_COUNT: case VENDOR_PTK_RECORD_NUMBER: case VENDOR_PTK_FREE_MEM: case VENDOR_PTK_APPLICATION_COUNT: case VENDOR_PTK_RTC_AAC_GUARD_SECONDS: case VENDOR_PTK_RTC_AAC_GUARD_COUNT: case VENDOR_PTK_RTC_AAC_GUARD_DURATION: case VENDOR_PTK_SLOT_ID: case VENDOR_PTK_MAX_SESSIONS: case VENDOR_PTK_MIN_PIN_LEN: case VENDOR_PTK_MAX_PIN_FAIL: case VENDOR_PTK_ROM_SPACE: case VENDOR_PTK_RAM_SPACE: case VENDOR_PTK_CKA_COUNTER: sb.append(" value=").append(getValueInt()); return; default: // no default, fall through to hex dump below } } catch (Exception e) { // unexpected CKA values // log warning log.warn("Unexpected CKA values", e); // hex dump below } // hex dump by default or if error parsing other data type byte[] value = getValue(); Hex.dump(sb, value, 0, ulValueLen, " ", 32, false); } public String toString() { StringBuilder sb = new StringBuilder(); dump(sb); return sb.toString(); } }
package com.messners.ajf.util; /** * This class encapsulates the command line passed to * the main() function of an executable. It processes * the arguments in the same way as Unixes getopt(). * * @author Greg Messner <greg@messners.com> */ public class GetOpt { public static final char NUM_CHR = ' public static final char ARG_XPTD = ':'; public static final int EOF = -1; public static final int ERROR = -2; protected String optarg; protected int optind; protected int charpos; protected char optopt; protected char optsw; protected String optstr; protected char switches[]; protected String msgbuf; /** * No args constructor. */ public GetOpt () { this(null); } /** * Construct a CmdLine object with the specified option switches. * * @param optstr the option string (see Unix getopt(3)) */ public GetOpt (String optstr) { this.optstr = optstr; optind = 0; charpos = 0; optopt = '\0'; optsw = '\0'; optarg = null; msgbuf = null; switches = new char[1]; switches[0] = '-'; } /** * Process cmd line arguments (getopt substitute).<p> * * Notes: This routine is a replacement for the UNIX routine getopt * (which is not universally available). * * @param argv argument vector * @return option found, ERROR if error or EOF if at end */ public int getOpt (String argv[]) { return (getOpt(argv, null)); } /** * Process cmd line arguments (getopt substitute).<p> * * Notes: This routine is a replacement for the UNIX routine getopt * (which is not universally available). * * @param argv argument vector * @param optstr the option string (see Unix getopt(3)) * @return option found, ERROR if error or EOF if at end */ public int getOpt (String argv[], String optstr) { int argc = argv.length; if (optstr == null) { optstr = this.optstr; } optarg = null; /* check if we should start over */ if (optind == 0) { charpos = 0; } /* if past all arguments, done */ if (optind >= argc) { charpos = 0; return (EOF); } /* check if new argument */ if (charpos == 0) { /* check if option & longer than 1 char */ char ch0 = argv[optind].charAt(0); for (int i = 0; i < switches.length; i++) { if (switches[i] == ch0) { charpos = 1; optsw = ch0; break; } } if (charpos == 0) { return (EOF); } } /* get next option & bump ptr */ optopt = argv[optind].charAt(charpos++); /* check for double option chars */ if (optopt == optsw) { charpos = 0; optind++; return (EOF); } /* check for number */ if (Character.isDigit(optopt)) { for (int i = 0; i < optstr.length(); i++) { char c = optstr.charAt(i); if (c == NUM_CHR) { optopt = NUM_CHR; optarg = argv[optind].substring( charpos - 1); charpos = 0; optind++; return ((int)optopt); } } } /* check if at end of string of options */ if (argv[optind].length() == charpos) { charpos = 0; optind++; } /* search for next option */ int optstr_len = optstr.length(); for (int i = 0; i < optstr_len; i++) { char ch = optstr.charAt(i); if (ch == ARG_XPTD) { continue; } if (optopt != ch) { continue; } /* got a matching letter in string */ /* check if no arg expected */ if (i + 1 >= optstr_len || optstr.charAt(i + 1) != ARG_XPTD) { return ((int)optopt); } /* process option argument */ if (optind == argc) { /* at end of list */ msgbuf = "option requires an argument -- " + optopt; return (ERROR); } optarg = argv[optind].substring(charpos); charpos = 0; optind++; return ((int)optopt); } msgbuf = "invalid option -- " + optopt; return (ERROR); } /** * Gets the argument for the last parsed option. */ public String getOptArg () { return (optarg); } /** * Gets the current option index. */ public int getOptIndex () { return (optind); } /** * Checks if an arg is present. * * @param argv args from cmd line. * @param arg arg to look for. * @return true if found, false if not. */ public boolean containsArg (String argv[], char arg) { int argc = argv.length; char opts[] = new char[1];; opts[0] = arg; String optstr = new String(opts); boolean found = false; while (!found) { if (optind >= argc) { break; } int c = getOpt(argv, optstr); if (c == arg) { found = true; } else if (c == EOF) { optind++; } } /* reset for real pass */ optind = 0; return (found); } /** * Checks if an arg is present. * * @param argv args from cmd line. * @param arg arg to look for. * @return A pointer to arg if present, null if not. */ public String getStringArg (String argv[], char arg) { int argc = argv.length; char opts[] = new char[2]; opts[0] = arg; opts[1] = ':'; String optstr = new String(opts); while (true) { if (optind >= argc) break; int c = getOpt(argv, optstr); if (c == arg) { optind = 0; return (optarg); } else if (c == EOF) { optind++; } } optind = 0; /* reset for real pass */ return (null); } /** * Gets the last reported error message. * * @return A pointer to error message */ public String getErrorMsg () { return (msgbuf); } /** * Sets option switches to look for. * * @param switches char array of switch characters. */ public void setSwitches (char switches[]) { this.switches = switches; } /** * Built-in tester */ public static void main (String args[]) { String optstr = args[0]; String argv[] = new String[args.length - 1]; for (int i = 1; i < args.length; i++) { argv[i - 1] = args[i]; } GetOpt opts = new GetOpt(optstr); while (true) { int c = opts.getOpt(argv); if (c == GetOpt.ERROR) { System.err.println(opts.getErrorMsg()); break; } if (c == GetOpt.EOF) { break; } System.err.println("c=" + (char)c + ", optarg=" + opts.getOptArg()); } } }
package com.net2plan.cli; import com.jom.JOMException; import com.net2plan.interfaces.networkDesign.Net2PlanException; import com.net2plan.internal.CommandLineParser; import com.net2plan.internal.Constants.UserInterface; import com.net2plan.internal.ErrorHandling; import com.net2plan.internal.SystemUtils; import com.net2plan.internal.Version; import com.net2plan.internal.plugins.ICLIModule; import com.net2plan.internal.plugins.Plugin; import com.net2plan.internal.plugins.PluginSystem; import com.net2plan.utils.StringUtils; import org.apache.commons.cli.*; import java.io.PrintWriter; import java.io.StringWriter; import java.util.LinkedHashMap; import java.util.Map; /** * Main class for the command-line user interface (CLI). * * @author Pablo Pavon-Marino, Jose-Luis Izquierdo-Zaragoza */ public class CLINet2Plan { private final static int LINE_WIDTH = 80; private final Map<String, Class<? extends ICLIModule>> modes = new LinkedHashMap<String, Class<? extends ICLIModule>>(); private final Options options = new Options(); /** * Default constructor. * * @param args Command-line arguments */ public CLINet2Plan(String args[]) { try { System.out.println("Here 1"); SystemUtils.configureEnvironment(CLINet2Plan.class, UserInterface.CLI); System.out.println("Here 2"); for (Class<? extends Plugin> plugin : PluginSystem.getPlugins(ICLIModule.class)) { try { ICLIModule instance = ((Class<? extends ICLIModule>) plugin).newInstance(); modes.put(instance.getModeName(), instance.getClass()); } catch (NoClassDefFoundError e) { e.printStackTrace(); throw new Net2PlanException("Class " + e.getMessage() + " cannot be found. A dependence for " + plugin.getSimpleName() + " is missing?"); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); throw new RuntimeException(e); } } Option helpOption = new Option("help", true, "Show the complete help information. 'modeName' is optional"); helpOption.setArgName("modeName"); helpOption.setOptionalArg(true); Option modeOption = new Option("mode", true, "Mode: " + StringUtils.join(StringUtils.toArray(modes.keySet()), ", ")); modeOption.setArgName("modeName"); modeOption.setOptionalArg(true); OptionGroup group = new OptionGroup(); group.addOption(modeOption); group.addOption(helpOption); options.addOptionGroup(group); CommandLineParser parser = new CommandLineParser(); CommandLine cli = parser.parse(options, args); if (cli.hasOption("help")) { String mode = cli.getOptionValue("help"); System.out.println(mode == null ? getCompleteHelp() : getModeHelp(mode)); } else if (!cli.hasOption("mode")) { System.out.println(getMainHelp()); } else { String mode = cli.getOptionValue("mode"); if (modes.containsKey(mode)) { ICLIModule modeInstance = modes.get(mode).newInstance(); try { modeInstance.executeFromCommandLine(args); } catch (Net2PlanException | JOMException ex) { if (ErrorHandling.isDebugEnabled()) ErrorHandling.printStackTrace(ex); System.out.println("Execution stopped"); System.out.println(); System.out.println(ex.getMessage()); } catch (ParseException ex) { System.out.println("Bad syntax: " + ex.getMessage()); System.out.println(); System.out.println(getModeHelp(mode)); } catch (Throwable ex) { Throwable ex1 = ErrorHandling.getInternalThrowable(ex); if (ex1 instanceof Net2PlanException || ex1 instanceof JOMException) { if (ErrorHandling.isDebugEnabled()) ErrorHandling.printStackTrace(ex); System.out.println("Execution stopped"); System.out.println(); System.out.println(ex1.getMessage()); } else if (ex1 instanceof ParseException) { System.out.println("Bad syntax: " + ex1.getMessage()); System.out.println(); System.out.println(getModeHelp(mode)); } else { System.out.println("Execution stopped. An unexpected error happened"); System.out.println(); ErrorHandling.printStackTrace(ex1); } } } else { throw new IllegalModeException("Bad mode - " + mode); } } } catch (IllegalModeException e) { System.out.println(e.getMessage()); System.out.println(); System.out.println(getMainHelp()); } catch (ParseException e) { System.out.println("Bad syntax: " + e.getMessage()); System.out.println(); System.out.println(getMainHelp()); } catch (Net2PlanException e) { if (ErrorHandling.isDebugEnabled()) ErrorHandling.printStackTrace(e); System.out.println(e.getMessage()); } catch (Throwable e) { ErrorHandling.printStackTrace(e); } } private String getModeHelp(String mode) { if (!modes.containsKey(mode)) throw new IllegalModeException("Bad mode - " + mode); try { ICLIModule modeInstance = modes.get(mode).newInstance(); Options modeOptions = modeInstance.getCommandLineOptions(); String modeHelp = modeInstance.getCommandLineHelp(); StringWriter sw = new StringWriter(); try (PrintWriter w = new PrintWriter(sw)) { HelpFormatter formatter = new HelpFormatter(); formatter.printWrapped(w, LINE_WIDTH, "Mode: " + mode); formatter.printWrapped(w, LINE_WIDTH, ""); formatter.printWrapped(w, LINE_WIDTH, modeHelp); formatter.printWrapped(w, LINE_WIDTH, ""); formatter.printHelp(w, LINE_WIDTH, "java -jar Net2Plan-cli.jar --mode " + mode, null, modeOptions, 0, 1, null, true); w.flush(); } return (sw.toString()); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } private String getMainHelp() { final StringBuilder help = new StringBuilder(); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); PrintWriter w = new PrintWriter(sw); formatter.printWrapped(w, LINE_WIDTH, "Net2Plan " + new Version().toString() + " Command-Line Interface"); formatter.printWrapped(w, LINE_WIDTH, ""); if (modes.isEmpty()) { formatter.printWrapped(w, LINE_WIDTH, "No CLI tool is available"); } else { formatter.printHelp(w, LINE_WIDTH, "java -jar Net2Plan-cli.jar", null, options, 0, 1, null, true); formatter.printWrapped(w, LINE_WIDTH, ""); formatter.printWrapped(w, LINE_WIDTH, "Select 'help' to show this information, or 'mode' to execute a specific tool. Optionally, if 'help' is accompanied of a mode name, the help information for this mode is shown"); } w.flush(); help.append(sw.toString()); return help.toString(); } private String getCompleteHelp() { final StringBuilder help = new StringBuilder(); final String lineSeparator = StringUtils.getLineSeparator(); help.append(getMainHelp()); for (String mode : modes.keySet()) { help.append(lineSeparator); help.append(lineSeparator); help.append(getModeHelp(mode)); } return help.toString(); } /** * Entry point for the command-line interface. * * @param args Command-line arguments */ public static void main(String[] args) { new CLINet2Plan(args); } private static class IllegalModeException extends RuntimeException { public IllegalModeException(String message) { super(message); } } }
package com.rox.emu.mem; import com.rox.emu.env.RoxByte; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simple array representing memory, implementing the memory interface * * @author Ross Drew */ public class SimpleMemory implements Memory { private final Logger LOG = LoggerFactory.getLogger(this.getClass()); private final RoxByte[] memoryArray; public SimpleMemory(){ memoryArray = new RoxByte[0x10000]; reset(); } /** * {@inheritDoc} */ @Override public void setByteAt(int location, int byteValue) { LOG.trace("STORE mem[" + location + "] --> " + byteValue); memoryArray[location] = RoxByte.signedFrom(byteValue & 0xFF); } /** * {@inheritDoc} */ @Override public void setBlock(int startLocation, int[] byteValues) { LOG.trace("STORE mem[" + startLocation + "] --> " + byteValues.length + " bytes"); // System.arraycopy(byteValues, 0, memoryArray, startLocation, byteValues.length); for (int i=0; i<byteValues.length; i++){ memoryArray[startLocation + i] = RoxByte.signedFrom(byteValues[i]); } } /** * {@inheritDoc} */ @Override public int getByte(int location) { LOG.trace("FETCH mem[" + location +"] --> " + memoryArray[location]); return memoryArray[location].getAsInt(); } /** * {@inheritDoc} */ @Override public int getWord(int location) { int word = (memoryArray[location].getAsInt() << 8 | memoryArray[location+1].getAsInt()); LOG.trace("FETCH mem[" + location +"] --> " + word); return word; } /** * {@inheritDoc} */ @Override public int[] getBlock(int from, int to) { int[] extractedData = new int[to-from]; // System.arraycopy(memoryArray, from, extractedData, 0, extractedData.length); for (int i=0; i<extractedData.length; i++){ extractedData[i] = memoryArray[from + i].getAsInt(); } return extractedData; } /** * {@inheritDoc} */ @Override public void reset() { for (int i=0; i<memoryArray.length; i++) memoryArray[i] = RoxByte.ZERO; // for (int i : memoryArray) { // memoryArray[i] = 0; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.sister.kelompok5; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Message extends UnicastRemoteObject implements MessageInterface { private static final long serialVersionUID = 1L; public Message() throws RemoteException { } public void Echo(String name) throws RemoteException { System.out.println("Echo from client: " + name); } }
package com.stratio.specs; import com.auth0.jwt.JWTSigner; import com.ning.http.client.cookie.Cookie; import com.stratio.exceptions.DBException; import com.stratio.tests.utils.RemoteSSHConnection; import com.stratio.tests.utils.ThreadProperty; import cucumber.api.DataTable; import cucumber.api.java.en.Given; import org.assertj.core.api.Assertions; import org.openqa.selenium.WebElement; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.stratio.assertions.Assertions.assertThat; /** * Generic Given Specs. */ public class GivenGSpec extends BaseGSpec { public static final int PAGE_LOAD_TIMEOUT = 120; public static final int IMPLICITLY_WAIT = 10; public static final int SCRIPT_TIMEOUT = 30; /** * Generic constructor. * * @param spec */ public GivenGSpec(CommonG spec) { this.commonspec = spec; } /** * Create a basic Index. * * @param index_name index name * @param table the table where index will be created. * @param column the column where index will be saved * @param keyspace keyspace used * @throws Exception */ @Given("^I create a Cassandra index named '(.+?)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)'$") public void createBasicMapping(String index_name, String table, String column, String keyspace) throws Exception { String query = "CREATE INDEX " + index_name + " ON " + table + " (" + column + ");"; commonspec.getCassandraClient().executeQuery(query); } /** * Create a Cassandra Keyspace. * * @param keyspace */ @Given("^I create a Cassandra keyspace named '(.+)'$") public void createCassandraKeyspace(String keyspace) { commonspec.getCassandraClient().createKeyspace(keyspace); } /** * Connect to cluster. * * @param clusterType DB type (Cassandra|Mongo|Elasticsearch) * @param url url where is started Cassandra cluster */ @Given("^I connect to '(Cassandra|Mongo|Elasticsearch)' cluster at '(.+)'$") public void connect(String clusterType, String url) throws DBException, UnknownHostException { switch (clusterType) { case "Cassandra": commonspec.getCassandraClient().buildCluster(); commonspec.getCassandraClient().connect(); break; case "Mongo": commonspec.getMongoDBClient().connect(); break; case "Elasticsearch": LinkedHashMap<String, Object> settings_map = new LinkedHashMap<String, Object>(); settings_map.put("cluster.name", System.getProperty("ES_CLUSTER", "elasticsearch")); commonspec.getElasticSearchClient().setSettings(settings_map); commonspec.getElasticSearchClient().connect(); break; default: throw new DBException("Unknown cluster type"); } } /** * Create table * * @param table * @param datatable * @param keyspace * @throws Exception */ @Given("^I create a Cassandra table named '(.+?)' using keyspace '(.+?)' with:$") public void createTableWithData(String table, String keyspace, DataTable datatable) { try { commonspec.getCassandraClient().useKeyspace(keyspace); int attrLength = datatable.getGherkinRows().get(0).getCells().size(); Map<String, String> columns = new HashMap<String, String>(); ArrayList<String> pk = new ArrayList<String>(); for (int i = 0; i < attrLength; i++) { columns.put(datatable.getGherkinRows().get(0).getCells().get(i), datatable.getGherkinRows().get(1).getCells().get(i)); if ((datatable.getGherkinRows().size() == 3) && datatable.getGherkinRows().get(2).getCells().get(i).equalsIgnoreCase("PK")) { pk.add(datatable.getGherkinRows().get(0).getCells().get(i)); } } if (pk.isEmpty()) { throw new Exception("A PK is needed"); } commonspec.getCassandraClient().createTableWithData(table, columns, pk); } catch (Exception e) { // TODO Auto-generated catch block commonspec.getLogger().debug("Exception captured"); commonspec.getLogger().debug(e.toString()); commonspec.getExceptions().add(e); } } /** * Insert Data * * @param table * @param datatable * @param keyspace * @throws Exception */ @Given("^I insert in keyspace '(.+?)' and table '(.+?)' with:$") public void insertData(String keyspace, String table, DataTable datatable) { try { commonspec.getCassandraClient().useKeyspace(keyspace); int attrLength = datatable.getGherkinRows().get(0).getCells().size(); Map<String, Object> fields = new HashMap<String, Object>(); for (int e = 1; e < datatable.getGherkinRows().size(); e++) { for (int i = 0; i < attrLength; i++) { fields.put(datatable.getGherkinRows().get(0).getCells().get(i), datatable.getGherkinRows().get(e).getCells().get(i)); } commonspec.getCassandraClient().insertData(keyspace + "." + table, fields); } } catch (Exception e) { // TODO Auto-generated catch block commonspec.getLogger().debug("Exception captured"); commonspec.getLogger().debug(e.toString()); commonspec.getExceptions().add(e); } } @Given("^I save element (in position \'(.+?)\' in )?\'(.+?)\' in environment variable \'(.+?)\'$") public void saveElementEnvironment(String foo, String position, String element, String envVar) throws Exception { Pattern pattern = Pattern.compile("^((.*)(\\.)+)(\\$.*)$"); Matcher matcher = pattern.matcher(element); String json; String parsedElement; if (matcher.find()) { json = matcher.group(2); parsedElement = matcher.group(4); } else { json = commonspec.getResponse().getResponse(); parsedElement = element; } String value = commonspec.getJSONPathString(json, parsedElement, position); if (value == null) { throw new Exception("Element to be saved: " + element + " is null"); } else { ThreadProperty.set(envVar, value); } } /** * Drop all the ElasticSearch indexes. */ @Given("^I drop every existing elasticsearch index$") public void dropElasticsearchIndexes() { commonspec.getElasticSearchClient().dropAllIndexes(); } /** * Drop an specific index of ElasticSearch. * * @param index */ @Given("^I drop an elasticsearch index named '(.+?)'$") public void dropElasticsearchIndex(String index) { commonspec.getElasticSearchClient().dropSingleIndex(index); } /** * Execute a cql file over a Cassandra keyspace. * * @param filename * @param keyspace */ @Given("a Cassandra script with name '(.+?)' and default keyspace '(.+?)'$") public void insertDataOnCassandraFromFile(String filename, String keyspace) { commonspec.getCassandraClient().loadTestData(keyspace, "/scripts/" + filename); } /** * Drop a Cassandra Keyspace. * * @param keyspace */ @Given("^I drop a Cassandra keyspace '(.+)'$") public void dropCassandraKeyspace(String keyspace) { commonspec.getCassandraClient().dropKeyspace(keyspace); } /** * Create a MongoDB dataBase. * * @param databaseName */ @Given("^I create a MongoDB dataBase '(.+?)'$") public void createMongoDBDataBase(String databaseName) { commonspec.getMongoDBClient().connectToMongoDBDataBase(databaseName); } /** * Drop MongoDB Database. * * @param databaseName */ @Given("^I drop a MongoDB database '(.+?)'$") public void dropMongoDBDataBase(String databaseName) { commonspec.getMongoDBClient().dropMongoDBDataBase(databaseName); } /** * Insert data in a MongoDB table. * * @param dataBase * @param tabName * @param table */ @Given("^I insert into a MongoDB database '(.+?)' and table '(.+?)' this values:$") public void insertOnMongoTable(String dataBase, String tabName, DataTable table) { commonspec.getMongoDBClient().connectToMongoDBDataBase(dataBase); commonspec.getMongoDBClient().insertIntoMongoDBCollection(tabName, table); } /** * Truncate table in MongoDB. * * @param database * @param table */ @Given("^I drop every document at a MongoDB database '(.+?)' and table '(.+?)'") public void truncateTableInMongo(String database, String table) { commonspec.getMongoDBClient().connectToMongoDBDataBase(database); commonspec.getMongoDBClient().dropAllDataMongoDBCollection(table); } /** * Browse to {@code url} using the current browser. * * @param path * @throws Exception */ @Given("^I browse to '(.+?)'$") public void seleniumBrowse(String path) throws Exception { assertThat(path).isNotEmpty(); if (commonspec.getWebHost() == null) { throw new Exception("Web host has not been set"); } if (commonspec.getWebPort() == null) { throw new Exception("Web port has not been set"); } String webURL = "http://" + commonspec.getWebHost() + commonspec.getWebPort(); commonspec.getDriver().get(webURL + path); commonspec.setParentWindow(commonspec.getDriver().getWindowHandle()); } /** * Set app host and port {@code host, @code port} * * @param host * @param port */ @Given("^My app is running in '([^:]+?)(:.+?)?'$") public void setupApp(String host, String port) { assertThat(host).isNotEmpty(); assertThat(port).isNotEmpty(); if (port == null) { port = ":80"; } commonspec.setWebHost(host); commonspec.setWebPort(port); commonspec.setRestHost(host); commonspec.setRestPort(port); } /** * Browse to {@code webHost, @code webPort} using the current browser. * * @param webHost * @param webPort * @throws MalformedURLException */ @Given("^I set web base url to '([^:]+?)(:.+?)?'$") public void setupWeb(String webHost, String webPort) throws MalformedURLException { assertThat(webHost).isNotEmpty(); assertThat(webPort).isNotEmpty(); if (webPort == null) { webPort = ":80"; } commonspec.setWebHost(webHost); commonspec.setWebPort(webPort); } /** * Send requests to {@code restHost @code restPort}. * * @param restHost * @param restPort */ @Given("^I( securely)? send requests to '([^:]+?)(:.+?)?'$") public void setupRestClient(String isSecured, String restHost, String restPort) { assertThat(restHost).isNotEmpty(); assertThat(restPort).isNotEmpty(); String restProtocol = "http: if (isSecured != null) { restProtocol = "https: } if (restHost == null) { restHost = "localhost"; } if (restPort == null) { restPort = ":80"; } commonspec.setRestProtocol(restProtocol); commonspec.setRestHost(restHost); commonspec.setRestPort(restPort); } /** * Maximizes current browser window. Mind the current resolution could break a test. */ @Given("^I maximize the browser$") public void seleniumMaximize(String url) { commonspec.getDriver().manage().window().maximize(); } /** * Switches to a frame/ iframe. */ @Given("^I switch to the iframe on index '(\\d+?)'$") public void seleniumSwitchFrame(Integer index) { assertThat(commonspec.getPreviousWebElements()).as("There are less found elements than required") .hasAtLeast(index); WebElement elem = commonspec.getPreviousWebElements().getPreviousWebElements().get(index); commonspec.getDriver().switchTo().frame(elem); } /** * Switches to a parent frame/ iframe. */ @Given("^I switch to a parent frame$") public void seleniumSwitchAParentFrame() { commonspec.getDriver().switchTo().parentFrame(); } /** * Switches to the frames main container. */ @Given("^I switch to the main frame container$") public void seleniumSwitchParentFrame() { commonspec.getDriver().switchTo().frame(commonspec.getParentWindow()); } /* * Opens a ssh connection to remote host * * @param remoteHost * @param user * @param password (required if pemFile null) * @param pemFile (required if password null) * */ @Given("^I open remote ssh connection to host '(.+?)' with user '(.+?)'( and password '(.+?)')?( using pem file '(.+?)')?$") public void openSSHConnection(String remoteHost, String user, String foo, String password, String bar, String pemFile) throws Exception { if ((pemFile == null) || (pemFile.equals("none"))) { if (password == null) { throw new Exception("You have to provide a password or a pem file to be used for connection"); } commonspec.setRemoteSSHConnection(new RemoteSSHConnection(user, password, remoteHost, null)); commonspec.getLogger().debug("Opening ssh connection with password: { " + password + "}", commonspec.getRemoteSSHConnection()); } else { File pem = new File(pemFile); if (!pem.exists()) { throw new Exception("Pem file: " + pemFile + " does not exist"); } commonspec.setRemoteSSHConnection(new RemoteSSHConnection(user, null, remoteHost, pemFile)); commonspec.getLogger().debug("Opening ssh connection with pemFile: {}", commonspec.getRemoteSSHConnection()); } } /* * Authenticate in a DCOS cluster * * @param remoteHost * @param email * @param user * @param password (required if pemFile null) * @param pemFile (required if password null) * */ @Given("^I want to authenticate in DCOS cluster '(.+?)' with email '(.+?)' with user '(.+?)'( and password '(.*?)')?( using pem file '(.+?)')$") public void authenticateDCOSpem(String remoteHost,String email, String user, String foo, String password, String bar, String pemFile) throws Exception { String DCOSsecret = null; if ((pemFile== null) || (pemFile.equals("none"))) { if ((password.equals("")) || (password == null)){ throw new Exception("You have to provide a password or a pem file to be used for connection"); } commonspec.setRemoteSSHConnection(new RemoteSSHConnection(user, password, remoteHost, null)); commonspec.getRemoteSSHConnection().runCommand("sudo cat /var/lib/dcos/dcos-oauth/auth-token-secret"); DCOSsecret = commonspec.getRemoteSSHConnection().getResult().trim(); } else { File pem = new File(pemFile); if (!pem.exists()) { throw new Exception("Pem file: " + pemFile + " does not exist"); } commonspec.setRemoteSSHConnection(new RemoteSSHConnection(user, null, remoteHost, pemFile)); commonspec.getRemoteSSHConnection().runCommand("sudo cat /var/lib/dcos/dcos-oauth/auth-token-secret"); DCOSsecret = commonspec.getRemoteSSHConnection().getResult().trim(); } final JWTSigner signer = new JWTSigner(DCOSsecret); final HashMap<String, Object> claims = new HashMap(); claims.put("uid", email); final String jwt = signer.sign(claims); Cookie cookie = new Cookie("dcos-acs-auth-cookie", jwt, false, "", "", 99999, false, false); List<Cookie> cookieList = new ArrayList<Cookie>(); cookieList.add(cookie); commonspec.setCookies(cookieList); commonspec.getLogger().debug("DCOS cookie was set: " + cookie); } /* * Authenticate in a DCOS cluster * * @param dcosHost * @param user * */ @Given("^I authenticate in DCOS cluster '(.+?)' with email '(.+?)'$") public void authenticateDCOS(String dcosCluster, String user) throws Exception { commonspec.setRemoteSSHConnection(new RemoteSSHConnection("root", "stratio", dcosCluster, null)); commonspec.getRemoteSSHConnection().runCommand("cat /var/lib/dcos/dcos-oauth/auth-token-secret"); String DCOSsecret = commonspec.getRemoteSSHConnection().getResult().trim(); final JWTSigner signer = new JWTSigner(DCOSsecret); final HashMap<String, Object> claims = new HashMap(); claims.put("uid", user); final String jwt = signer.sign(claims); Cookie cookie = new Cookie("dcos-acs-auth-cookie", jwt, false, "", "", 99999, false, false); List<Cookie> cookieList = new ArrayList<Cookie>(); cookieList.add(cookie); commonspec.setCookies(cookieList); } /* * Copies file/s from remote system into local system * * @param remotePath * @param localPath * */ @Given("^I copy '(.+?)' from remote ssh connection and store it in '(.+?)'$") public void copyFromRemoteFile(String remotePath, String localPath) throws Exception { commonspec.getRemoteSSHConnection().copyFrom(remotePath, localPath); } /* * Copies file/s from local system to remote system * * @param localPath * @param remotePath * */ @Given("^I copy '(.+?)' to remote ssh connection in '(.+?)'$") public void copyToRemoteFile(String localPath, String remotePath) throws Exception { commonspec.getRemoteSSHConnection().copyTo(localPath, remotePath); } /** * Executes the command specified in local system * * @param command **/ @Given("^I execute command '(.+?)' locally$") public void executeLocalCommand(String command) throws Exception { commonspec.runLocalCommand(command); } /** * Executes the command specified in remote system * * @param command **/ @Given("^I execute command '(.+?)' in remote ssh connection( with exit status '(.+?)')?( and save the value in environment variable '(.+?)')?$") public void executeCommand(String command, String foo, Integer exitStatus, String var, String envVar) throws Exception { if (exitStatus == null) { exitStatus = 0; } commonspec.getRemoteSSHConnection().runCommand(command); commonspec.setCommandResult(commonspec.getRemoteSSHConnection().getResult()); commonspec.setCommandExitStatus(commonspec.getRemoteSSHConnection().getExitStatus()); List<String> logOutput = Arrays.asList(commonspec.getCommandResult().split("\n")); StringBuffer log = new StringBuffer(); int logLastLines = 25; if (logOutput.size() < 25) { logLastLines = logOutput.size(); } for (String s : logOutput.subList(logOutput.size() - logLastLines, logOutput.size())) { log.append(s).append("\n"); } if (envVar != null){ ThreadProperty.set(envVar, commonspec.getRemoteSSHConnection().getResult()); } if (commonspec.getRemoteSSHConnection().getExitStatus() != exitStatus) { if (System.getProperty("logLevel", "") != null && System.getProperty("logLevel", "").equalsIgnoreCase("debug")) { commonspec.getLogger().debug("Command complete stdout:\n{}", commonspec.getCommandResult()); } else { commonspec.getLogger().error("Command last {} lines stdout:", logLastLines); commonspec.getLogger().error("{}", log); } } else { commonspec.getLogger().debug("Command complete stdout:\n{}", commonspec.getCommandResult()); } Assertions.assertThat(commonspec.getRemoteSSHConnection().getExitStatus()).isEqualTo(exitStatus); } /** * Insert document in a MongoDB table. * * @param dataBase * @param collection * @param document */ @Given("^I insert into MongoDB database '(.+?)' and collection '(.+?)' the document from schema '(.+?)'$") public void insertOnMongoTable(String dataBase, String collection, String document) throws Exception { String retrievedDoc = commonspec.retrieveData(document, "json"); commonspec.getMongoDBClient().connectToMongoDBDataBase(dataBase); commonspec.getMongoDBClient().insertDocIntoMongoDBCollection(collection, retrievedDoc); } /** * Get all opened windows and store it. */ @Given("^new window is opened$") public void seleniumGetwindows() { Set<String> wel = commonspec.getDriver().getWindowHandles(); Assertions.assertThat(wel).as("Element count doesnt match").hasSize(2); } /** * Connect to zookeeper. * * @param zookeeperHosts as host:port (comma separated) */ @Given("^I connect to zk cluster at '(.+)'$") public void connectToZk(String zookeeperHosts) { commonspec.getZookeeperClient().setZookeeperConnection(zookeeperHosts, 3000); commonspec.getZookeeperClient().connectZk(); } /** * Connect to Kafka. * @param zkHost * @param zkPort * @param zkPath */ @Given("^I connect to kafka cluster at '(.+)':'(.+)' using path '(.+)'$") public void connectKafka(String zkHost, String zkPort, String zkPath) throws UnknownHostException { if (System.getenv("DCOS_CLUSTER") != null) { commonspec.getKafkaUtils().setZkHost(zkHost, zkPort, zkPath); } else { commonspec.getKafkaUtils().setZkHost(zkHost, zkPort, "dcos-service-" + zkPath); } commonspec.getKafkaUtils().connect(); } }
package com.zandero.rest; import com.zandero.rest.context.ContextProvider; import com.zandero.rest.data.ClassFactory; import com.zandero.rest.data.MediaTypeHelper; import com.zandero.rest.exception.ClassFactoryException; import com.zandero.rest.exception.ExceptionHandler; import com.zandero.rest.injection.InjectionProvider; import com.zandero.rest.reader.ValueReader; import com.zandero.rest.writer.HttpResponseWriter; import com.zandero.rest.writer.NotFoundResponseWriter; import com.zandero.utils.Assert; import io.vertx.core.Vertx; import io.vertx.core.http.HttpMethod; import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.CorsHandler; import javax.ws.rs.core.MediaType; import java.util.*; /** * Helper class to build up RestRouter with all writers, readers, handlers and context providers in one place */ public class RestBuilder { private final Vertx vertx; private final Router router; private List<Object> apis = new ArrayList<>(); private List<Object> contextProviders = new ArrayList<>(); private Map<Class, Object> registeredProviders = new HashMap<>(); private List<Object> exceptionHandlers = new ArrayList<>(); private Map<MediaType, Object> mediaTypeResponseWriters = new LinkedHashMap<>(); private Map<Class, Object> classResponseWriters = new LinkedHashMap<>(); private Map<MediaType, Object> mediaTypeValueReaders = new LinkedHashMap<>(); private Map<Class, Object> classValueReaders = new LinkedHashMap<>(); /** * Map of path / not found handlers */ private Map<String, Object> notFound = new LinkedHashMap<>(); /** * CORS handler if desired */ private CorsHandler corsHandler = null; private InjectionProvider injectionProvider = null; public RestBuilder(Router router) { Assert.notNull(router, "Missing vertx router!"); this.router = router; this.vertx = null; } public RestBuilder(Vertx vertx) { // hide Assert.notNull(vertx, "Missing vertx!"); this.router = null; this.vertx = vertx; } public RestBuilder register(Object... restApi) { Assert.notNullOrEmpty(restApi, "Missing REST API(s)!"); apis.addAll(Arrays.asList(restApi)); return this; } public RestBuilder notFound(String path, Class<? extends NotFoundResponseWriter> writer) { Assert.notNullOrEmptyTrimmed(path, "Missing path prefix!"); Assert.notNull(writer, "Missing not fount response writer!"); notFound.put(path, writer); // adds route path prefix return this; } public RestBuilder notFound(Class<? extends NotFoundResponseWriter> writer) { Assert.notNull(writer, "Missing not fount response writer!"); notFound.put(null, writer); // default ... handles all return this; } /** * Enables CORS for all methods and headers / * intended for testing purposes only - not recommended for production use * @return self */ public RestBuilder enableCors() { Set<String> allowedHeaders = new HashSet<>(); allowedHeaders.add("Access-Control-Allow-Origin"); //allowedHeaders.add("Access-Control-Allow-Credentials"); allowedHeaders.add("Access-Control-Allow-Headers"); allowedHeaders.add("Access-Control-Allow-Methods"); allowedHeaders.add("Access-Control-Expose-Headers"); allowedHeaders.add("Access-Control-Request-Method"); allowedHeaders.add("Access-Control-Request-Headers"); //allowedHeaders.add("Access-Control-Max-Age"); allowedHeaders.add("Origin"); return enableCors("*", false, -1, allowedHeaders); } /** * Enables CORS * * @param allowedOriginPattern allowed origin * @param allowCredentials allow credentials (true/false) * @param maxAge in seconds * @param allowedHeaders set of allowed headers * @param methods list of methods ... if empty all methods are allowed @return self * @return self */ public RestBuilder enableCors(String allowedOriginPattern, boolean allowCredentials, int maxAge, Set<String> allowedHeaders, HttpMethod... methods) { corsHandler = CorsHandler.create(allowedOriginPattern) .allowCredentials(allowCredentials) .maxAgeSeconds(maxAge); if (methods == null || methods.length == 0) { // if not given than all methods = HttpMethod.values(); } for (HttpMethod method : methods) { corsHandler.allowedMethod(method); } corsHandler.allowedHeaders(allowedHeaders); return this; } /** * Registeres one or more exception handler classes * * @param handlers to be registered * @return builder */ @SafeVarargs public final RestBuilder errorHandler(Class<? extends ExceptionHandler>... handlers) { Assert.notNullOrEmpty(handlers, "Missing exception handler(s)!"); exceptionHandlers.addAll(Arrays.asList(handlers)); return this; } /** * Registeres one or more exception handler instances * * @param handlers to be registered * @return builder */ public RestBuilder errorHandler(ExceptionHandler<?>... handlers) { Assert.notNullOrEmpty(handlers, "Missing exception handler(s)!"); exceptionHandlers.addAll(Arrays.asList(handlers)); return this; } public RestBuilder writer(Class<?> clazz, Class<? extends HttpResponseWriter> writer) { Assert.notNull(clazz, "Missing response class!"); Assert.notNull(writer, "Missing response writer type class!"); classResponseWriters.put(clazz, writer); return this; } public RestBuilder writer(String mediaType, Class<? extends HttpResponseWriter> writer) { Assert.notNullOrEmptyTrimmed(mediaType, "Missing media type!"); Assert.notNull(writer, "Missing response writer class!"); MediaType type = MediaTypeHelper.valueOf(mediaType); Assert.notNull(type, "Unknown media type given: " + mediaType); mediaTypeResponseWriters.put(type, writer); return this; } public RestBuilder writer(MediaType mediaType, Class<? extends HttpResponseWriter> writer) { Assert.notNull(mediaType, "Missing media type!"); Assert.notNull(writer, "Missing response writer class!"); mediaTypeResponseWriters.put(mediaType, writer); return this; } public RestBuilder reader(Class<?> clazz, Class<? extends ValueReader> reader) { Assert.notNull(clazz, "Missing read in class!"); Assert.notNull(reader, "Missing request reader type class!"); classValueReaders.put(clazz, reader); return this; } public RestBuilder reader(String mediaType, Class<? extends ValueReader> reader) { Assert.notNullOrEmptyTrimmed(mediaType, "Missing media type!"); Assert.notNull(reader, "Missing value reader class!"); MediaType type = MediaTypeHelper.valueOf(mediaType); Assert.notNull(type, "Unknown media type given: " + mediaType); mediaTypeValueReaders.put(type, reader); return this; } public RestBuilder reader(MediaType mediaType, Class<? extends ValueReader> reader) { Assert.notNull(mediaType, "Missing media type!"); Assert.notNull(reader, "Missing value reader class!"); mediaTypeValueReaders.put(mediaType, reader); return this; } public RestBuilder reader(Class<? extends ValueReader> reader) { Assert.notNull(reader, "Missing value reader class!"); mediaTypeValueReaders.put(null, reader); return this; } public <T> RestBuilder provide(ContextProvider<T> provider) { Assert.notNull(provider, "Missing context provider!"); contextProviders.add(provider); return this; } public <T> RestBuilder provide(Class<? extends ContextProvider<T>> provider) { Assert.notNull(provider, "Missing context provider!"); contextProviders.add(provider); return this; } public <T> RestBuilder addProvider(Class<T> clazz, ContextProvider<T> provider) { Assert.notNull(clazz, "Missing provided class type!"); Assert.notNull(provider, "Missing context provider!"); registeredProviders.put(clazz, provider); return this; } public <T> RestBuilder addProvider(Class<? extends ContextProvider<T>> provider) { Assert.notNull(provider, "Missing context provider!"); Class clazz = (Class) ClassFactory.getGenericType(provider); registeredProviders.put(clazz, provider); return this; } /** * Assosicate provider to getInstance members into REST classes, Reader, Writers ... * * @param provider to do the injection * @return rest builder */ public RestBuilder injectWith(InjectionProvider provider) { injectionProvider = provider; return this; } public RestBuilder injectWith(Class<? extends InjectionProvider> provider) { try { injectionProvider = (InjectionProvider) ClassFactory.newInstanceOf(provider); } catch (ClassFactoryException e) { throw new IllegalArgumentException(e); } return this; } private Router getRouter() { if (vertx == null) { return RestRouter.register(router, apis.toArray()); } return RestRouter.register(vertx, apis.toArray()); } @SuppressWarnings("unchecked") public Router build() { Assert.notNullOrEmpty(apis, "No REST API given, register at least one! Use: .register(api) call!"); RestRouter.injectWith(injectionProvider); if (registeredProviders.size() > 0) { registeredProviders.forEach((clazz, provider) -> { if (provider instanceof Class) { RestRouter.addProvider((Class<? extends ContextProvider>) provider); } else { RestRouter.addProvider(clazz, (ContextProvider) provider); } }); } // register APIs Router output = getRouter(); contextProviders.forEach(provider -> { if (provider instanceof Class) { RestRouter.provide(output, (Class<? extends ContextProvider>) provider); } else { RestRouter.provide(output, (ContextProvider<?>) provider); } }); // register readers classValueReaders.forEach((clazz, reader) -> { if (reader instanceof Class) { RestRouter.getReaders().register(clazz, (Class<? extends ValueReader>) reader); } else { RestRouter.getReaders().register(clazz, (ValueReader) reader); } }); mediaTypeValueReaders.forEach((type, reader) -> { if (type == null) { RestRouter.getReaders().register((Class<? extends ValueReader>) reader); } if (reader instanceof Class) { RestRouter.getReaders().register(type, (Class<? extends ValueReader>) reader); } else { RestRouter.getReaders().register(type, (ValueReader) reader); } }); // register writers classResponseWriters.forEach((clazz, writer) -> { if (writer instanceof Class) { RestRouter.getWriters().register(clazz, (Class<? extends HttpResponseWriter>) writer); } else { RestRouter.getWriters().register(clazz, (HttpResponseWriter) writer); } }); mediaTypeResponseWriters.forEach((type, writer) -> { if (writer instanceof Class) { RestRouter.getWriters().register(type, (Class<? extends HttpResponseWriter>) writer); } else { RestRouter.getWriters().register(type, (HttpResponseWriter<?>) writer); } }); // register exception handlers exceptionHandlers.forEach(handler -> { if (handler instanceof Class) { RestRouter.getExceptionHandlers().register((Class<? extends ExceptionHandler>) handler); } else { RestRouter.getExceptionHandlers().register((ExceptionHandler) handler); } }); for (String path : notFound.keySet()) { Object notFoundHandler = notFound.get(path); if (notFoundHandler instanceof Class) { RestRouter.notFound(output, path, (Class<? extends NotFoundResponseWriter>) notFoundHandler); } else { RestRouter.notFound(output, path, (NotFoundResponseWriter) notFoundHandler); } } if (corsHandler != null) { output.route().handler(corsHandler); } return output; } }
package control; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import data.Camera; import data.CameraShot; import data.DirectorShot; import data.Instrument; import data.Shot; import gui.centerarea.CameraShotBlock; import gui.centerarea.DirectorShotBlock; import gui.centerarea.ShotBlock; import gui.events.CameraShotBlockUpdatedEvent; import gui.headerarea.DetailView; import gui.headerarea.DirectorDetailView; import gui.misc.TweakingHelper; import gui.styling.StyledCheckbox; import gui.styling.StyledMenuButton; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.event.EventHandler; import javafx.scene.control.CustomMenuItem; import javafx.scene.input.KeyCode; import javafx.scene.input.MouseEvent; import lombok.extern.log4j.Log4j2; /** * Controller for the DetailView. */ @Log4j2 public class DetailViewController { private DetailView detailView; private ControllerManager manager; private DirectorShotBlock activeBlock; private List<StyledCheckbox> activeBlockBoxes; /** * Constructor. * @param manager - the controller manager this controller belongs to */ public DetailViewController(ControllerManager manager) { this.detailView = manager.getRootPane().getRootHeaderArea().getDetailView(); this.manager = manager; initDescription(); initName(); initBeginCount(); initEndCount(); } /** * Re-init the tool view for when a camera block is selected. */ public void reInitForCameraBlock() { initDescription(); initName(); initBeginCount(); initEndCount(); initInstrumentsDropdown(); } /** * Re-init the tool view for when a director block is selected. */ public void reInitForDirectorBlock() { reInitForCameraBlock(); initBeginPadding(); initEndPadding(); initDropDown(); } /** * Initialize the handlers for the begin padding field. */ private void initBeginPadding() { //((DirectorDetailView) detailView).setBeforePadding(0); ((DirectorDetailView) detailView).getPaddingBeforeField() .focusedProperty().addListener(this::beforePaddingFocusListener); ((DirectorDetailView) detailView).getPaddingBeforeField().setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { this.beforePaddingUpdateHelper(); } }); } /** * Listener for focus change on before padding field. * @param observable the observable value * @param oldValue If there was an old value * @param newValue If there was a new value */ private void beforePaddingFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!newValue) { this.beforePaddingUpdateHelper(); } } /** * Update method for the before padding field. */ private void beforePaddingUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( ((DirectorDetailView) detailView).getPaddingBeforeField().getText()); ((DirectorDetailView) detailView).getPaddingBeforeField().setText(newValue); double newVal = Double.parseDouble(newValue); DirectorShotBlock directorShotBlock = ((DirectorShotBlock) manager.getActiveShotBlock()); directorShotBlock.setPaddingBefore(newVal); DirectorShot directorShot = ((DirectorShot) manager.getActiveShotBlock().getShot()); directorShot.setFrontShotPadding(newVal); directorShot.getCameraShots().forEach(e -> { CameraShotBlock shotBlock = manager.getTimelineControl().getShotBlockForShot(e); shotBlock.setBeginCount(directorShot.getBeginCount() - newVal, true); manager.getTimelineControl().modifyCameraShot( (CameraShotBlockUpdatedEvent) shotBlock.getShotBlockUpdatedEvent(), shotBlock); manager.setActiveShotBlock(directorShotBlock); }); manager.getTimelineControl().recomputeAllCollisions(); } } /** * Initialize the handlers for end padding field. */ private void initEndPadding() { ((DirectorDetailView) detailView).getPaddingAfterField().focusedProperty() .addListener(this::afterPaddingFocusListener); ((DirectorDetailView) detailView).getPaddingAfterField().setOnKeyPressed( event -> { if (event.getCode().equals(KeyCode.ENTER)) { this.afterPaddingUpdateHelper(); } }); } /** * Listener for focus change on end padding field. * @param observable the observable value * @param oldValue if there is an old value * @param newValue if there is a new value */ private void afterPaddingFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!newValue) { this.afterPaddingUpdateHelper(); } } /** * Update method for the after padding. */ private void afterPaddingUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( ((DirectorDetailView) detailView).getPaddingAfterField().getText()); ((DirectorDetailView) detailView).getPaddingAfterField().setText(newValue); double newVal = Double.parseDouble(newValue); DirectorShotBlock directorShotBlock = ((DirectorShotBlock) manager.getActiveShotBlock()); directorShotBlock.setPaddingAfter(newVal); ((DirectorShot) manager.getActiveShotBlock().getShot()).setEndShotPadding(newVal); ((DirectorShot) manager.getActiveShotBlock().getShot()).getCameraShots().forEach(e -> { CameraShotBlock shotBlock = manager.getTimelineControl().getShotBlockForShot(e); shotBlock.setEndCount(((DirectorShot) manager.getActiveShotBlock().getShot()) .getEndCount() + newVal, true); manager.getTimelineControl().modifyCameraShot( (CameraShotBlockUpdatedEvent) shotBlock.getShotBlockUpdatedEvent(), shotBlock); manager.setActiveShotBlock(directorShotBlock); }); manager.getTimelineControl().recomputeAllCollisions(); } } /** * Initialize the instruments dropdown. * @param shotBlock the shot block to do that for */ private void initInstrumentsDropdown(ShotBlock shotBlock) { log.error("Initing da dropdown"); ArrayList<Instrument> instruments = shotBlock.getInstruments(); detailView.getInstrumentsDropdown().getItems().clear(); detailView.setInstruments(manager.getScriptingProject().getInstruments()); shotBlock.getInstruments().forEach(instrument -> { detailView.getInstrumentsDropdown().getCheckModel().check(instrument.getName()); }); } /** * Initialize the instruments dropdown menu. */ private void initInstrumentsDropdown() { detailView.getInstrumentsDropdown().getCheckModel() .getCheckedIndices() .addListener(this::instrumentsDropdownChangeListener); } /** * Listener for changes in checked indices for instruments dropdown. * @param c the change that happened */ private void instrumentsDropdownChangeListener(ListChangeListener.Change c) { Shot shot = manager.getActiveShotBlock().getShot(); c.next(); if (c.wasAdded()) { instrumentAddedInDropdown((int) c.getAddedSubList().get(0)); } else { instrumentDeletedInDropdown((int) c.getRemoved().get(0)); } } /** * Handler for a unchecked index in instrument dropdown. * @param index the index that got unchecked */ private void instrumentDeletedInDropdown(int index) { ShotBlock shotBlock = manager.getActiveShotBlock(); shotBlock.getInstruments().remove(manager.getScriptingProject().getInstruments() .get(index)); shotBlock.getShot().getInstruments().remove(manager.getScriptingProject() .getInstruments().get(index)); shotBlock.getTimetableBlock().removeInstrument(manager.getScriptingProject() .getInstruments().get(index)); shotBlock.recompute(); } /** * Handler for a checked index in instrument dropdown. * @param index the index that got unchecked */ private void instrumentAddedInDropdown(int index) { ShotBlock shotBlock = manager.getActiveShotBlock(); shotBlock.getInstruments().add(manager.getScriptingProject().getInstruments().get(index)); shotBlock.getTimetableBlock().addInstrument(manager.getScriptingProject() .getInstruments().get(index)); shotBlock.recompute(); } /** * Change listener for the dropdown. Fires whenever a box is selected or deselected. * @param c The Change with information about what changed. */ private void camerasDropdownChangeListener(ListChangeListener.Change c) { DirectorShot shot = ((DirectorShot) manager.getActiveShotBlock().getShot()); c.next(); if (c.wasAdded()) { cameraAddedInDropdown((int) c.getAddedSubList().get(0)); } else { cameraDeletedInDropdown((int) c.getRemoved().get(0)); } } /** * Method for handling a deselect in the drop down. * @param index the index of the deselected camera. */ private void cameraDeletedInDropdown(int index) { DirectorShotBlock dShotBlock = ((DirectorShotBlock) manager.getActiveShotBlock()); DirectorShot dShot = ((DirectorShot) manager.getActiveShotBlock().getShot()); Iterator<CameraShot> iterator = dShot.getCameraShots().iterator(); CameraShot toRemove = null; while (iterator.hasNext()) { CameraShot shot = iterator.next(); if (manager.getTimelineControl() .getShotBlockForShot(shot).getTimetableNumber() == index) { toRemove = shot; break; } } manager.getTimelineControl().removeCameraShot(toRemove); dShot.getCameraShots().remove(toRemove); dShot.getTimelineIndices().remove(index); } /** * Method for handling a select in the dropdown. * @param index the index of the camera that was selected. */ private void cameraAddedInDropdown(int index) { CameraShot shot = new CameraShot(); DirectorShot dShot = ((DirectorShot) manager.getActiveShotBlock().getShot()); // Set shot variables shot.setName(dShot.getName()); shot.setDescription(dShot.getDescription()); shot.setBeginCount(dShot.getBeginCount() - dShot.getFrontShotPadding()); shot.setEndCount(dShot.getEndCount() + dShot.getEndShotPadding()); shot.setDirectorShot(dShot); // Add shot where needed dShot.getCameraShots().add(shot); dShot.getTimelineIndices().add(index); DirectorShotBlock dShotBlock = ((DirectorShotBlock) manager.getActiveShotBlock()); manager.getScriptingProject().getCameraTimelines().get(index).addShot(shot); manager.getTimelineControl().initShotBlock(index, shot, false); manager.setActiveShotBlock(dShotBlock); } /** * Init the begincount handlers. */ private void initBeginCount() { detailView.getBeginCountField().focusedProperty() .addListener(this::beginCountFocusListener); detailView.getBeginCountField().setOnKeyPressed( event -> { if (event.getCode().equals(KeyCode.ENTER)) { this.beginCountUpdateHelper(); } }); } /** * Changelistener for when focus on begincountfield changes. * @param observable - the observable * @param oldValue - the old value of focus * @param newValue - the new value of focus */ void beginCountFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { // exiting focus if (!newValue) { this.beginCountUpdateHelper(); } } /** * Helper for when the begincount field is edited. * Parses entry to quarters and updates all the values */ void beginCountUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( detailView.getBeginCountField().getText()); detailView.getBeginCountField().setText(newValue); double newVal = Double.parseDouble(newValue); manager.getActiveShotBlock().setBeginCount(newVal); manager.getActiveShotBlock().getShot().setBeginCount(newVal); } } /** * Init the endcuont handlers. */ private void initEndCount() { detailView.getEndCountField().focusedProperty() .addListener(this::endCountFocusListener); detailView.getEndCountField().setOnKeyPressed( event -> { if (event.getCode().equals(KeyCode.ENTER)) { endCountUpdateHelper(); } }); } /** * Changelistener for when focus on endcountfield changes. * @param observable - the observable * @param oldValue - the old value of focus * @param newValue - the new value of focus */ void endCountFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { // exiting focus if (!newValue) { this.endCountUpdateHelper(); } } /** * Helper for when the endcount field is edited. * Parses entry to quarters and updates all the values */ private void endCountUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( detailView.getEndCountField().getText()); double newVal = Double.parseDouble(newValue); detailView.getEndCountField().setText(newValue); manager.getActiveShotBlock().setEndCount(newVal); manager.getActiveShotBlock().getShot().setEndCount(newVal); } } /** * Init the description handlers. */ private void initDescription() { detailView.getDescriptionField().textProperty() .addListener(this::descriptionTextChangedListener); } /** * Changelistener for when the text in descriptionfield changes. * @param observable - the observable * @param oldValue - the old value of the field * @param newValue - the new value of the field */ void descriptionTextChangedListener(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (manager.getActiveShotBlock() != null) { manager.getActiveShotBlock().setDescription(newValue); manager.getActiveShotBlock().getShot().setDescription(newValue); } } /** * Init the name handler. */ private void initName() { detailView.getNameField().textProperty() .addListener(this::nameTextChangedListener); } /** * Changelistener for when the text in namefield changes. * @param observable - the observable * @param oldValue - the old value of the field * @param newValue - the new value of the field */ void nameTextChangedListener(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (manager.getActiveShotBlock() != null) { manager.getActiveShotBlock().setName(newValue); manager.getActiveShotBlock().getShot().setName(newValue); } } /** * Method to signal that the active block is changed so we can update it. */ public void activeBlockChanged() { if (manager.getActiveShotBlock() != null) { if (manager.getActiveShotBlock() instanceof CameraShotBlock) { activeBlockChangedCamera(); } else { activeBlockChangedDirector(); } } else { detailView.resetDetails(); detailView.setInvisible(); } } /** * Handler for when the active block is now a camera shot. */ private void activeBlockChangedCamera() { detailView = new DetailView(); detailView.setDescription(manager.getActiveShotBlock().getDescription()); detailView.setName(manager.getActiveShotBlock().getName()); detailView.setBeginCount(manager.getActiveShotBlock().getBeginCount()); detailView.setEndCount(manager.getActiveShotBlock().getEndCount()); initInstrumentsDropdown(manager.getActiveShotBlock()); detailView.setVisible(); detailView.setVisible(true); // Re-init the detail view with new data manager.getRootPane().getRootHeaderArea().setDetailView(detailView); manager.getRootPane().getRootHeaderArea().reInitHeaderBar(detailView); this.reInitForCameraBlock(); } /** * Handler for when the active block is now a director shot. */ private void activeBlockChangedDirector() { DirectorShotBlock shotBlock = (DirectorShotBlock) manager.getActiveShotBlock(); detailView = new DirectorDetailView(); // Set detail view variables detailView.setDescription(shotBlock.getDescription()); detailView.setName(shotBlock.getName()); detailView.setBeginCount(shotBlock.getBeginCount()); detailView.setEndCount(shotBlock.getEndCount()); ((DirectorDetailView) detailView).getPaddingBeforeField() .setText(detailView.formatDouble(shotBlock.getPaddingBefore())); ((DirectorDetailView) detailView).getPaddingAfterField() .setText(detailView.formatDouble(shotBlock.getPaddingAfter())); activeBlock = shotBlock; //initDropDown(shotBlock); initInstrumentsDropdown(shotBlock); detailView.setVisible(); detailView.setVisible(true); // Re-init the detail view with new data manager.getRootPane().getRootHeaderArea().reInitHeaderBar(detailView); this.reInitForDirectorBlock(); } /** * Initialize drop down menu. */ private void initDropDown() { StyledMenuButton cameraButtons = ((DirectorDetailView) detailView).getSelectCamerasButton(); cameraButtons.setBorderColor(TweakingHelper.getColor(0)); cameraButtons.setFillColor(TweakingHelper.getBackgroundColor()); activeBlockBoxes = new ArrayList<>(); cameraButtons.showingProperty().addListener(createDropdownListener(cameraButtons)); } /** * Creates ChangeListener for the Dropdown checkboxes. * @param cameraButtons the dropdown with checkboxes. * @return the ChangeListener. */ private ChangeListener<Boolean> createDropdownListener(StyledMenuButton cameraButtons) { return new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { Set<Integer> indices = activeBlock.getTimelineIndices(); for (int i = 0; i < manager.getScriptingProject().getCameras().size(); i++) { Camera camera = manager.getScriptingProject().getCameras().get(i); StyledCheckbox checkbox = new StyledCheckbox(camera.getName(), indices.contains(i)); activeBlockBoxes.add(checkbox); CustomMenuItem item = new CustomMenuItem(checkbox); item.setHideOnClick(false); cameraButtons.getItems().add(item); int j = i; checkbox.setOnMouseClicked(createDropdownHandler(checkbox, j)); } } else { activeBlockBoxes.clear(); cameraButtons.getItems().clear(); } } }; } /** * Event handler for when a checkbox in the camera dropdown is clicked. * @param box the checkbox that was clicked. * @param i index of the checkbox. * @return the Event Handler. */ private EventHandler<MouseEvent> createDropdownHandler(StyledCheckbox box, int i) { return e -> { if (box.isSelected()) { cameraAddedInDropdown(i); } else { cameraDeletedInDropdown(i); } }; } }
package control; import java.util.Set; import data.DirectorShot; import gui.centerarea.CameraShotBlock; import gui.centerarea.DirectorShotBlock; import gui.headerarea.DetailView; import gui.headerarea.DirectorDetailView; import javafx.beans.value.ObservableValue; import javafx.scene.input.KeyCode; /** * Controller for the DetailView. */ public class DetailViewController { private DetailView detailView; private ControllerManager manager; /** * Constructor. * @param manager - the controller manager this controller belongs to */ public DetailViewController(ControllerManager manager) { this.detailView = manager.getRootPane().getRootHeaderArea().getDetailView(); this.manager = manager; initDescription(); initName(); initBeginCount(); initEndCount(); } public void reInitForCameraBlock() { initDescription(); initName(); initBeginCount(); initEndCount(); } public void reInitForDirectorBlock() { reInitForCameraBlock(); initBeginPadding(); initEndPadding(); initCamerasDropDown(); } private void initBeginPadding() { //((DirectorDetailView) detailView).setBeforePadding(0); ((DirectorDetailView) detailView).getPaddingBeforeField().focusedProperty().addListener(this::beforePaddingFocusListener); ((DirectorDetailView) detailView).getPaddingBeforeField().setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { this.beforePaddingUpdateHelper(); } }); } private void beforePaddingFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!newValue) { this.beforePaddingUpdateHelper(); } } private void beforePaddingUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber(((DirectorDetailView) detailView).getPaddingBeforeField().getText()); ((DirectorDetailView) detailView).getPaddingBeforeField().setText(newValue); double newVal = Double.parseDouble(newValue); ((DirectorShotBlock) manager.getActiveShotBlock()).setPaddingBefore(newVal); ((DirectorShot) manager.getActiveShotBlock().getShot()).setFrontShotPadding(newVal); ((DirectorShot) manager.getActiveShotBlock().getShot()).getCameraShots().forEach(e -> { System.out.println("Should update"); CameraShotBlock shotBlock = manager.getTimelineControl().getShotBlockForShot(e); shotBlock.setBeginCount(((DirectorShot) manager.getActiveShotBlock().getShot()).getBeginCount() - newVal, true); }); } } private void initEndPadding() { ((DirectorDetailView) detailView).getPaddingAfterField().focusedProperty().addListener(this::afterPaddingFocusListener); ((DirectorDetailView) detailView).getPaddingAfterField().setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { this.afterPaddingUpdateHelper(); } }); } private void afterPaddingFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!newValue) { this.afterPaddingUpdateHelper(); } } private void afterPaddingUpdateHelper() { System.out.println("AFTER UPDATE HELPER"); if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber(((DirectorDetailView) detailView).getPaddingAfterField().getText()); ((DirectorDetailView) detailView).getPaddingAfterField().setText(newValue); double newVal = Double.parseDouble(newValue); ((DirectorShotBlock) manager.getActiveShotBlock()).setPaddingAfter(newVal); ((DirectorShot) manager.getActiveShotBlock().getShot()).setEndShotPadding(newVal); ((DirectorShot) manager.getActiveShotBlock().getShot()).getCameraShots().forEach(e -> { CameraShotBlock shotBlock = manager.getTimelineControl().getShotBlockForShot(e); shotBlock.setEndCount(((DirectorShot) manager.getActiveShotBlock().getShot()).getEndCount() + newVal, true); }); } } private void initCamerasDropDown() { } /** * Init the begincount handlers. */ private void initBeginCount() { //detailView.setBeginCount(0); detailView.getBeginCountField().focusedProperty() .addListener(this::beginCountFocusListener); detailView.getBeginCountField().setOnKeyPressed( event -> { if (event.getCode().equals(KeyCode.ENTER)) { this.beginCountUpdateHelper(); } }); } /** * Changelistener for when focus on begincountfield changes. * @param observable - the observable * @param oldValue - the old value of focus * @param newValue - the new value of focus */ void beginCountFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { // exiting focus if (!newValue) { this.beginCountUpdateHelper(); } } /** * Helper for when the begincount field is edited. * Parses entry to quarters and updates all the values */ void beginCountUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( detailView.getBeginCountField().getText()); detailView.getBeginCountField().setText(newValue); double newVal = Double.parseDouble(newValue); manager.getActiveShotBlock().setBeginCount(newVal); manager.getActiveShotBlock().getShot().setBeginCount(newVal); } } /** * Init the endcuont handlers. */ private void initEndCount() { //detailView.setEndCount(0); detailView.getEndCountField().focusedProperty() .addListener(this::endCountFocusListener); detailView.getEndCountField().setOnKeyPressed( event -> { if (event.getCode().equals(KeyCode.ENTER)) { endCountUpdateHelper(); } }); } /** * Changelistener for when focus on endcountfield changes. * @param observable - the observable * @param oldValue - the old value of focus * @param newValue - the new value of focus */ void endCountFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { // exiting focus if (!newValue) { this.endCountUpdateHelper(); } } /** * Helper for when the endcount field is edited. * Parses entry to quarters and updates all the values */ private void endCountUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( detailView.getEndCountField().getText()); double newVal = Double.parseDouble(newValue); detailView.getEndCountField().setText(newValue); manager.getActiveShotBlock().setEndCount(newVal); manager.getActiveShotBlock().getShot().setEndCount(newVal); } } /** * Init the description handlers. */ private void initDescription() { //detailView.setDescription(""); detailView.getDescriptionField().textProperty() .addListener(this::descriptionTextChangedListener); } /** * Changelistener for when the text in descriptionfield changes. * @param observable - the observable * @param oldValue - the old value of the field * @param newValue - the new value of the field */ void descriptionTextChangedListener(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (manager.getActiveShotBlock() != null) { manager.getActiveShotBlock().setDescription(newValue); manager.getActiveShotBlock().getShot().setDescription(newValue); } } /** * Init the name handler. */ private void initName() { //detailView.setName(""); detailView.getNameField().textProperty() .addListener(this::nameTextChangedListener); } /** * Changelistener for when the text in namefield changes. * @param observable - the observable * @param oldValue - the old value of the field * @param newValue - the new value of the field */ void nameTextChangedListener(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (manager.getActiveShotBlock() != null) { manager.getActiveShotBlock().setName(newValue); manager.getActiveShotBlock().getShot().setName(newValue); } } /** * Method to signal that the active block is changed so we can update it. */ public void activeBlockChanged() { if (manager.getActiveShotBlock() != null) { System.out.println("PASSED NULL CHECK"); if (manager.getActiveShotBlock() instanceof CameraShotBlock) { System.out.println("IS CAMERA SHOT BLOCK"); detailView = new DetailView(); detailView.setDescription(manager.getActiveShotBlock().getDescription()); detailView.setName(manager.getActiveShotBlock().getName()); detailView.setBeginCount(manager.getActiveShotBlock().getBeginCount()); detailView.setEndCount(manager.getActiveShotBlock().getEndCount()); detailView.setVisible(); detailView.setVisible(true); manager.getRootPane().getRootHeaderArea().setDetailView(detailView); manager.getRootPane().getRootHeaderArea().reInitHeaderBar(detailView); this.reInitForCameraBlock(); } else { System.out.println("IS DIRECTOR SHOT BLOCK"); DirectorShotBlock shotBlock = (DirectorShotBlock) manager.getActiveShotBlock(); detailView = new DirectorDetailView(); detailView.setDescription(shotBlock.getDescription()); detailView.setName(shotBlock.getName()); detailView.setBeginCount(shotBlock.getBeginCount()); detailView.setEndCount(shotBlock.getEndCount()); ((DirectorDetailView) detailView).getPaddingBeforeField().setText(detailView.formatDouble(shotBlock.getPaddingBefore())); ((DirectorDetailView) detailView).getPaddingAfterField().setText(detailView.formatDouble(shotBlock.getPaddingAfter())); initDropDown(shotBlock); detailView.setVisible(); detailView.setVisible(true); manager.getRootPane().getRootHeaderArea().reInitHeaderBar(detailView); this.reInitForDirectorBlock(); } } else { detailView.resetDetails(); detailView.setInvisible(); } } private void initDropDown(DirectorShotBlock shotBlock) { Set<Integer> indices = shotBlock.getTimelineIndices(); ((DirectorDetailView) detailView).getSelectCamerasDropDown().getItems().clear(); manager.getScriptingProject().getCameras().forEach(camera -> { ((DirectorDetailView) detailView).getSelectCamerasDropDown().getItems().add(camera.getName()); }); indices.forEach(e -> { ((DirectorDetailView) detailView).getSelectCamerasDropDown().getCheckModel().check(e); }); } }
package cyclops.control.lazy; import com.aol.cyclops2.data.collections.extensions.CollectionX; import com.aol.cyclops2.hkt.Higher; import com.aol.cyclops2.hkt.Higher4; import com.aol.cyclops2.types.*; import com.aol.cyclops2.types.foldable.To; import com.aol.cyclops2.types.functor.BiTransformable; import com.aol.cyclops2.types.functor.Transformable; import com.aol.cyclops2.types.reactive.Completable; import com.aol.cyclops2.types.reactive.ValueSubscriber; import cyclops.async.Future; import cyclops.collections.mutable.ListX; import cyclops.control.*; import cyclops.function.*; import cyclops.monads.AnyM; import cyclops.monads.Witness; import cyclops.monads.Witness.either4; import cyclops.stream.ReactiveSeq; import cyclops.typeclasses.*; import cyclops.typeclasses.comonad.Comonad; import cyclops.typeclasses.comonad.ComonadByPure; import cyclops.typeclasses.foldable.Foldable; import cyclops.typeclasses.foldable.Unfoldable; import cyclops.typeclasses.functor.Functor; import cyclops.typeclasses.monad.*; import lombok.AccessLevel; import lombok.AllArgsConstructor; import org.jooq.lambda.tuple.Tuple2; import org.jooq.lambda.tuple.Tuple3; import org.jooq.lambda.tuple.Tuple4; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.function.*; import java.util.stream.Stream; /** * A right biased Lazy Either4 type. map / flatMap operators are tail-call optimized * * * Can be one of 4 types * Left1 * Left2 * Left3 * Right * * * * @author johnmcclean * * @param <LT1> First type (Left type) * @param <LT2> Second type * @param <LT3> Third Type * @param <RT> Right type (operations are performed on this type if present) */ public interface Either4<LT1, LT2,LT3, RT> extends Transformable<RT>, Filters<RT>, Higher4<either4,LT1,LT2,LT3,RT>, BiTransformable<LT3, RT>, To<Either4<LT1, LT2,LT3, RT>>, MonadicValue<RT>, Supplier<RT>{ public static <LT1,LT2,LT3,T> Kleisli<Higher<Higher<Higher<either4, LT1>, LT2>,LT3>,Either4<LT1,LT2,LT3,T>,T> kindKleisli(){ return Kleisli.of(Instances.monad(), Either4::widen); } public static <LT1,LT2,LT3,T> Higher<Higher<Higher<Higher<either4, LT1>, LT2>,LT3>,T> widen(Either4<LT1,LT2,LT3,T> narrow) { return narrow; } public static <LT1,LT2,LT3,T> Cokleisli<Higher<Higher<Higher<either4, LT1>, LT2>,LT3>,T,Either4<LT1,LT2,LT3,T>> kindCokleisli(){ return Cokleisli.of(Either4::narrowK); } static <LT2,LT3,RT> Either4.CompletableEither4<RT,LT2,LT3,RT> either4(){ Completable.CompletablePublisher<RT> c = new Completable.CompletablePublisher<RT>(); return new Either4.CompletableEither4<RT,LT2,LT3, RT>(c,fromFuture(Future.fromPublisher(c))); } @AllArgsConstructor static class CompletableEither4<ORG,LT1,LT2,RT> implements Either4<Throwable,LT1,LT2,RT>, Completable<ORG> { public final Completable.CompletablePublisher<ORG> complete; public final Either4<Throwable, LT1,LT2, RT> either; @Override public boolean isFailed() { return complete.isFailed(); } @Override public boolean isDone() { return complete.isDone(); } @Override public boolean complete(ORG done) { return complete.complete(done); } @Override public boolean completeExceptionally(Throwable error) { return complete.completeExceptionally(error); } @Override public RT get() { return either.get(); } @Override public <R> R visit(Function<? super Throwable, ? extends R> left1, Function<? super LT1, ? extends R> left2, Function<? super LT2, ? extends R> left3, Function<? super RT, ? extends R> right) { return either.visit(left1,left2,left3,right); } @Override public Maybe<RT> filter(Predicate<? super RT> test) { return either.filter(test); } @Override public <RT1> Either4<Throwable, LT1, LT2, RT1> flatMap(Function<? super RT, ? extends MonadicValue<? extends RT1>> mapper) { return either.flatMap(mapper); } @Override public Either4<Throwable, LT1, RT, LT2> swap3() { return either.swap3(); } @Override public Either4<Throwable, RT, LT2, LT1> swap2() { return either.swap2(); } @Override public Either4<RT, LT1, LT2, Throwable> swap1() { return either.swap1(); } @Override public boolean isRight() { return either.isRight(); } @Override public boolean isLeft1() { return either.isLeft1(); } @Override public boolean isLeft2() { return either.isLeft2(); } @Override public boolean isLeft3() { return either.isLeft3(); } @Override public <R1, R2> Either4<Throwable, LT1, R1, R2> bimap(Function<? super LT2, ? extends R1> fn1, Function<? super RT, ? extends R2> fn2) { return either.bimap(fn1,fn2); } @Override public <R> Either4<Throwable, LT1, LT2, R> map(Function<? super RT, ? extends R> fn) { return either.map(fn); } @Override public <T> Either4<Throwable, LT1, LT2, T> unit(T unit) { return either.unit(unit); } } /** * Static method useful as a method reference for fluent consumption of any value type stored in this Either * (will capture the lowest common type) * * <pre> * {@code * * myEither.to(Either4::consumeAny) .accept(System.out::println); * } * </pre> * * @param either Either to consume value for * @return Consumer we can applyHKT to consume value */ static <X, LT1 extends X, LT2 extends X, LT3 extends X, RT extends X> Consumer<Consumer<? super X>> consumeAny( Either4<LT1, LT2, LT3, RT> either) { return in -> visitAny(in, either); } static <X, LT1 extends X, LT2 extends X, LT3 extends X, RT extends X, R> Function<Function<? super X, R>, R> applyAny( Either4<LT1, LT2, LT3, RT> either) { return in -> visitAny(either, in); } static <X, LT1 extends X, LT2 extends X, LT3 extends X, RT extends X, R> R visitAny( Either4<LT1, LT2, LT3, RT> either, Function<? super X, ? extends R> fn) { return either.visit(fn, fn, fn, fn); } static <X, LT1 extends X, LT2 extends X, LT3 extends X, RT extends X> X visitAny(Consumer<? super X> c, Either4<LT1, LT2, LT3, RT> either) { Function<? super X, X> fn = x -> { c.accept(x); return x; }; return visitAny(either, fn); } static <LT1, LT2, LT3, RT> Either4<LT1, LT2, LT3, RT> fromMonadicValue(MonadicValue<RT> mv4) { if (mv4 instanceof Either4) { return (Either4) mv4; } return mv4.toOptional() .isPresent() ? Either4.right(mv4.get()) : Either4.left1(null); } static <LT1,LT2,LT3,RT> Either4<LT1,LT2,LT3,RT> fromLazy(Eval<Either4<LT1,LT2,LT3,RT>> lazy){ return new Either4.Lazy<>(lazy); } static <LT2,LT3,RT> Either4<Throwable,LT2,LT3,RT> fromFuture(Future<RT> future){ return fromLazy(Eval.<Either4<Throwable,LT2,LT3,RT>>fromFuture( future.map(e->e!=null?Either4.<Throwable,LT2,LT3,RT>right(e):Either4.<Throwable,LT2,LT3,RT>left1(new NoSuchElementException())) .recover(t->Either4.<Throwable,LT2,LT3,RT>left1(t.getCause())))); } /** * Turn a toX of Either3 into a singleUnsafe Either with Lists of values. * * <pre> * {@code * * Either4<String,String,String,Integer> just = Either4.right(10); Either4<String,String,String,Integer> none = Either4.left("none"); * Either4<ListX<String>,ListX<String>,ListX<String>,ListX<Integer>> xors =Either4.sequence(ListX.of(just,none,Either4.right(1))); //Eitehr.right(ListX.of(10,1))); * * }</pre> * * * * @param Either3 Either3 to sequence * @return Either3 Sequenced */ public static <LT1,LT2,LT3, PT> Either4<ListX<LT1>,ListX<LT2>,ListX<LT3>,ListX<PT>> sequence(final CollectionX<Either4<LT1, LT2, LT3, PT>> xors) { Objects.requireNonNull(xors); return AnyM.sequence(xors.stream().filter(Either4::isRight).map(AnyM::fromEither4).to().listX(), either4.INSTANCE) .to(Witness::either4); } /** * Traverse a Collection of Either3 producing an Either4 with a ListX, applying the transformation function to every * element in the list * * @param xors Either4s to sequence and transform * @param fn Transformation function * @return An Either4 with a transformed list */ public static <LT1,LT2, LT3,PT,R> Either4<ListX<LT1>,ListX<LT2>,ListX<LT3>,ListX<R>> traverse(final CollectionX<Either4<LT1, LT2, LT3, PT>> xors, Function<? super PT, ? extends R> fn) { return sequence(xors).map(l->l.map(fn)); } /** * Accumulate the results only from those Either3 which have a Right type present, using the supplied Monoid (a combining BiFunction/BinaryOperator and identity element that takes two * input values of the same type and returns the combined result) {@see com.aol.cyclops2.Monoids }. * * <pre> * {@code * Either4<String,String,String,Integer> just = Either4.right(10); Either4<String,String,String,Integer> none = Either4.left("none"); * * Either4<ListX<String>,ListX<String>,Integer> xors = Either4.accumulatePrimary(Monoids.intSum,ListX.of(just,none,Either4.right(1))); //Either4.right(11); * * } * </pre> * * * * @param xors Collection of Eithers to accumulate primary values * @param reducer Reducer to accumulate results * @return Either4 populated with the accumulate primary operation */ public static <LT1,LT2,LT3, RT> Either4<ListX<LT1>, ListX<LT2>,ListX<LT3>, RT> accumulate(final Monoid<RT> reducer, final CollectionX<Either4<LT1, LT2, LT3, RT>> xors) { return sequence(xors).map(s -> s.reduce(reducer)); } /** * Lazily construct a Right Either from the supplied publisher * <pre> * {@code * ReactiveSeq<Integer> reactiveStream = ReactiveSeq.of(1,2,3); Either4<Throwable,String,String,Integer> lazy = Either4.fromPublisher(reactiveStream); //Either[1] * * } * </pre> * @param pub Publisher to construct an Either from * @return Either constructed from the supplied Publisher */ public static <T1,T2,T> Either4<Throwable, T1, T2, T> fromPublisher(final Publisher<T> pub) { return fromFuture(Future.fromPublisher(pub)); } /** * Construct a Right Either4 from the supplied Iterable * <pre> * {@code * List<Integer> list = Arrays.asList(1,2,3); Either4<Throwable,String,Integer> future = Either4.fromIterable(list); //Either4[1] * * } * </pre> * @param iterable Iterable to construct an Either from * @return Either constructed from the supplied Iterable */ public static <ST, T, T2,RT> Either4<ST, T,T2,RT> fromIterable(final Iterable<RT> iterable) { final Iterator<RT> it = iterable.iterator(); return it.hasNext() ? Either4.right( it.next()) : Either4.left1(null); } /** * Construct a Either4#Right from an Eval * * @param right Eval to construct Either4#Right from * @return Either4 right instance */ public static <LT, M1,B, RT> Either4<LT, M1,B, RT> rightEval(final Eval<RT> right) { return new Right<>( right); } /** * Construct a Either4#Left1 from an Eval * * @param left Eval to construct Either4#Left1 from * @return Either4 Left1 instance */ public static <LT, M1, B, RT> Either4<LT, M1, B, RT> left1Eval(final Eval<LT> left) { return new Left1<>( left); } /** * Construct a Either4#Right * * @param right Value to store * @return Either4 Right instance */ public static <LT, M1, B, RT> Either4<LT, M1, B, RT> right(final RT right) { return new Right<>( Eval.later(()->right)); } /** * Construct a Either4#Left1 * * @param left Value to store * @return Left1 instance */ public static <LT, M1, B, RT> Either4<LT, M1, B, RT> left1(final LT left) { return new Left1<>( Eval.now(left)); } /** * Construct a Either4#Second * * @param middle Value to store * @return Second instance */ public static <LT, M1, B, RT> Either4<LT, M1, B, RT> left2(final M1 middle) { return new Left2<>( Eval.now(middle)); } /** * Construct a Either4#Third * * @param middle Value to store * @return Third instance */ public static <LT, M1, B, RT> Either4<LT, M1, B, RT> left3(final B middle) { return new Left3<>( Eval.now(middle)); } /** * Construct a Either4#Second from an Eval * * @param second Eval to construct Either4#middle from * @return Either4 second instance */ public static <LT, M1, B, RT> Either4<LT, M1, B, RT> left2Eval(final Eval<M1> middle) { return new Left2<>( middle); } /** * Construct a Either4#Third from an Eval * * @param third Eval to construct Either4#middle from * @return Either4 third instance */ public static <LT, M1, B, RT> Either4<LT, M1, B, RT> left3Eval(final Eval<B> middle) { return new Left3<>( middle); } @Override default <R> Either4<LT1, LT2, LT3, R> zipWith(Iterable<Function<? super RT, ? extends R>> fn) { return (Either4<LT1, LT2, LT3, R>) MonadicValue.super.zipWith(fn); } @Override default <R> Either4<LT1,LT2,LT3,R> zipWithS(Stream<Function<? super RT, ? extends R>> fn) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.zipWithS(fn); } @Override default <R> Either4<LT1,LT2,LT3,R> zipWithP(Publisher<Function<? super RT, ? extends R>> fn) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.zipWithP(fn); } @Override default <R> Either4<LT1,LT2,LT3,R> retry(final Function<? super RT, ? extends R> fn) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.retry(fn); } @Override default <U> Either4<LT1,LT2,LT3,Tuple2<RT, U>> zipP(final Publisher<? extends U> other) { return (Either4)MonadicValue.super.zipP(other); } @Override default <R> Either4<LT1,LT2,LT3,R> retry(final Function<? super RT, ? extends R> fn, final int retries, final long delay, final TimeUnit timeUnit) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.retry(fn,retries,delay,timeUnit); } @Override default <S, U> Either4<LT1,LT2,LT3,Tuple3<RT, S, U>> zip3(final Iterable<? extends S> second, final Iterable<? extends U> third) { return (Either4)MonadicValue.super.zip3(second,third); } @Override default <S, U, R> Either4<LT1,LT2,LT3,R> zip3(final Iterable<? extends S> second, final Iterable<? extends U> third, final Fn3<? super RT, ? super S, ? super U, ? extends R> fn3) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.zip3(second,third,fn3); } @Override default <T2, T3, T4> Either4<LT1,LT2,LT3,Tuple4<RT, T2, T3, T4>> zip4(final Iterable<? extends T2> second, final Iterable<? extends T3> third, final Iterable<? extends T4> fourth) { return (Either4)MonadicValue.super.zip4(second,third,fourth); } @Override default <T2, T3, T4, R> Either4<LT1,LT2,LT3,R> zip4(final Iterable<? extends T2> second, final Iterable<? extends T3> third, final Iterable<? extends T4> fourth, final Fn4<? super RT, ? super T2, ? super T3, ? super T4, ? extends R> fn) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.zip4(second,third,fourth,fn); } @Override default <R> Either4<LT1,LT2,LT3,R> flatMapS(final Function<? super RT, ? extends Stream<? extends R>> mapper) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.flatMapS(mapper); } default < RT1> Either4<LT1, LT2, LT3, RT1> flatMapI(Function<? super RT, ? extends Iterable<? extends RT1>> mapper){ return this.flatMap(a -> { return Either4.fromIterable(mapper.apply(a)); }); } default Trampoline<Either4<LT1,LT2,LT3,RT>> toTrampoline() { return Trampoline.more(()->Trampoline.done(this)); } @Override default int arity() { return 4; } default < RT1> Either4<LT1, LT2, LT3,RT1> flatMapP(Function<? super RT, ? extends Publisher<? extends RT1>> mapper){ return this.flatMap(a -> fromPublisher(mapper.apply(a))); } /** * Visit the types in this Either4, only one user supplied function is executed depending on the type * * @param left1 Function to execute if this Either4 is a Left1 instance * @param left2 Function to execute if this Either4 is a Left2 instance * @param left3 Function to execute if this Either4 is a Left3 instance * @param right Function to execute if this Either4 is a right instance * @return Result of executed function */ <R> R visit(final Function<? super LT1, ? extends R> left1, final Function<? super LT2, ? extends R> left2 , final Function<? super LT3, ? extends R> left3, final Function<? super RT, ? extends R> right); /** * Filter this Either4 resulting in a Maybe#none if it is not a Right instance or if the predicate does not * hold. Otherwise results in a Maybe containing the current value * * @param test Predicate to applyHKT to filter this Either4 * @return Maybe containing the current value if this is a Right instance and the predicate holds, otherwise Maybe#none */ Maybe<RT> filter(Predicate<? super RT> test); /** * Flattening transformation on this Either4. Contains an internal trampoline so will convert tail-recursive calls * to iteration. * * @param mapper Mapping function * @return Mapped Either4 */ < RT1> Either4<LT1, LT2,LT3, RT1> flatMap( Function<? super RT, ? extends MonadicValue<? extends RT1>> mapper); /** * @return Swap the third and the right types */ Either4<LT1,LT2, RT, LT3> swap3(); /** * @return Swap the second and the right types */ Either4<LT1, RT,LT3, LT2> swap2(); /** * @return Swap the right and left types */ Either4<RT, LT2,LT3, LT1> swap1(); /** * @return True if this lazy contains the right type */ boolean isRight(); /** * @return True if this lazy contains the left1 type */ boolean isLeft1(); /** * @return True if this lazy contains the left2 type */ boolean isLeft2(); /** * @return True if this lazy contains the left3 type */ boolean isLeft3(); /* (non-Javadoc) * @see com.aol.cyclops2.types.Filters#ofType(java.lang.Class) */ @Override default <U> Maybe<U> ofType(Class<? extends U> type) { return (Maybe<U>)MonadicValue.super.ofType(type); } /* (non-Javadoc) * @see com.aol.cyclops2.types.Filters#filterNot(java.util.function.Predicate) */ @Override default Maybe<RT> filterNot(Predicate<? super RT> predicate) { return (Maybe<RT>)MonadicValue.super.filterNot(predicate); } /* (non-Javadoc) * @see com.aol.cyclops2.types.Filters#notNull() */ @Override default Maybe<RT> notNull() { return (Maybe<RT>)MonadicValue.super.notNull(); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.functor.BiTransformable#bimap(java.util.function.Function, * java.util.function.Function) */ @Override <R1, R2> Either4<LT1, LT2, R1, R2> bimap(Function<? super LT3, ? extends R1> fn1, Function<? super RT, ? extends R2> fn2); /* * (non-Javadoc) * * @see com.aol.cyclops2.types.functor.Transformable#map(java.util.function.Function) */ @Override <R> Either4<LT1,LT2,LT3, R> map(Function<? super RT, ? extends R> fn); /** * Return an Ior that can be this object or a Ior.primary or Ior.secondary * @return new Ior */ default Ior<LT1, RT> toIor() { return this.visit(l->Ior.secondary(l), m->Ior.secondary(null), m->Ior.secondary(null), r->Ior.primary(r)); } default Xor<LT1, RT> toXor() { return this.visit(l->Xor.secondary(l), m->Xor.secondary(null), m->Xor.secondary(null), r->Xor.primary(r)); } /* (non-Javadoc) * @see com.aol.cyclops2.types.MonadicValue#coflatMap(java.util.function.Function) */ @Override default <R> Either4<LT1,LT2,LT3,R> coflatMap(Function<? super MonadicValue<RT>, R> mapper) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.coflatMap(mapper); } /* (non-Javadoc) * @see com.aol.cyclops2.types.MonadicValue#nest() */ @Override default Either4<LT1,LT2,LT3,MonadicValue<RT>> nest() { return (Either4<LT1,LT2,LT3,MonadicValue<RT>>)MonadicValue.super.nest(); } /* (non-Javadoc) * @see com.aol.cyclops2.types.MonadicValue#forEach4(java.util.function.Function, java.util.function.BiFunction, com.aol.cyclops2.util.function.TriFunction, com.aol.cyclops2.util.function.QuadFunction) */ @Override default <T2, R1, R2, R3, R> Either4<LT1,LT2,LT3,R> forEach4(Function<? super RT, ? extends MonadicValue<R1>> value1, BiFunction<? super RT, ? super R1, ? extends MonadicValue<R2>> value2, Fn3<? super RT, ? super R1, ? super R2, ? extends MonadicValue<R3>> value3, Fn4<? super RT, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.forEach4(value1, value2, value3, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops2.types.MonadicValue#forEach4(java.util.function.Function, java.util.function.BiFunction, com.aol.cyclops2.util.function.TriFunction, com.aol.cyclops2.util.function.QuadFunction, com.aol.cyclops2.util.function.QuadFunction) */ @Override default <T2, R1, R2, R3, R> Either4<LT1,LT2,LT3,R> forEach4(Function<? super RT, ? extends MonadicValue<R1>> value1, BiFunction<? super RT, ? super R1, ? extends MonadicValue<R2>> value2, Fn3<? super RT, ? super R1, ? super R2, ? extends MonadicValue<R3>> value3, Fn4<? super RT, ? super R1, ? super R2, ? super R3, Boolean> filterFunction, Fn4<? super RT, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.forEach4(value1, value2, value3, filterFunction, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops2.types.MonadicValue#forEach3(java.util.function.Function, java.util.function.BiFunction, com.aol.cyclops2.util.function.TriFunction) */ @Override default <T2, R1, R2, R> Either4<LT1,LT2,LT3,R> forEach3(Function<? super RT, ? extends MonadicValue<R1>> value1, BiFunction<? super RT, ? super R1, ? extends MonadicValue<R2>> value2, Fn3<? super RT, ? super R1, ? super R2, ? extends R> yieldingFunction) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.forEach3(value1, value2, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops2.types.MonadicValue#forEach3(java.util.function.Function, java.util.function.BiFunction, com.aol.cyclops2.util.function.TriFunction, com.aol.cyclops2.util.function.TriFunction) */ @Override default <T2, R1, R2, R> Either4<LT1,LT2,LT3,R> forEach3(Function<? super RT, ? extends MonadicValue<R1>> value1, BiFunction<? super RT, ? super R1, ? extends MonadicValue<R2>> value2, Fn3<? super RT, ? super R1, ? super R2, Boolean> filterFunction, Fn3<? super RT, ? super R1, ? super R2, ? extends R> yieldingFunction) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.forEach3(value1, value2, filterFunction, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops2.types.MonadicValue#forEach2(java.util.function.Function, java.util.function.BiFunction) */ @Override default <R1, R> Either4<LT1,LT2,LT3,R> forEach2(Function<? super RT, ? extends MonadicValue<R1>> value1, BiFunction<? super RT, ? super R1, ? extends R> yieldingFunction) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.forEach2(value1, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops2.types.MonadicValue#forEach2(java.util.function.Function, java.util.function.BiFunction, java.util.function.BiFunction) */ @Override default <R1, R> Either4<LT1,LT2,LT3,R> forEach2(Function<? super RT, ? extends MonadicValue<R1>> value1, BiFunction<? super RT, ? super R1, Boolean> filterFunction, BiFunction<? super RT, ? super R1, ? extends R> yieldingFunction) { return (Either4<LT1,LT2,LT3,R>)MonadicValue.super.forEach2(value1, filterFunction, yieldingFunction); } /* (non-Javadoc) * @see com.aol.cyclops2.types.MonadicValue#combineEager(com.aol.cyclops2.Monoid, com.aol.cyclops2.types.MonadicValue) */ @Override default Either4<LT1,LT2,LT3,RT> combineEager(Monoid<RT> monoid, MonadicValue<? extends RT> v2) { return (Either4<LT1,LT2,LT3,RT>)MonadicValue.super.combineEager(monoid, v2); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.Combiner#combine(com.aol.cyclops2.types.Value, * java.util.function.BiFunction) */ @Override default <T2, R> Either4<LT1, LT2, LT3, R> combine(final Value<? extends T2> app, final BiFunction<? super RT, ? super T2, ? extends R> fn) { return (Either4<LT1, LT2, LT3, R>) MonadicValue.super.combine(app, fn); } /* * (non-Javadoc) * * @see * com.aol.cyclops2.types.Combiner#combine(java.util.function.BinaryOperator, * com.aol.cyclops2.types.Combiner) */ @Override default Either4<LT1, LT2, LT3, RT> zip(final BinaryOperator<Zippable<RT>> combiner, final Zippable<RT> app) { return (Either4<LT1, LT2, LT3, RT>) MonadicValue.super.zip(combiner, app); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.Zippable#zip(java.util.reactiveStream.Stream, * java.util.function.BiFunction) */ @Override default <U, R> Either4<LT1, LT2, LT3, R> zipS(final Stream<? extends U> other, final BiFunction<? super RT, ? super U, ? extends R> zipper) { return (Either4<LT1, LT2, LT3, R>) MonadicValue.super.zipS(other, zipper); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.Zippable#zip(java.util.reactiveStream.Stream) */ @Override default <U> Either4<LT1, LT2, LT3, Tuple2<RT, U>> zipS(final Stream<? extends U> other) { return (Either4) MonadicValue.super.zipS(other); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.Zippable#zip(java.lang.Iterable) */ @Override default <U> Either4<LT1, LT2, LT3, Tuple2<RT, U>> zip(final Iterable<? extends U> other) { return (Either4) MonadicValue.super.zip(other); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.Pure#unit(java.lang.Object) */ @Override <T> Either4<LT1, LT2,LT3, T> unit(T unit); /* * (non-Javadoc) * * @see com.aol.cyclops2.types.applicative.MonadicValue#zip(java.lang. * Iterable, java.util.function.BiFunction) */ @Override default <T2, R> Either4<LT1, LT2, LT3, R> zip(final Iterable<? extends T2> app, final BiFunction<? super RT, ? super T2, ? extends R> fn) { return (Either4<LT1, LT2, LT3, R>) MonadicValue.super.zip(app, fn); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.applicative.MonadicValue#zip(java.util. * function.BiFunction, org.reactivestreams.Publisher) */ @Override default <T2, R> Either4<LT1, LT2,LT3, R> zipP(final Publisher<? extends T2> app, final BiFunction<? super RT, ? super T2, ? extends R> fn) { return (Either4<LT1, LT2, LT3, R>) MonadicValue.super.zipP(app,fn); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.functor.BiTransformable#bipeek(java.util.function.Consumer, * java.util.function.Consumer) */ @Override default Either4<LT1, LT2, LT3, RT> bipeek(final Consumer<? super LT3> c1, final Consumer<? super RT> c2) { return (Either4<LT1, LT2, LT3, RT>) BiTransformable.super.bipeek(c1, c2); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.functor.BiTransformable#bicast(java.lang.Class, * java.lang.Class) */ @Override default <U1, U2> Either4<LT1, LT2,U1, U2> bicast(final Class<U1> type1, final Class<U2> type2) { return (Either4<LT1, LT2,U1, U2>) BiTransformable.super.bicast(type1, type2); } /* * (non-Javadoc) * * @see * com.aol.cyclops2.types.functor.BiTransformable#bitrampoline(java.util.function.Function, * java.util.function.Function) */ @Override default <R1, R2> Either4<LT1, LT2, R1, R2> bitrampoline( final Function<? super LT3, ? extends Trampoline<? extends R1>> mapper1, final Function<? super RT, ? extends Trampoline<? extends R2>> mapper2) { return (Either4<LT1,LT2, R1, R2>) BiTransformable.super.bitrampoline(mapper1, mapper2); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.functor.Transformable#cast(java.lang.Class) */ @Override default <U> Either4<LT1, LT2, LT3, U> cast(final Class<? extends U> type) { return (Either4<LT1, LT2, LT3, U>) MonadicValue.super.cast(type); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.functor.Transformable#peek(java.util.function.Consumer) */ @Override default Either4<LT1, LT2, LT3, RT> peek(final Consumer<? super RT> c) { return (Either4<LT1, LT2, LT3, RT>) MonadicValue.super.peek(c); } /* * (non-Javadoc) * * @see * com.aol.cyclops2.types.functor.Transformable#trampoline(java.util.function.Function) */ @Override default <R> Either4<LT1, LT2, LT3, R> trampoline(final Function<? super RT, ? extends Trampoline<? extends R>> mapper) { return (Either4<LT1, LT2, LT3, R>) MonadicValue.super.trampoline(mapper); } @AllArgsConstructor(access = AccessLevel.PRIVATE) final static class Lazy<ST, M,M2, PT> implements Either4<ST, M,M2, PT> { private final Eval<Either4<ST, M,M2, PT>> lazy; public Either4<ST, M,M2, PT> resolve() { return lazy.get() .visit(Either4::left1, Either4::left2,Either4::left3, Either4::right); } private static <ST, M,M2, PT> Lazy<ST, M,M2, PT> lazy(final Eval<Either4<ST, M,M2, PT>> lazy) { return new Lazy<>(lazy); } @Override public <R> Either4<ST, M,M2, R> map(final Function<? super PT, ? extends R> mapper) { return flatMap(t -> Either4.right(mapper.apply(t))); } @Override public <RT1> Either4<ST, M,M2, RT1> flatMap( final Function<? super PT, ? extends MonadicValue<? extends RT1>> mapper) { return Either4.fromLazy(lazy.map(m->m.flatMap(mapper))); } @Override public Maybe<PT> filter(final Predicate<? super PT> test) { return Maybe.fromEval(Eval.later(() -> resolve().filter(test))) .flatMap(Function.identity()); } @Override public Trampoline<Either4<ST,M,M2,PT>> toTrampoline() { Trampoline<Either4<ST,M,M2,PT>> trampoline = lazy.toTrampoline(); return new Trampoline<Either4<ST,M,M2,PT>>() { @Override public Either4<ST,M,M2,PT> get() { Either4<ST,M,M2,PT> either = lazy.get(); while (either instanceof Either4.Lazy) { either = ((Either4.Lazy<ST,M,M2,PT>) either).lazy.get(); } return either; } @Override public boolean complete(){ return false; } @Override public Trampoline<Either4<ST,M,M2,PT>> bounce() { Either4<ST,M,M2,PT> either = lazy.get(); if(either instanceof Either4.Lazy){ return either.toTrampoline(); } return Trampoline.done(either); } }; } @Override public PT get() { return trampoline().get(); } private Either4<ST,M,M2,PT> trampoline(){ Either4<ST,M,M2,PT> maybe = lazy.get(); while (maybe instanceof Lazy) { maybe = ((Lazy<ST,M,M2,PT>) maybe).lazy.get(); } return maybe; } @Override public ReactiveSeq<PT> stream() { return trampoline() .stream(); } @Override public Iterator<PT> iterator() { return trampoline() .iterator(); } @Override public <R> R visit(final Function<? super PT, ? extends R> present, final Supplier<? extends R> absent) { return trampoline() .visit(present, absent); } @Override public void subscribe(final Subscriber<? super PT> s) { lazy.get() .subscribe(s); } @Override public boolean test(final PT t) { return trampoline() .test(t); } @Override public <R> R visit(final Function<? super ST, ? extends R> first, final Function<? super M, ? extends R> second, final Function<? super M2, ? extends R> third, final Function<? super PT, ? extends R> primary) { return trampoline() .visit(first, second,third, primary); } @Override public Either4<ST, M, PT, M2> swap3() { return lazy(Eval.later(() -> resolve().swap3())); } @Override public Either4<ST, PT, M2, M> swap2() { return lazy(Eval.later(() -> resolve().swap2())); } @Override public Either4<PT, M,M2, ST> swap1() { return lazy(Eval.later(() -> resolve().swap1())); } @Override public boolean isRight() { return trampoline() .isRight(); } @Override public boolean isLeft1() { return trampoline() .isLeft1(); } @Override public boolean isLeft2() { return trampoline() .isLeft2(); } @Override public boolean isLeft3() { return trampoline() .isLeft3(); } @Override public <R1, R2> Either4<ST, M,R1, R2> bimap(final Function<? super M2, ? extends R1> fn1, final Function<? super PT, ? extends R2> fn2) { return lazy(Eval.later(() -> resolve().bimap(fn1, fn2))); } @Override public <T> Either4<ST, M, M2,T> unit(final T unit) { return Either4.right(unit); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.visit(Either4::left1,Either4::left2,Either4::left3,Either4::right).hashCode(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return this.visit(Either4::left1,Either4::left2,Either4::left3,Either4::right).equals(obj); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return trampoline().toString(); } } @AllArgsConstructor(access = AccessLevel.PRIVATE) static class Right<ST, M,M2, PT> implements Either4<ST, M,M2, PT> { private final Eval<PT> value; @Override public <R> Either4<ST, M, M2, R> map(final Function<? super PT, ? extends R> fn) { return new Right<ST, M, M2, R>( value.map(fn)); } @Override public Either4<ST, M,M2, PT> peek(final Consumer<? super PT> action) { return map(i -> { action.accept(i); return i; }); } @Override public Maybe<PT> filter(final Predicate<? super PT> test) { return Maybe.fromEval(Eval.later(() -> test.test(get()) ? Maybe.just(get()) : Maybe.<PT> none())) .flatMap(Function.identity()); } @Override public PT get() { return value.get(); } @Override public <RT1> Either4<ST, M, M2, RT1> flatMap( final Function<? super PT, ? extends MonadicValue<? extends RT1>> mapper) { Eval<? extends Either4<? extends ST, ? extends M, ? extends M2, ? extends RT1>> et = value.map(mapper.andThen(Either4::fromMonadicValue)); final Eval<Either4<ST, M, M2, RT1>> e3 = (Eval<Either4<ST, M, M2, RT1>>)et; return new Lazy<>( e3); } @Override public boolean isRight() { return true; } @Override public boolean isLeft1() { return false; } @Override public String toString() { return mkString(); } @Override public String mkString() { return "Either4.right[" + value.get() + "]"; } @Override public <R> R visit(final Function<? super ST, ? extends R> secondary, final Function<? super M, ? extends R> mid, final Function<? super M2, ? extends R> mid2,final Function<? super PT, ? extends R> primary) { return primary.apply(value.get()); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.applicative.MonadicValue#ap(com.aol. * cyclops2.types.Value, java.util.function.BiFunction) */ @Override public <T2, R> Either4<ST, M,M2, R> combine(final Value<? extends T2> app, final BiFunction<? super PT, ? super T2, ? extends R> fn) { return new Right<>( value.combine(app, fn)); } @Override public <R1, R2> Either4<ST,M, R1, R2> bimap(final Function<? super M2, ? extends R1> fn1, final Function<? super PT, ? extends R2> fn2) { return (Either4<ST, M,R1, R2>) this.map(fn2); } @Override public ReactiveSeq<PT> stream() { return value.stream(); } @Override public Iterator<PT> iterator() { return value.iterator(); } @Override public <R> R visit(final Function<? super PT, ? extends R> present, final Supplier<? extends R> absent) { return value.visit(present, absent); } @Override public void subscribe(final Subscriber<? super PT> s) { value.subscribe(s); } @Override public boolean test(final PT t) { return value.test(t); } @Override public <T> Either4<ST, M, M2, T> unit(final T unit) { return Either4.right(unit); } @Override public Either4<ST, M, PT, M2> swap3() { return new Left3<>(value); } @Override public Either4<ST, PT, M2, M> swap2() { return new Left2<>(value); } @Override public Either4<PT, M,M2, ST> swap1() { return new Left1<>( value); } @Override public boolean isLeft2() { return false; } @Override public boolean isLeft3() { return false; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if(obj instanceof Lazy){ return ((Lazy)obj).equals(this); } if (getClass() != obj.getClass()) return false; Right other = (Right) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } } @AllArgsConstructor(access = AccessLevel.PRIVATE) static class Left1<ST, M, M2,PT> implements Either4<ST, M,M2, PT> { private final Eval<ST> value; @Override public <R> Either4<ST, M, M2, R> map(final Function<? super PT, ? extends R> fn) { return (Either4<ST, M, M2,R>) this; } @Override public Either4<ST, M, M2, PT> peek(final Consumer<? super PT> action) { return this; } @Override public void subscribe(final Subscriber<? super PT> s) { s.onComplete(); } @Override public Maybe<PT> filter(final Predicate<? super PT> test) { return Maybe.none(); } @Override public PT get() { throw new NoSuchElementException( "Attempt to access right value on a Left Either4"); } @Override public <RT1> Either4<ST, M, M2, RT1> flatMap( final Function<? super PT, ? extends MonadicValue<? extends RT1>> mapper) { return (Either4) this; } @Override public boolean isRight() { return false; } @Override public boolean isLeft1() { return true; } @Override public boolean isLeft3() { return false; } @Override public String toString() { return mkString(); } @Override public String mkString() { return "Either4.left1[" + value.get() + "]"; } @Override public <R> R visit(final Function<? super ST, ? extends R> secondary, final Function<? super M, ? extends R> mid, final Function<? super M2, ? extends R> mid2, final Function<? super PT, ? extends R> primary) { return secondary.apply(value.get()); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.applicative.MonadicValue#ap(com.aol. * cyclops2.types.Value, java.util.function.BiFunction) */ @Override public <T2, R> Either4<ST, M, M2, R> combine(final Value<? extends T2> app, final BiFunction<? super PT, ? super T2, ? extends R> fn) { return (Either4<ST, M,M2, R>) this; } @Override public <R1, R2> Either4<ST, M,R1, R2> bimap(final Function<? super M2, ? extends R1> fn1, final Function<? super PT, ? extends R2> fn2) { return (Either4<ST,M, R1, R2>) this; } @Override public ReactiveSeq<PT> stream() { return ReactiveSeq.empty(); } @Override public Iterator<PT> iterator() { return Arrays.<PT> asList() .iterator(); } @Override public <R> R visit(final Function<? super PT, ? extends R> present, final Supplier<? extends R> absent) { return absent.get(); } @Override public boolean test(final PT t) { return false; } @Override public <T> Either4<ST, M,M2, T> unit(final T unit) { return Either4.right(unit); } @Override public Either4<ST, M,PT, M2> swap3() { return (Either4<ST, M,PT, M2>) this; } @Override public Either4<ST, PT,M2, M> swap2() { return (Either4<ST, PT,M2, M>) this; } @Override public Either4<PT, M,M2, ST> swap1() { return new Right<>( value); } @Override public boolean isLeft2() { return false; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if(obj instanceof Lazy){ return ((Lazy)obj).equals(this); } if (getClass() != obj.getClass()) return false; Left1 other = (Left1) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } } @AllArgsConstructor(access = AccessLevel.PRIVATE) static class Left2<ST, M,M2, PT> implements Either4<ST, M, M2, PT> { private final Eval<M> value; @Override public <R> Either4<ST, M, M2,R> map(final Function<? super PT, ? extends R> fn) { return (Either4<ST, M, M2,R>) this; } @Override public Either4<ST, M, M2, PT> peek(final Consumer<? super PT> action) { return this; } @Override public Maybe<PT> filter(final Predicate<? super PT> test) { return Maybe.none(); } @Override public PT get() { throw new NoSuchElementException( "Attempt to access right value on a Middle Either4"); } @Override public void subscribe(final Subscriber<? super PT> s) { s.onComplete(); } @Override public <RT1> Either4<ST, M, M2,RT1> flatMap( final Function<? super PT, ? extends MonadicValue<? extends RT1>> mapper) { return (Either4) this; } @Override public boolean isRight() { return false; } @Override public boolean isLeft1() { return false; } @Override public String toString() { return mkString(); } @Override public String mkString() { return "Either4.left2[" + value.get() + "]"; } @Override public <R> R visit(final Function<? super ST, ? extends R> secondary, final Function<? super M, ? extends R> mid1, final Function<? super M2, ? extends R> mid2, final Function<? super PT, ? extends R> primary) { return mid1.apply(value.get()); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.applicative.MonadicValue#ap(com.aol. * cyclops2.types.Value, java.util.function.BiFunction) */ @Override public <T2, R> Either4<ST, M, M2,R> combine(final Value<? extends T2> app, final BiFunction<? super PT, ? super T2, ? extends R> fn) { return (Either4<ST, M, M2,R>) this; } @Override public <R1, R2> Either4<ST, M, R1, R2> bimap(final Function<? super M2, ? extends R1> fn1, final Function<? super PT, ? extends R2> fn2) { return (Either4<ST, M,R1, R2>) this; } @Override public ReactiveSeq<PT> stream() { return ReactiveSeq.empty(); } @Override public Iterator<PT> iterator() { return Arrays.<PT> asList() .iterator(); } @Override public <R> R visit(final Function<? super PT, ? extends R> present, final Supplier<? extends R> absent) { return absent.get(); } @Override public boolean test(final PT t) { return false; } @Override public <T> Either4<ST, M,M2, T> unit(final T unit) { return Either4.right(unit); } @Override public Either4<ST, M, PT,M2> swap3() { return (Either4<ST, M, PT,M2>) this; } @Override public Either4<ST, PT,M2, M> swap2() { return new Right<>( value); } @Override public Either4<PT, M, M2,ST> swap1() { return (Either4<PT, M,M2, ST>) this; } @Override public boolean isLeft2() { return true; } @Override public boolean isLeft3() { return false; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if(obj instanceof Lazy){ return ((Lazy)obj).equals(this); } if (getClass() != obj.getClass()) return false; Left2 other = (Left2) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } } @AllArgsConstructor(access = AccessLevel.PRIVATE) static class Left3<ST, M,M2, PT> implements Either4<ST, M, M2, PT> { private final Eval<M2> value; @Override public <R> Either4<ST, M, M2,R> map(final Function<? super PT, ? extends R> fn) { return (Either4<ST, M, M2,R>) this; } @Override public Either4<ST, M, M2, PT> peek(final Consumer<? super PT> action) { return this; } @Override public Maybe<PT> filter(final Predicate<? super PT> test) { return Maybe.none(); } @Override public void subscribe(final Subscriber<? super PT> s) { s.onComplete(); } @Override public PT get() { throw new NoSuchElementException( "Attempt to access right value on a Middle Either4"); } @Override public <RT1> Either4<ST, M, M2,RT1> flatMap( final Function<? super PT, ? extends MonadicValue<? extends RT1>> mapper) { return (Either4) this; } @Override public boolean isRight() { return false; } @Override public boolean isLeft1() { return false; } @Override public boolean isLeft3() { return true; } @Override public String toString() { return mkString(); } @Override public String mkString() { return "Either4.left3[" + value.get() + "]"; } @Override public <R> R visit(final Function<? super ST, ? extends R> secondary, final Function<? super M, ? extends R> mid1, final Function<? super M2, ? extends R> mid2, final Function<? super PT, ? extends R> primary) { return mid2.apply(value.get()); } /* * (non-Javadoc) * * @see com.aol.cyclops2.types.applicative.MonadicValue#ap(com.aol. * cyclops2.types.Value, java.util.function.BiFunction) */ @Override public <T2, R> Either4<ST, M, M2,R> combine(final Value<? extends T2> app, final BiFunction<? super PT, ? super T2, ? extends R> fn) { return (Either4<ST, M, M2,R>) this; } @Override public <R1, R2> Either4<ST, M, R1, R2> bimap(final Function<? super M2, ? extends R1> fn1, final Function<? super PT, ? extends R2> fn2) { return (Either4<ST, M,R1, R2>) this; } @Override public ReactiveSeq<PT> stream() { return ReactiveSeq.empty(); } @Override public Iterator<PT> iterator() { return Arrays.<PT> asList() .iterator(); } @Override public <R> R visit(final Function<? super PT, ? extends R> present, final Supplier<? extends R> absent) { return absent.get(); } @Override public boolean test(final PT t) { return false; } @Override public <T> Either4<ST, M,M2, T> unit(final T unit) { return Either4.right(unit); } @Override public Either4<ST, M, PT,M2> swap3() { return new Right<>( value); } @Override public Either4<ST, PT,M2, M> swap2() { return (Either4<ST, PT,M2, M>)this; } @Override public Either4<PT, M, M2,ST> swap1() { return (Either4<PT, M,M2, ST>) this; } @Override public boolean isLeft2() { return false; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if(obj instanceof Lazy){ return ((Lazy)obj).equals(this); } if (getClass() != obj.getClass()) return false; Left3 other = (Left3) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } } public static <L1,L2,L3,T> Either4<L1,L2,L3,T> narrowK3(final Higher4<either4, L1,L2,L3,T> xor) { return (Either4<L1,L2,L3,T>)xor; } public static <L1,L2,L3,T> Either4<L1,L2,L3,T> narrowK(final Higher<Higher<Higher<Higher<either4, L1>,L2>,L3>,T> xor) { return (Either4<L1,L2,L3,T>)xor; } default Active<Higher<Higher<Higher<either4, LT1>, LT2>,LT3>,RT> allTypeclasses(){ return Active.of(this,Instances.definitions()); } default <W2,R> Nested<Higher<Higher<Higher<either4, LT1>, LT2>,LT3>,W2,R> mapM(Function<? super RT,? extends Higher<W2,R>> fn, InstanceDefinitions<W2> defs){ return Nested.of(map(fn), Instances.definitions(), defs); } public static class Instances { public static <L1,L2,L3> InstanceDefinitions<Higher<Higher<Higher<either4, L1>, L2>,L3>> definitions() { return new InstanceDefinitions<Higher<Higher<Higher<either4, L1>, L2>,L3>>() { @Override public <T, R> Functor<Higher<Higher<Higher<either4, L1>, L2>,L3>> functor() { return Instances.functor(); } @Override public <T> Pure<Higher<Higher<Higher<either4, L1>, L2>,L3>> unit() { return Instances.unit(); } @Override public <T, R> Applicative<Higher<Higher<Higher<either4, L1>, L2>,L3>> applicative() { return Instances.applicative(); } @Override public <T, R> Monad<Higher<Higher<Higher<either4, L1>, L2>,L3>> monad() { return Instances.monad(); } @Override public <T, R> Maybe<MonadZero<Higher<Higher<Higher<either4, L1>, L2>,L3>>> monadZero() { return Maybe.just(Instances.monadZero()); } @Override public <T> Maybe<MonadPlus<Higher<Higher<Higher<either4, L1>, L2>,L3>>> monadPlus() { return Maybe.none(); } @Override public <T> MonadRec<Higher<Higher<Higher<either4, L1>, L2>,L3>> monadRec() { return Instances.monadRec(); } @Override public <T> Maybe<MonadPlus<Higher<Higher<Higher<either4, L1>, L2>,L3>>> monadPlus(Monoid<Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T>> m) { return Maybe.none(); } @Override public <C2, T> Maybe<Traverse<Higher<Higher<Higher<either4, L1>, L2>,L3>>> traverse() { return Maybe.just(Instances.traverse()); } @Override public <T> Maybe<Foldable<Higher<Higher<Higher<either4, L1>, L2>,L3>>> foldable() { return Maybe.just(Instances.foldable()); } @Override public <T> Maybe<Comonad<Higher<Higher<Higher<either4, L1>, L2>,L3>>> comonad() { return Maybe.just(Instances.comonad()); } @Override public <T> Maybe<Unfoldable<Higher<Higher<Higher<either4, L1>, L2>,L3>>> unfoldable() { return Maybe.none(); } }; } public static <L1,L2,L3> Functor<Higher<Higher<Higher<either4, L1>, L2>,L3>> functor() { return new Functor<Higher<Higher<Higher<either4, L1>, L2>,L3>>() { @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> map(Function<? super T, ? extends R> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return narrowK(ds).map(fn); } }; } public static <L1,L2,L3> Pure<Higher<Higher<Higher<either4, L1>, L2>,L3>> unit() { return new Pure<Higher<Higher<Higher<either4, L1>, L2>,L3>>() { @Override public <T> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> unit(T value) { return Either4.right(value); } }; } public static <L1,L2,L3> Applicative<Higher<Higher<Higher<either4, L1>, L2>,L3>> applicative() { return new Applicative<Higher<Higher<Higher<either4, L1>, L2>,L3>>() { @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> ap(Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, ? extends Function<T, R>> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> apply) { return narrowK(fn).flatMap(x -> narrowK(apply).map(x)); } @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> map(Function<? super T, ? extends R> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return Instances.<L1,L2,L3>functor().map(fn,ds); } @Override public <T> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> unit(T value) { return Instances.<L1,L2,L3>unit().unit(value); } }; } public static <L1,L2,L3> Monad<Higher<Higher<Higher<either4, L1>, L2>,L3>> monad() { return new Monad<Higher<Higher<Higher<either4, L1>, L2>,L3>>() { @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> ap(Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, ? extends Function<T, R>> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> apply) { return Instances.<L1,L2,L3>applicative().ap(fn,apply); } @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> map(Function<? super T, ? extends R> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return Instances.<L1,L2,L3>functor().map(fn,ds); } @Override public <T> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> unit(T value) { return Instances.<L1,L2,L3>unit().unit(value); } @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> flatMap(Function<? super T, ? extends Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R>> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return narrowK(ds).flatMap(fn.andThen(m->narrowK(m))); } }; } public static <L1,L2,L3,T,R> MonadRec<Higher<Higher<Higher<either4, L1>, L2>,L3>> monadRec(){ return new MonadRec<Higher<Higher<Higher<either4, L1>, L2>,L3>>(){ @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> tailRec(T initial, Function<? super T, ? extends Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, ? extends Xor<T, R>>> fn) { return narrowK(fn.apply(initial)).flatMap( eval -> eval.visit(s->narrowK(tailRec(s,fn)),p->Eval.now(p))); } }; } public static <L1,L2,L3> MonadZero<Higher<Higher<Higher<either4, L1>, L2>,L3>> monadZero() { return new MonadZero<Higher<Higher<Higher<either4, L1>, L2>,L3>>() { @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> ap(Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, ? extends Function<T, R>> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> apply) { return Instances.<L1,L2,L3>applicative().ap(fn,apply); } @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> map(Function<? super T, ? extends R> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return Instances.<L1,L2,L3>functor().map(fn,ds); } @Override public Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, ?> zero() { return Either4.left1(null); } @Override public <T> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> unit(T value) { return Instances.<L1,L2,L3>unit().unit(value); } @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> flatMap(Function<? super T, ? extends Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R>> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return Instances.<L1,L2,L3>monad().flatMap(fn,ds); } }; } public static <L1,L2,L3> Traverse<Higher<Higher<Higher<either4, L1>, L2>,L3>> traverse() { return new Traverse<Higher<Higher<Higher<either4, L1>, L2>,L3>> () { @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> ap(Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, ? extends Function<T, R>> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> apply) { return Instances.<L1,L2,L3>applicative().ap(fn,apply); } @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> map(Function<? super T, ? extends R> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return Instances.<L1,L2,L3>functor().map(fn,ds); } @Override public <T> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> unit(T value) { return Instances.<L1, L2,L3>unit().unit(value); } @Override public <C2, T, R> Higher<C2, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R>> traverseA(Applicative<C2> applicative, Function<? super T, ? extends Higher<C2, R>> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { Either4<L1,L2,L3,T> maybe = narrowK(ds); return maybe.visit(left-> applicative.unit(Either4.<L1,L2,L3,R>left1(left)), middle1->applicative.unit(Either4.<L1,L2,L3,R>left2(middle1)), middle2->applicative.unit(Either4.<L1,L2,L3,R>left3(middle2)), right->applicative.map(m->Either4.right(m), fn.apply(right))); } @Override public <C2, T> Higher<C2, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T>> sequenceA(Applicative<C2> applicative, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, Higher<C2, T>> ds) { return traverseA(applicative,Function.identity(),ds); } }; } public static <L1,L2,L3> Foldable<Higher<Higher<Higher<either4, L1>, L2>,L3>> foldable() { return new Foldable<Higher<Higher<Higher<either4, L1>, L2>,L3>>() { @Override public <T> T foldRight(Monoid<T> monoid, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return narrowK(ds).foldRight(monoid); } @Override public <T> T foldLeft(Monoid<T> monoid, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return narrowK(ds).foldLeft(monoid); } }; } public static <L1,L2,L3> Comonad<Higher<Higher<Higher<either4, L1>, L2>,L3>> comonad() { return new ComonadByPure<Higher<Higher<Higher<either4, L1>, L2>,L3>>() { @Override public <T> T extract(Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return narrowK(ds).get(); } @Override public <T, R> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, R> map(Function<? super T, ? extends R> fn, Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> ds) { return Instances.<L1,L2,L3>functor().map(fn,ds); } @Override public <T> Higher<Higher<Higher<Higher<either4, L1>, L2>,L3>, T> unit(T value) { return Instances.<L1, L2,L3>unit().unit(value); } }; } } }
package de.bwaldvogel.liblinear; import static de.bwaldvogel.liblinear.Linear.info; /** * Trust Region Newton Method optimization */ class Tron { private final Function fun_obj; private final double eps; private final int max_iter; private final double eps_cg; public Tron(Function fun_obj, double eps, int max_iter, double eps_cg) { this.fun_obj = fun_obj; this.eps = eps; this.max_iter = max_iter; this.eps_cg = eps_cg; } void tron(double[] w) { // Parameters for updating the iterates. double eta0 = 1e-4, eta1 = 0.25, eta2 = 0.75; // Parameters for updating the trust region size delta. double sigma1 = 0.25, sigma2 = 0.5, sigma3 = 4; int n = fun_obj.get_nr_variable(); int i, cg_iter; double delta, snorm, one = 1.0; double alpha, f, fnew, prered, actred, gs; int search = 1, iter = 1; double[] s = new double[n]; double[] r = new double[n]; double[] g = new double[n]; // calculate gradient norm at w=0 for stopping condition. double[] w0 = new double[n]; for (i = 0; i < n; i++) w0[i] = 0; fun_obj.fun(w0); fun_obj.grad(w0, g); double gnorm0 = euclideanNorm(g); f = fun_obj.fun(w); fun_obj.grad(w, g); delta = euclideanNorm(g); double gnorm = delta; if (gnorm <= eps * gnorm0) search = 0; iter = 1; double[] w_new = new double[n]; while (iter <= max_iter && search != 0) { cg_iter = trcg(delta, g, s, r); System.arraycopy(w, 0, w_new, 0, n); daxpy(one, s, w_new); gs = dot(g, s); prered = -0.5 * (gs - dot(s, r)); fnew = fun_obj.fun(w_new); // Compute the actual reduction. actred = f - fnew; // On the first iteration, adjust the initial step bound. snorm = euclideanNorm(s); if (iter == 1) delta = Math.min(delta, snorm); // Compute prediction alpha*snorm of the step. if (fnew - f - gs <= 0) alpha = sigma3; else alpha = Math.max(sigma1, -0.5 * (gs / (fnew - f - gs))); // Update the trust region bound according to the ratio of actual to // predicted reduction. if (actred < eta0 * prered) delta = Math.min(Math.max(alpha, sigma1) * snorm, sigma2 * delta); else if (actred < eta1 * prered) delta = Math.max(sigma1 * delta, Math.min(alpha * snorm, sigma2 * delta)); else if (actred < eta2 * prered) delta = Math.max(sigma1 * delta, Math.min(alpha * snorm, sigma3 * delta)); else delta = Math.max(delta, Math.min(alpha * snorm, sigma3 * delta)); info("iter %2d act %5.3e pre %5.3e delta %5.3e f %5.3e |g| %5.3e CG %3d%n", iter, actred, prered, delta, f, gnorm, cg_iter); if (actred > eta0 * prered) { iter++; System.arraycopy(w_new, 0, w, 0, n); f = fnew; fun_obj.grad(w, g); gnorm = euclideanNorm(g); if (gnorm <= eps * gnorm0) break; } if (f < -1.0e+32) { info("WARNING: f < -1.0e+32%n"); break; } if (prered <= 0) { info("WARNING: prered <= 0%n"); break; } if (Math.abs(actred) <= 1.0e-12 * Math.abs(f) && Math.abs(prered) <= 1.0e-12 * Math.abs(f)) { info("WARNING: actred and prered too small%n"); break; } } } private int trcg(double delta, double[] g, double[] s, double[] r) { int n = fun_obj.get_nr_variable(); double one = 1; double[] d = new double[n]; double[] Hd = new double[n]; double rTr, rnewTrnew, cgtol; for (int i = 0; i < n; i++) { s[i] = 0; r[i] = -g[i]; d[i] = r[i]; } cgtol = eps_cg * euclideanNorm(g); int cg_iter = 0; rTr = dot(r, r); while (true) { if (euclideanNorm(r) <= cgtol) break; cg_iter++; fun_obj.Hv(d, Hd); double alpha = rTr / dot(d, Hd); daxpy(alpha, d, s); if (euclideanNorm(s) > delta) { info("cg reaches trust region boundary%n"); alpha = -alpha; daxpy(alpha, d, s); double std = dot(s, d); double sts = dot(s, s); double dtd = dot(d, d); double dsq = delta * delta; double rad = Math.sqrt(std * std + dtd * (dsq - sts)); if (std >= 0) alpha = (dsq - sts) / (std + rad); else alpha = (rad - std) / dtd; daxpy(alpha, d, s); alpha = -alpha; daxpy(alpha, Hd, r); break; } alpha = -alpha; daxpy(alpha, Hd, r); rnewTrnew = dot(r, r); double beta = rnewTrnew / rTr; scale(beta, d); daxpy(one, r, d); rTr = rnewTrnew; } return (cg_iter); } /** * constant times a vector plus a vector * * <pre> * vector2 += constant * vector1 * </pre> * * @since 1.8 */ private static void daxpy(double constant, double vector1[], double vector2[]) { if (constant == 0) return; assert vector1.length == vector2.length; for (int i = 0; i < vector1.length; i++) { vector2[i] += constant * vector1[i]; } } /** * returns the dot product of two vectors * * @since 1.8 */ private static double dot(double vector1[], double vector2[]) { double product = 0; assert vector1.length == vector2.length; for (int i = 0; i < vector1.length; i++) { product += vector1[i] * vector2[i]; } return product; } /** * returns the euclidean norm of a vector * * @since 1.8 */ private static double euclideanNorm(double vector[]) { int n = vector.length; if (n < 1) { return 0; } if (n == 1) { return Math.abs(vector[0]); } // this algorithm is (often) more accurate than just summing up the squares and taking the square-root afterwards double scale = 0; // scaling factor that is factored out double sum = 1; // basic sum of squares from which scale has been factored out for (int i = 0; i < n; i++) { if (vector[i] != 0) { double abs = Math.abs(vector[i]); // try to get the best scaling factor if (scale < abs) { double t = scale / abs; sum = 1 + sum * (t * t); scale = abs; } else { double t = abs / scale; sum += t * t; } } } return scale * Math.sqrt(sum); } /** * scales a vector by a constant * * @since 1.8 */ private static void scale(double constant, double vector[]) { if (constant == 1.0) return; for (int i = 0; i < vector.length; i++) { vector[i] *= constant; } } }
package de.movope.web; import de.movope.game.ChessGame; import de.movope.game.Color; import de.movope.game.Move; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import static com.google.common.base.Preconditions.checkNotNull; @RestController public class GameController { @Autowired private ChessGameRepository gameRepository; @RequestMapping(value = "/game/{gameId}", method = RequestMethod.PUT) public ResponseEntity<?> startNewGame(@PathVariable String gameId) { ChessGame game = ChessGame.createNew(gameId); gameRepository.save(game); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(ServletUriComponentsBuilder .fromCurrentRequest().path("/{id}") .buildAndExpand(gameId).toUri()); return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED); } @RequestMapping(value = "/game/{gameId}/board", method = RequestMethod.GET) public ChessBoardView getBoardFromGame(@PathVariable String gameId) { ChessGame game = gameRepository.findById(gameId); if (game == null) { throw new GameNotFoundException(gameId); } checkNotNull(game, "Chessgame with id=" + gameId + " not found."); return new ChessBoardView(game.getBoard()); } @RequestMapping(value = "/game/{gameId}/move", method = RequestMethod.POST) public HttpStatus makeMove(@PathVariable String gameId, @RequestBody MoveResource moveRessource) { ChessGame game = gameRepository.findById(gameId); checkNotNull(game, "Chessgame with id=" + gameId + " not found."); Move move = Move.create(moveRessource.getFrom(), moveRessource.getTo()); if (!game.isMovePossible(move, Color.WHITE)) { throw new IllegalStateException("Move can not be executed!"); } game.execute(move); game.executeNextMoveForComputer(); gameRepository.save(game); return HttpStatus.CREATED; } @RequestMapping("/game/delete") public void delete() { gameRepository.deleteAll(); } @ResponseStatus(HttpStatus.NOT_FOUND) class GameNotFoundException extends RuntimeException { public GameNotFoundException(String gameId) { super("could not find game '" + gameId + "'."); } } }
/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.control.*; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Random; import java.util.concurrent.Executors; import jssc.SerialPort; import jssc.SerialPortException; import jssc.SerialPortList; /** * The controller for the front-end program. * * @since October 13, 2016 * @author Ted Frohlich <ttf10@case.edu> * @author Abby Walker <amw138@case.edu> */ public class Controller { @FXML private Menu connectMenu; @FXML private ToggleGroup connectGroup; @FXML private LineChart eegChart; @FXML private LineChart ekgChart; @FXML private ToggleButton recordButton; private ObservableList<String> serialPortList; private SerialPort eegPort, ekgPort; private enum SignalType {EEG, EKG} private List<LineChart.Series> eegChannels; private LineChart.Series ekgChannel; private FileWriter fileWriter; /** * Construct a controller for the front-end program by performing the setup routine: * <ul> * 1. Detect serial ports. <br> * 2. Connect to the first port by default, if it exists. <br> * </ul> */ public Controller() { if (detectSerialPorts() && serialPortList.size() == 1) { connect(serialPortList.get(0), SignalType.EEG); } } /** * Get the appropriate serial port associated with the given signal type. * * @param signalType the signal type associated with the serial port * * @return a reference to {@link #eegPort} or {@link #ekgPort} depending on the value of <code>signalType</code>; <code>null</code> is return by default if something went wrong */ private SerialPort getPortFor(SignalType signalType) { switch (signalType) { case EEG: return eegPort; case EKG: return ekgPort; default: return null; } } /** * Set the appropriate serial port associated with the given signal type to a new serial port with the specified port name. * * @param signalType the signal type associated with the serial port * @param portName the name of the serial port */ private void setPortFor(SignalType signalType, String portName) { switch (signalType) { case EEG: eegPort = new SerialPort(portName); return; case EKG: ekgPort = new SerialPort(portName); return; default: // do nothing } } /** * Initialize the list of detected ports. * * @return <code>true</code> if at least one serial port was detected; <code>false</code> otherwise */ private boolean detectSerialPorts() { serialPortList = FXCollections.observableArrayList(); serialPortList.addAll(SerialPortList.getPortNames()); return !serialPortList.isEmpty(); } /** * Connect to the specified serial port, and designate it for the given signal type. * * @param portName the name of the serial port * @param signalType the signal type associated with the serial port * * @return <code>true</code> if the serial port was successfully connected; <code>false</code> if there is already another port currently open, or just if something went wrong connecting this one */ private boolean connect(String portName, SignalType signalType) { boolean success = false; try { System.out.print("Connecting to serial port " + portName + "..."); final SerialPort port = getPortFor(signalType); if (portName == null) throw new NullPointerException("Can't connect to null port!"); if (port != null && port.isOpened()) throw new InterruptedException("Already connected!"); setPortFor(signalType, portName); success = port.openPort(); System.out.println("\t->\tSuccessfully connected!"); } catch (Exception e) { System.out.println("\t->\tCouldn't connect! " + e.getMessage()); } return success; } /** * Disconnect from the serial port. * * @return <code>true</code> if the serial port was successfully disconnected; <code>false</code> if none of the ports were connected to begin with, or just if something went wrong disconnecting this one */ private boolean disconnect() { boolean success = false; try { System.out.print("Disconnecting from serial port " + eegPort.getPortName() + "..."); success = eegPort.closePort(); eegPort = null; if (success) System.out.println("\t->\tSuccessfully disconnected!"); } catch (Exception e) { System.out.println("\t->\tAlready disconnected!"); } return success; } /** * Get whether data recording is currently toggled 'on' in the front-end. * * @return <code>true</code> if the 'record' toggle button has been pushed; <code>false</code> if no data recording is currently happening */ private boolean isRecording() { return recordButton.isSelected(); } @FXML public void connect(ActionEvent actionEvent) { connect("COM5", SignalType.EEG); // TODO: Figure out how to get item text from action event. } @FXML public void onMouseEnteredRecordButton() { recordButton.setText((isRecording() ? "Stop" : "Start") + " Recording"); } @FXML public void onMouseExitedRecordButton() { recordButton.setText("Record" + (isRecording() ? "ing..." : "")); } @FXML public void onMousePressedRecordButton() { recordButton.setStyle("-fx-background-color: darkred"); } @FXML public void onMouseReleasedRecordButton() { recordButton.setStyle("-fx-background-color: red"); } @FXML public void onConnectMenuValidation(Event event) { connectMenu.getItems().clear(); String[] portNames = SerialPortList.getPortNames(); if (portNames.length == 0) { MenuItem dummy = new MenuItem("<no ports available>"); dummy.setDisable(true); connectMenu.getItems().add(dummy); return; } for (String portName : portNames) { connectMenu.getItems().add(new RadioMenuItem(portName)); } } @FXML public void record() { if (isRecording()) { // start recording... //TODO: Run thread for saving data to file. } else { // stop recording... //TODO: End thread for saving data to file. } onMouseEnteredRecordButton(); // indicate what next click would do } @FXML public void confirmExit() throws Exception { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirm Exit"); alert.setHeaderText("Are you sure you want to exit?"); ButtonType result = alert.showAndWait().orElse(ButtonType.CANCEL); if (result == ButtonType.OK) { disconnect(); Platform.exit(); } } /** * A controller for the EEG tab. */ private class EEGController { @FXML private LineChart<String, Number> leftRostralChart, rightRostralChart, leftCaudalChart, rightCaudalChart; private CategoryAxis xAxis; private NumberAxis yAxis; private ObservableList<String> xAxisCategories; private LineChart.Series<String, Number>[] electrodes; private ObservableList<LineChart.Data<String, Number>> leftRostralList, rightRostralList, leftCaudalList, rightCaudalList; private int lastObservedChangelistSize, changesBeforeUpdate = 10; private Task<Date> chartUpdateTask; private EEGController() { initObservableLists(); getObservableLists().forEach(list -> list.addListener(dataListChangeListener())); initAxes(); xAxis.setCategories(xAxisCategories); // xAxis.setAutoRanging(false); //TODO: instantiate and add data series initChartUpdateTask(); Executors.newSingleThreadExecutor().submit(chartUpdateTask); } private void initAxes() { xAxis = new CategoryAxis(); yAxis = new NumberAxis(); xAxis.setLabel("Time (sec)"); yAxis.setLabel("Relative Amplitude"); } private void initChartUpdateTask() { chartUpdateTask = new Task<Date>() { @Override protected Date call() throws Exception { while (true) { try { Thread.sleep(1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } if (isCancelled()) break; updateValue(new Date()); } return new Date(); } }; chartUpdateTask.valueProperty().addListener(new ChangeListener<Date>() { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); //TODO: eventually just want seconds Random random = new Random(); @Override public void changed(ObservableValue<? extends Date> observableDate, Date oldDate, Date newDate) { String strDate = dateFormat.format(newDate); xAxisCategories.add(strDate); getObservableLists().forEach(list -> list.add(new LineChart.Data(strDate, newDate.getMinutes() + random.nextInt(100500)))); } }); } private void initObservableLists() { leftRostralList = rightRostralList = leftCaudalList = rightCaudalList = FXCollections.observableArrayList(); xAxisCategories = FXCollections.observableArrayList(); } private List<LineChart<String, Number>> getCharts() { List<LineChart<String, Number>> charts = Collections.emptyList(); charts.add(leftRostralChart); charts.add(rightRostralChart); charts.add(leftCaudalChart); charts.add(rightCaudalChart); return charts; } private List<ObservableList<LineChart.Data<String, Number>>> getObservableLists() { List<ObservableList<LineChart.Data<String, Number>>> lists = Collections.emptyList(); lists.add(leftRostralList); lists.add(rightRostralList); lists.add(leftCaudalList); lists.add(rightCaudalList); return lists; } private ListChangeListener<LineChart.Data<String, Number>> dataListChangeListener() { return change -> { if (change.getList().size() - lastObservedChangelistSize > changesBeforeUpdate) { lastObservedChangelistSize += changesBeforeUpdate; xAxis.getCategories().remove(0, changesBeforeUpdate); } }; } } /** * A controller for the EKG tab. */ private class EKGController { //TODO: } }
/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.control.*; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Random; import java.util.concurrent.Executors; import jssc.SerialPort; import jssc.SerialPortException; import jssc.SerialPortList; /** * The controller for the front-end program. * * @since October 13, 2016 * @author Ted Frohlich <ttf10@case.edu> * @author Abby Walker <amw138@case.edu> */ public class Controller { @FXML private Menu connectMenu; @FXML public ToggleGroup connectGroup; @FXML private ToggleButton recordButton; private FileWriter fileWriter; private SerialPort serialPort; private ObservableList<String> serialPortList; /** * Construct a controller for the front-end program by performing the setup routine: * <ul> * 1. Detect serial ports. <br> * 2. Connect to the first port by default, if it exists. <br> * </ul> */ public Controller() { if (detectSerialPorts() && serialPortList.size() == 1) { connect(serialPortList.get(0)); } } @FXML private void confirmExit() throws Exception { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirm Exit"); alert.setHeaderText("Are you sure you want to exit?"); ButtonType result = alert.showAndWait().orElse(ButtonType.CANCEL); if (result == ButtonType.OK) { disconnect(); Platform.exit(); } } @FXML public void connect(ActionEvent actionEvent) { connect("COM5"); // TODO: Figure out how to get item text from action event. } @FXML private void onMouseEnteredRecordButton() { recordButton.setText((isRecording() ? "Stop" : "Start") + " Recording"); } @FXML private void onMouseExitedRecordButton() { recordButton.setText("Record" + (isRecording() ? "ing..." : "")); } @FXML private void onMousePressedRecordButton() { recordButton.setStyle("-fx-background-color: darkred"); } @FXML private void onMouseReleasedRecordButton() { recordButton.setStyle("-fx-background-color: red"); } @FXML public void onShowingConnectMenu(Event event) { connectMenu.getItems().clear(); String[] portNames = SerialPortList.getPortNames(); if (portNames.length == 0) { MenuItem dummy = new MenuItem("<no ports available>"); dummy.setDisable(true); connectMenu.getItems().add(dummy); return; } for (String portName : portNames) { connectMenu.getItems().add(new RadioMenuItem(portName)); } } @FXML private void record() { if (isRecording()) { // start recording... //TODO: Run thread for saving data to file. } else { // stop recording... //TODO: End thread for saving data to file. } onMouseEnteredRecordButton(); // indicate what next click would do } /** * Connect to the specified serial port. * * @param portName the name of the serial port * @return <code>true</code> if the serial port was successfully connected; <code>false</code> if there is already another port currently open, or just if something went wrong connecting this one */ private boolean connect(String portName) { boolean success = false; try { System.out.print("Connecting to serial port " + portName + "..."); if (serialPort != null && serialPort.isOpened()) { System.out.println("\t->\tAlready connected!"); } else { serialPort = new SerialPort(portName); success = serialPort.openPort(); System.out.println("\t->\tSuccessfully connected!"); } } catch (SerialPortException e) { System.out.println("\t->\tCouldn't connect!"); } return success; } /** * Initialize the list of detected ports. * * @return <code>true</code> if at least one serial port was detected; <code>false</code> otherwise */ private boolean detectSerialPorts() { serialPortList = FXCollections.observableArrayList(); serialPortList.addAll(SerialPortList.getPortNames()); return !serialPortList.isEmpty(); } /** * Disconnect from the serial port. * * @return <code>true</code> if the serial port was successfully disconnected; <code>false</code> if none of the ports were connected to begin with, or just if something went wrong disconnecting this one */ private boolean disconnect() { boolean success = false; try { System.out.print("Disconnecting from serial port " + serialPort.getPortName() + "..."); success = serialPort.closePort(); serialPort = null; if (success) System.out.println("\t->\tSuccessfully disconnected!"); } catch (Exception e) { System.out.println("\t->\tAlready disconnected!"); } return success; } /** * Get whether data recording is currently toggled 'on' in the front-end. * * @return <code>true</code> if the 'record' toggle button has been pushed; <code>false</code> if no data recording is currently happening */ private boolean isRecording() { return recordButton.isSelected(); } /** * A controller for the EEG tab. */ private class EEGController { @FXML private LineChart<String, Number> leftRostralChart, rightRostralChart, leftCaudalChart, rightCaudalChart; private CategoryAxis xAxis; private NumberAxis yAxis; private ObservableList<String> xAxisCategories; private LineChart.Series<String, Number>[] electrodes; private ObservableList<LineChart.Data<String, Number>> leftRostralList, rightRostralList, leftCaudalList, rightCaudalList; private int lastObservedChangelistSize, changesBeforeUpdate = 10; private Task<Date> chartUpdateTask; private EEGController() { initObservableLists(); getObservableLists().forEach(list -> list.addListener(dataListChangeListener())); initAxes(); xAxis.setCategories(xAxisCategories); // xAxis.setAutoRanging(false); //TODO: instantiate and add data series initChartUpdateTask(); Executors.newSingleThreadExecutor().submit(chartUpdateTask); } private void initAxes() { xAxis = new CategoryAxis(); yAxis = new NumberAxis(); xAxis.setLabel("Time (sec)"); yAxis.setLabel("Relative Amplitude"); } private void initChartUpdateTask() { chartUpdateTask = new Task<Date>() { @Override protected Date call() throws Exception { while (true) { try { Thread.sleep(1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } if (isCancelled()) break; updateValue(new Date()); } return new Date(); } }; chartUpdateTask.valueProperty().addListener(new ChangeListener<Date>() { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); //TODO: eventually just want seconds Random random = new Random(); @Override public void changed(ObservableValue<? extends Date> observableDate, Date oldDate, Date newDate) { String strDate = dateFormat.format(newDate); xAxisCategories.add(strDate); getObservableLists().forEach(list -> list.add(new LineChart.Data(strDate, newDate.getMinutes() + random.nextInt(100500)))); } }); } private void initObservableLists() { leftRostralList = rightRostralList = leftCaudalList = rightCaudalList = FXCollections.observableArrayList(); xAxisCategories = FXCollections.observableArrayList(); } private List<LineChart<String, Number>> getCharts() { List<LineChart<String, Number>> charts = Collections.emptyList(); charts.add(leftRostralChart); charts.add(rightRostralChart); charts.add(leftCaudalChart); charts.add(rightCaudalChart); return charts; } private List<ObservableList<LineChart.Data<String, Number>>> getObservableLists() { List<ObservableList<LineChart.Data<String, Number>>> lists = Collections.emptyList(); lists.add(leftRostralList); lists.add(rightRostralList); lists.add(leftCaudalList); lists.add(rightCaudalList); return lists; } private ListChangeListener<LineChart.Data<String, Number>> dataListChangeListener() { return change -> { if (change.getList().size() - lastObservedChangelistSize > changesBeforeUpdate) { lastObservedChangelistSize += changesBeforeUpdate; xAxis.getCategories().remove(0, changesBeforeUpdate); } }; } } /** * A controller for the EKG tab. */ private class EKGController { //TODO: } }
package hudson.plugins.jira; import hudson.Util; import hudson.model.AbstractProject; import hudson.plugins.jira.soap.JiraSoapService; import hudson.plugins.jira.soap.JiraSoapServiceService; import hudson.plugins.jira.soap.JiraSoapServiceServiceLocator; import javax.xml.rpc.ServiceException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * Represents an external JIRA installation and configuration * needed to access this JIRA. * * @author Kohsuke Kawaguchi */ public class JiraSite { public URL url; /** * User name needed to login. Optional. */ public String userName; /** * Password needed to login. Optional. */ public String password; /** * True if this JIRA is configured to allow Confluence-style Wiki comment. */ public boolean supportsWikiStyleComment; /** * List of project keys (i.e., "MNG" portion of "MNG-512"), * last time we checked. Copy on write semantics. */ private transient volatile Set<String> projects; /** * @stapler-constructor */ public JiraSite(URL url, String userName, String password) { this.url = url; this.userName = Util.fixEmpty(userName); this.password = Util.fixEmpty(password); } public JiraSite() {} public String getName() { return url.toExternalForm(); } /** * Creates a remote access session tos his JIRA. * * @return * null if remote access is not supported. */ public JiraSession createSession() throws IOException, ServiceException { if(userName==null || password==null) return null; // remote access not supported JiraSoapServiceService jiraSoapServiceGetter = new JiraSoapServiceServiceLocator(); JiraSoapService service = jiraSoapServiceGetter.getJirasoapserviceV2( new URL(url, "rpc/soap/jirasoapservice-v2")); return new JiraSession(this,service,service.login(userName,password)); } /** * Computes the URL to the given issue. */ public URL getUrl(JiraIssue issue) throws IOException { return getUrl(issue.id); } /** * Computes the URL to the given issue. */ public URL getUrl(String id) throws MalformedURLException { return new URL(url,"browse/"+ id); } /** * Gets the list of project IDs in this JIRA. * This information could be bit old, or it can be null. */ public Set<String> getProjectKeys() { if(projects==null) { synchronized (this) { try { if(projects==null) { // this will cause the setProjectKeys invocation. JiraSession session = createSession(); if(session!=null) session.getProjectKeys(); } } catch (IOException e) { // in case of error, set empty set to avoid trying the same thing repeatedly. LOGGER.log(Level.WARNING,"Failed to obtain JIRA project list",e); setProjectKeys(new HashSet<String>()); } catch (ServiceException e) { LOGGER.log(Level.WARNING,"Failed to obtain JIRA project list",e); setProjectKeys(new HashSet<String>()); } } } return Collections.unmodifiableSet(projects); } protected void setProjectKeys(Set<String> keys) { if(projects!=null && projects.equals(keys)) return; // no change projects = new HashSet<String>(keys); JiraProjectProperty.DESCRIPTOR.save(); } /** * Gets the effective {@link JiraSite} associated with the given project. * * @return null * if no such was found. */ public static JiraSite get(AbstractProject<?,?> p) { JiraProjectProperty jpp = p.getProperty(JiraProjectProperty.class); if(jpp!=null) { JiraSite site = jpp.getSite(); if(site!=null) return site; } // if only one is configured, that must be it. JiraSite[] sites = JiraProjectProperty.DESCRIPTOR.getSites(); if(sites.length==1) return sites[0]; return null; } /** * Checks if the given JIRA id will be likely to exist in this issue tracker. * * <p> * This method checks whether the key portion is a valid key (except that * it can potentially use stale data). Number portion is not checked at all. * * @param id * String like MNG-1234 */ public boolean existsIssue(String id) { int idx = id.indexOf('-'); if(idx==-1) return false; Set<String> keys = getProjectKeys(); return keys==null || keys.contains(id.substring(0,idx)); } private static final Logger LOGGER = Logger.getLogger(JiraSite.class.getName()); }
package io.github.robwin; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; import io.github.resilience4j.circuitbreaker.autoconfigure.CircuitBreakerProperties; import io.github.resilience4j.circuitbreaker.event.CircuitBreakerEvent; import io.github.resilience4j.circuitbreaker.monitoring.health.CircuitBreakerHealthIndicator; import io.github.resilience4j.consumer.EventConsumerRegistry; import io.prometheus.client.spring.boot.EnablePrometheusEndpoint; import io.prometheus.client.spring.boot.EnableSpringBootMetricsCollector; @SpringBootApplication @EnableSpringBootMetricsCollector @EnablePrometheusEndpoint @EnableConfigurationProperties public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public HealthIndicator backendA(CircuitBreakerRegistry circuitBreakerRegistry, EventConsumerRegistry<CircuitBreakerEvent> eventConsumerRegistry, CircuitBreakerProperties circuitBreakerProperties){ return new CircuitBreakerHealthIndicator(circuitBreakerRegistry, eventConsumerRegistry, circuitBreakerProperties, "backendA"); } @Bean public HealthIndicator backendB(CircuitBreakerRegistry circuitBreakerRegistry, EventConsumerRegistry<CircuitBreakerEvent> eventConsumerRegistry, CircuitBreakerProperties circuitBreakerProperties){ return new CircuitBreakerHealthIndicator(circuitBreakerRegistry, eventConsumerRegistry, circuitBreakerProperties, "backendB"); } }