answer
stringlengths
17
10.2M
package com.chahyadis.jwt.interfaces; /** * IssuerKey<br> * nama aplikasi. * * @author Surya Chahyadi * @since March 26th, 2015 * @version 1.0 */ public abstract interface IssuerKey { /** * appName<br/> * Berupa identitas project yang akan divalidasi oleh server. * * @return {@link String} */ abstract String appName(); }
package com.doctor.esper.event; import java.math.BigDecimal; public class Withdrawal { private String account; private BigDecimal amount; public Withdrawal(String account, BigDecimal amount) { this.account = account; this.amount = amount; } public String getAccount() { return account; } public BigDecimal getAmount() { return amount; } public void setAccount(String account) { this.account = account; } public void setAmount(BigDecimal amount) { this.amount = amount; } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.anim; import java.util.ArrayList; import java.util.List; import playn.core.GroupLayer; import playn.core.Layer; import tripleplay.util.Layers; /** * Handles creation and management of animations. Animations may involve the tweening of a * geometric property of a layer (x, y, rotation, scale, alpha), or simple delays, or performing * actions. Animations can also be sequenced to orchestrate complex correlated actions. */ public abstract class Animator { /** * Creates an instance of an animator. The caller is responsible for calling {@link #update} on * said animator to drive the animation process. */ public static Animator create () { return new Impl(); } /** * Registers an animation with this animator. It will be started on the next frame and continue * until cancelled or it reports that it has completed. */ public abstract <T extends Animation> T add (T tween); /** * Starts a tween on the supplied layer's x/y-translation. */ public Animation.Two tweenTranslation (Layer layer) { return tweenXY(layer); } /** * Starts a tween on the supplied layer's x/y-translation. */ public Animation.Two tweenXY (Layer layer) { return add(new Animation.Two(onX(layer), onY(layer))); } /** * Starts a tween on the supplied layer's x-translation. */ public Animation.One tweenX (Layer layer) { return tween(onX(layer)); } /** * Starts a tween on the supplied layer's y-translation. */ public Animation.One tweenY (Layer layer) { return tween(onY(layer)); } /** * Starts a tween on the supplied layer's rotation. */ public Animation.One tweenRotation (final Layer layer) { return tween(new Animation.Value() { public float initial () { return layer.transform().rotation(); } public void set (float value) { layer.setRotation(value); } }); } /** * Starts a tween on the supplied layer's x/y-scale. */ public Animation.One tweenScale (final Layer layer) { return tween(new Animation.Value() { public float initial () { return layer.transform().uniformScale(); } public void set (float value) { layer.setScale(value); } }); } /** * Starts a tween on the supplied layer's x/y-scale. */ public Animation.Two tweenScaleXY (Layer layer) { return add(new Animation.Two(onScaleX(layer), onScaleY(layer))); } /** * Starts a tween on the supplied layer's x-scale. */ public Animation.One tweenScaleX (Layer layer) { return tween(onScaleX(layer)); } /** * Starts a tween on the supplied layer's y-scale. */ public Animation.One tweenScaleY (Layer layer) { return tween(onScaleY(layer)); } /** * Starts a tween on the supplied layer's transparency. */ public Animation.One tweenAlpha (final Layer layer) { return tween(new Animation.Value() { public float initial () { return layer.alpha(); } public void set (float value) { layer.setAlpha(value); } }); } /** * Starts a tween using the supplied custom value. {@link Animation.Value#initial} will be used * (if needed) to obtain the initial value before the tween begins. {@link Animation.Value#set} * will be called each time the tween is updated with the intermediate values. */ public Animation.One tween (Animation.Value value) { return add(new Animation.One(value)); } /** * Creates an animation that delays for the specified number of seconds. */ public Animation.Delay delay (float seconds) { return add(new Animation.Delay(seconds)); } /** * Returns an animator which can be used to construct an animation that will be repeated until * the supplied layer has been removed from its parent. The layer must be added to a parent * before the next frame (if it's not already), or the cancellation will trigger immediately. */ public Animator repeat (Layer layer) { return add(new Animation.Repeat(layer)).then(); } /** * Creates an animation that executes the supplied runnable and immediately completes. */ public Animation.Action action (Runnable action) { return add(new Animation.Action(action)); } /** * Adds the supplied child to the supplied parent. This is generally done as the beginning of a * chain of animations, which itself may be delayed or subject to animation barriers. */ public Animation.Action add (final GroupLayer parent, final Layer child) { return action(new Runnable() { public void run () { parent.add(child); } }); } /** * Reparents the supplied child to the supplied new parent. This involves translating the * child's current coordinates to screen coordinates, moving it to its new parent layer and * translating its coordinates into the coordinate space of the new parent. Thus the child does * not change screen position, even though its coordinates relative to its parent will most * likely have changed. */ public Animation.Action reparent(final GroupLayer newParent, final Layer child) { return action(new Runnable() { public void run () { Layers.reparent(child, newParent); } }); } /** * Destroys the specified layer. This is generally done as the end of a chain of animations, * which culminate in the removal (destruction) of the target layer. */ public Animation.Action destroy (final Layer layer) { return action(new Runnable() { public void run () { layer.destroy(); } }); } /** * Sets the specified layer's depth to the specified value. */ public Animation.Action setDepth (final Layer layer, final float depth) { return action(new Runnable() { public void run () { layer.setDepth(depth); } }); } /** * Causes this animator to delay the start of any subsequently registered animations until all * currently registered animations are complete. */ public void addBarrier () { addBarrier(0); } /** * Causes this animator to delay the start of any subsequently registered animations until the * specified delay has elapsed <em>after this barrier becomes active</em>. Any previously * registered barriers must first expire and this barrier must move to the head of the list * before its delay timer will be started. This is probably what you want. */ public void addBarrier (float delay) { throw new UnsupportedOperationException( "Barriers are only supported on the top-level animator."); } /** * Performs per-frame animation processing. */ public void update (float time) { // nada by default } protected static Animation.Value onX (final Layer layer) { return new Animation.Value() { public float initial () { return layer.transform().tx(); } public void set (float value) { layer.transform().setTx(value); } }; } protected static Animation.Value onY (final Layer layer) { return new Animation.Value() { public float initial () { return layer.transform().ty(); } public void set (float value) { layer.transform().setTy(value); } }; } protected static Animation.Value onScaleX (final Layer layer) { return new Animation.Value() { public float initial () { return layer.transform().scaleX(); } public void set (float value) { layer.transform().setScaleX(value); } }; } protected static Animation.Value onScaleY (final Layer layer) { return new Animation.Value() { public float initial () { return layer.transform().scaleY(); } public void set (float value) { layer.transform().setScaleY(value); } }; } /** Implementation details, avert your eyes. */ protected static class Impl extends Animator { @Override public <T extends Animation> T add (T anim) { _accum.add(anim); return anim; } @Override public void addBarrier (float delay) { Barrier barrier = new Barrier(delay); _barriers.add(barrier); // pushing a barrier causes subsequent animations to be accumulated separately _accum = barrier.accum; } @Override public void update (float time) { // if we have any animations queued up to be added, add those now if (!_nanims.isEmpty()) { for (int ii = 0, ll = _nanims.size(); ii < ll; ii++) { _nanims.get(ii).init(time); } _anims.addAll(_nanims); _nanims.clear(); } // now process all of our registered animations for (int ii = 0, ll = _anims.size(); ii < ll; ii++) { if (_anims.get(ii).apply(this, time)) { _anims.remove(ii ll -= 1; } } // if we have no active animations, or a timed barrier has expired, unblock a barrier boolean noActiveAnims = _anims.isEmpty() && _nanims.isEmpty(); if (!_barriers.isEmpty() && (noActiveAnims || _barriers.get(0).expired(time))) { Barrier barrier = _barriers.remove(0); _nanims.addAll(barrier.accum); // if we just unblocked the last barrier, start accumulating back on _nanims if (_barriers.isEmpty()) { _accum = _nanims; } } } protected List<Animation> _anims = new ArrayList<Animation>(); protected List<Animation> _nanims = new ArrayList<Animation>(); protected List<Animation> _accum = _nanims; protected List<Barrier> _barriers = new ArrayList<Barrier>(); } /** Implementation details, avert your eyes. */ protected static class Barrier { public List<Animation> accum = new ArrayList<Animation>(); public float expireDelay; public float absoluteExpireTime; public Barrier (float expireDelay) { this.expireDelay = expireDelay; } public boolean expired (float time) { if (expireDelay == 0) return false; if (absoluteExpireTime == 0) absoluteExpireTime = time + expireDelay; return time > absoluteExpireTime; } } }
package org.carlspring.strongbox.providers.repository; import org.carlspring.strongbox.artifact.coordinates.ArtifactCoordinates; import org.carlspring.strongbox.configuration.Configuration; import org.carlspring.strongbox.configuration.ConfigurationManager; import org.carlspring.strongbox.data.criteria.Expression.ExpOperator; import org.carlspring.strongbox.data.criteria.Paginator; import org.carlspring.strongbox.data.criteria.Predicate; import org.carlspring.strongbox.data.criteria.Selector; import org.carlspring.strongbox.domain.ArtifactEntry; import org.carlspring.strongbox.io.*; import org.carlspring.strongbox.providers.datastore.StorageProviderRegistry; import org.carlspring.strongbox.providers.io.RepositoryFiles; import org.carlspring.strongbox.providers.io.RepositoryPath; import org.carlspring.strongbox.providers.layout.LayoutProviderRegistry; import org.carlspring.strongbox.services.ArtifactEntryService; import org.carlspring.strongbox.services.ArtifactTagService; import org.carlspring.strongbox.storage.repository.Repository; import javax.inject.Inject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Path; import java.util.Date; import java.util.List; import org.apache.commons.io.output.CountingOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; /** * @author carlspring */ @Transactional public abstract class AbstractRepositoryProvider implements RepositoryProvider, RepositoryStreamCallback { private static final Logger logger = LoggerFactory.getLogger(AbstractRepositoryProvider.class); @Inject protected RepositoryProviderRegistry repositoryProviderRegistry; @Inject protected LayoutProviderRegistry layoutProviderRegistry; @Inject protected StorageProviderRegistry storageProviderRegistry; @Inject protected ConfigurationManager configurationManager; @Inject protected ArtifactEntryService artifactEntryService; @Inject protected ArtifactTagService artifactTagService; public RepositoryProviderRegistry getRepositoryProviderRegistry() { return repositoryProviderRegistry; } public void setRepositoryProviderRegistry(RepositoryProviderRegistry repositoryProviderRegistry) { this.repositoryProviderRegistry = repositoryProviderRegistry; } public LayoutProviderRegistry getLayoutProviderRegistry() { return layoutProviderRegistry; } public void setLayoutProviderRegistry(LayoutProviderRegistry layoutProviderRegistry) { this.layoutProviderRegistry = layoutProviderRegistry; } public StorageProviderRegistry getStorageProviderRegistry() { return storageProviderRegistry; } public void setStorageProviderRegistry(StorageProviderRegistry storageProviderRegistry) { this.storageProviderRegistry = storageProviderRegistry; } public ConfigurationManager getConfigurationManager() { return configurationManager; } public void setConfigurationManager(ConfigurationManager configurationManager) { this.configurationManager = configurationManager; } public Configuration getConfiguration() { return configurationManager.getConfiguration(); } @Override public RepositoryInputStream getInputStream(Path path) throws IOException { if (path == null) { return null; } Assert.isInstanceOf(RepositoryPath.class, path); RepositoryPath repositoryPath = (RepositoryPath) path; return decorate((RepositoryPath) path, getInputStreamInternal(repositoryPath)); } protected abstract InputStream getInputStreamInternal(RepositoryPath repositoryPath) throws IOException; protected RepositoryInputStream decorate(RepositoryPath repositoryPath, InputStream is) { if (is == null || is instanceof RepositoryInputStream) { return (RepositoryInputStream) is; } return RepositoryInputStream.of(repositoryPath, is).with(this); } @Override public RepositoryOutputStream getOutputStream(Path path) throws IOException { Assert.isInstanceOf(RepositoryPath.class, path); OutputStream os = getOutputStreamInternal((RepositoryPath) path); return decorate((RepositoryPath) path, os); } protected abstract OutputStream getOutputStreamInternal(RepositoryPath repositoryPath) throws IOException; protected final RepositoryOutputStream decorate(RepositoryPath repositoryPath, OutputStream os) throws IOException { if (os == null || os instanceof RepositoryOutputStream) { return (RepositoryOutputStream) os; } return RepositoryOutputStream.of(repositoryPath, os).with(this); } @Override public void onBeforeWrite(RepositoryStreamContext ctx) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) ctx.getPath(); String path = RepositoryFiles.stringValue(repositoryPath); logger.debug(String.format("Writing [%s]", path)); if (!RepositoryFiles.isArtifact(repositoryPath)) { return; } Repository repository = repositoryPath.getRepository(); String storageId = repository.getStorage().getId(); String repositoryId = repository.getId(); ArtifactEntry artifactEntry = provideArtifactEntry(storageId, repositoryId, path); artifactEntry.setStorageId(storageId); artifactEntry.setRepositoryId(repositoryId); artifactEntry.setArtifactPath(path); ArtifactOutputStream aos = StreamUtils.findSource(ArtifactOutputStream.class, (OutputStream) ctx); ArtifactCoordinates coordinates = aos.getCoordinates(); artifactEntry.setArtifactCoordinates(coordinates); Date now = new Date(); artifactEntry.setLastUpdated(now); artifactEntry.setLastUsed(now); artifactEntryService.save(artifactEntry, true); } @Override public void onAfterClose(RepositoryStreamContext ctx) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) ctx.getPath(); String path = RepositoryFiles.stringValue(repositoryPath); logger.debug(String.format("Closing [%s]", path)); if (!RepositoryFiles.isArtifact(repositoryPath)) { return; } Repository repository = repositoryPath.getRepository(); String storageId = repository.getStorage().getId(); String repositoryId = repository.getId(); ArtifactEntry artifactEntry = provideArtifactEntry(storageId, repositoryId, path); Assert.notNull(artifactEntry.getUuid(), String.format("Invalid [%s] for [%s]", ArtifactEntry.class.getSimpleName(), ctx.getPath())); CountingOutputStream cos = StreamUtils.findSource(CountingOutputStream.class, (OutputStream) ctx); artifactEntry.setSizeInBytes(cos.getByteCount()); artifactEntryService.save(artifactEntry); } @Override public void onBeforeRead(RepositoryStreamContext ctx) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) ctx.getPath(); String path = RepositoryFiles.stringValue(repositoryPath); logger.debug(String.format("Reading /" + repositoryPath.getRepository().getStorage().getId() + "/" + repositoryPath.getRepository().getId() + "/%s", path)); if (!RepositoryFiles.isArtifact(repositoryPath)) { return; } Repository repository = repositoryPath.getRepository(); String storageId = repository.getStorage().getId(); String repositoryId = repository.getId(); ArtifactEntry artifactEntry = provideArtifactEntry(storageId, repositoryId, path); Assert.notNull(artifactEntry.getUuid(), String.format("Invalid [%s] for [%s]", ArtifactEntry.class.getSimpleName(), ctx.getPath())); artifactEntry.setLastUsed(new Date()); artifactEntry.setDownloadCount(artifactEntry.getDownloadCount() + 1); artifactEntryService.save(artifactEntry); } protected ArtifactEntry provideArtifactEntry(String storageId, String repositoryId, String path) { ArtifactEntry artifactEntry = artifactEntryService.findOneArtifact(storageId, repositoryId, path) .map(e -> artifactEntryService.lockOne(e.getObjectId())) .orElse(new ArtifactEntry()); return artifactEntry; } @Override public Path fetchPath(Path repositoryPath) throws IOException { return fetchPath((RepositoryPath)repositoryPath); } protected abstract Path fetchPath(RepositoryPath repositoryPath) throws IOException; @Override public List<Path> search(RepositorySearchRequest searchRequest, RepositoryPageRequest pageRequest) { Paginator paginator = new Paginator(); paginator.setLimit(pageRequest.getLimit()); paginator.setSkip(pageRequest.getSkip()); Predicate p = createPredicate(searchRequest); return search(searchRequest.getStorageId(), searchRequest.getRepositoryId(), p, paginator); } @Override public Long count(RepositorySearchRequest searchRequest) { Predicate p = createPredicate(searchRequest); return count(searchRequest.getStorageId(), searchRequest.getRepositoryId(), p); } protected Predicate createPredicate(RepositorySearchRequest searchRequest) { Predicate p = Predicate.empty(); searchRequest.getCoordinates() .entrySet() .forEach(e -> p.and(createCoordinatePredicate(e.getKey(), e.getValue(), searchRequest.isStrict()))); searchRequest.getTagSet() .forEach(t -> p.and(Predicate.of(ExpOperator.CONTAINS.of("tagSet.name", t.getName())))); return p; } protected Predicate createPredicate(String storageId, String repositoryId, Predicate predicate) { Predicate result = Predicate.of(ExpOperator.EQ.of("storageId", storageId)) .and(Predicate.of(ExpOperator.EQ.of("repositoryId", repositoryId))); if (predicate.isEmpty()) { return result; } return result.and(predicate); } private Predicate createCoordinatePredicate(String key, String value, boolean strict) { if (!strict) { return Predicate.of(ExpOperator.LIKE.of(String.format("artifactCoordinates.coordinates.%s", key), "%"+ value + "%")); } return Predicate.of(ExpOperator.EQ.of(String.format("artifactCoordinates.coordinates.%s", key), value)); } protected Selector<ArtifactEntry> createSelector(String storageId, String repositoryId, Predicate p) { Selector<ArtifactEntry> selector = new Selector<>(ArtifactEntry.class); selector.where(createPredicate(storageId, repositoryId, p)); return selector; } }
package com.ezardlabs.dethsquare; import java.util.Iterator; public final class Animator extends Script implements Iterable<Animation> { private Animation[] animations; private int index = -1; private int frame = 0; private long nextFrameTime = 0; private boolean finished = false; public boolean shouldUpdate = true; public Animator(Animation... animations) { this.animations = animations; } public void setAnimations(Animation... animations) { this.animations = animations; } public void addAnimations(Animation... animations) { Animation[] newAnimations = new Animation[this.animations.length + animations.length]; System.arraycopy(this.animations, 0, newAnimations, 0, this.animations.length); System.arraycopy(animations, 0, newAnimations, this.animations.length, animations.length); this.animations = newAnimations; } public void update() { if (!shouldUpdate) { if (index == -1 || frame == -1) return; gameObject.renderer.sprite = animations[index].frames[frame]; return; } int startFrame = frame; if (index == -1 || frame == -1) return; int tempFrame; if (System.currentTimeMillis() >= nextFrameTime) { nextFrameTime += animations[index].frameDuration; tempFrame = animations[index].type.update(frame, animations[index].frames.length); if (tempFrame == -1) { if (animations[index].listener != null && !finished) { animations[index].listener.onAnimationFinished(this); finished = true; } return; } else { finished = false; } frame = tempFrame; try { gameObject.renderer.sprite = animations[index].frames[frame]; } catch (ArrayIndexOutOfBoundsException ignored) { } } else { tempFrame = frame; } if (tempFrame != startFrame && animations[index].listener != null) { animations[index].listener.onFrame(this, tempFrame); } } public void play(String animationName) { if (index != -1 && animations[index].name.equals(animationName)) return; for (int i = 0; i < animations.length; i++) { if (i != index && animations[i].name.equals(animationName)) { index = i; frame = 0; nextFrameTime = System.currentTimeMillis() + animations[index].frameDuration; gameObject.renderer.sprite = animations[index].frames[frame]; if (animations[index].listener != null) animations[index].listener.onAnimatedStarted(this); break; } } } public Animation getCurrentAnimation() { if (index == -1) return null; else return animations[index]; } public int getCurrentAnimationId() { return index; } public void setCurrentAnimationId(int animationId) { index = animationId; } public int getCurrentAnimationFrame() { return frame; } public void setCurrentAnimationFrame(int frame) { this.frame = frame; } @Override public Iterator<Animation> iterator() { return new ObjectIterator<>(animations); } }
package com.parse.starter; import com.parse.starter.R; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.TextView; public class UploadActivity extends Activity { private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.upload); } //hello /** Creates and intent to take a picture and return control to calling * application. Then starts the intent. * @param v - view, used by layout */ public void onClk_TakePicture(View v) { // create intent to take a picture and return control to calling application. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // start the image capture intent startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); } @Override /** Gets the resulting image after the picture has been taking. Called * after the image is taken. */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { // Changes name of label for now TextView txtvw = (TextView)findViewById(R.id.Location); txtvw.setText("Image captured!"); } } } public void onClk_SubmitPicture(View v) { } }
package ui.issuepanel; import backend.interfaces.IModel; import backend.resource.TurboIssue; import filter.expression.Qualifier; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Priority; import ui.UI; import ui.components.IssueListView; import ui.issuecolumn.ColumnControl; import ui.issuecolumn.IssueColumn; import util.KeyPress; import util.events.IssueSelectedEvent; import java.time.LocalDateTime; import java.util.HashMap; import java.util.HashSet; import java.util.Optional; public class IssuePanel extends IssueColumn { private final IModel model; private final UI ui; private int issueCount; private IssueListView listView; private final KeyCombination keyCombBoxToList = new KeyCodeCombination(KeyCode.DOWN, KeyCombination.CONTROL_DOWN); private final KeyCombination keyCombListToBox = new KeyCodeCombination(KeyCode.UP, KeyCombination.CONTROL_DOWN); private final KeyCombination maximizeWindow = new KeyCodeCombination(KeyCode.X, KeyCombination.CONTROL_DOWN); private final KeyCombination minimizeWindow = new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN); private final KeyCombination defaultSizeWindow = new KeyCodeCombination(KeyCode.D, KeyCombination.CONTROL_DOWN); // IssueCommentCounts and issueNonSelfCommentCounts are accessed whenever the view is updated // via listView.setItems in refreshItems. However, an overwrite of the count only happens upon // an IssueSelectedEvent. private HashMap<Integer, Integer> issueCommentCounts = new HashMap<>(); private HashMap<Integer, Integer> issueNonSelfCommentCounts = new HashMap<>(); public IssuePanel(UI ui, IModel model, ColumnControl parentColumnControl, int columnIndex) { super(ui, model, parentColumnControl, columnIndex); this.model = model; this.ui = ui; listView = new IssueListView(); setupListView(); getChildren().add(listView); refreshItems(true); } /** * Determines if an issue has had new comments added (or removed) based on * its last-known comment count in {@link #issueCommentCounts}. * @param issue * @return true if the issue has changed, false otherwise */ private boolean issueHasNewComments(TurboIssue issue, boolean hasMetadata) { if (currentFilterExpression.getQualifierNames().contains(Qualifier.UPDATED) && hasMetadata) { return issueNonSelfCommentCounts.containsKey(issue.getId()) && Math.abs( issueNonSelfCommentCounts.get(issue.getId()) - issue.getMetadata().getNonSelfCommentCount() ) > 0; } else { return issueCommentCounts.containsKey(issue.getId()) && Math.abs(issueCommentCounts.get(issue.getId()) - issue.getCommentCount()) > 0; } } /** * Updates {@link #issueCommentCounts} with the latest counts. * Returns a list of issues which have new comments. * @return */ private HashSet<Integer> updateIssueCommentCounts(boolean hasMetadata) { HashSet<Integer> result = new HashSet<>(); for (TurboIssue issue : getIssueList()) { if (issueCommentCounts.containsKey(issue.getId())) { // We know about this issue; check if it's been updated if (issueHasNewComments(issue, hasMetadata)) { result.add(issue.getId()); } } else { // We don't know about this issue, just put the current comment count. issueNonSelfCommentCounts.put(issue.getId(), issue.getMetadata().getNonSelfCommentCount()); issueCommentCounts.put(issue.getId(), issue.getCommentCount()); } } return result; } @Override public void refreshItems(boolean hasMetadata) { // super.refreshItems(hasMetadata); // boolean hasUpdatedQualifier = currentFilterExpression.getQualifierNames().contains(Qualifier.UPDATED); // // Only update filter if filter does not contain UPDATED (does not need to wait for metadata) // // or if hasMetadata is true (metadata has arrived), or if getIssueList is empty (if filter does // // have UPDATED, but there are no issues whose metadata require retrieval causing hasMetadata to // // never be true) // if (!hasUpdatedQualifier // not waiting for metadata, just update // || hasMetadata // metadata has arrived, update // || getIssueList().size() == 0 // checked only when above two not satisfied final HashSet<Integer> issuesWithNewComments = updateIssueCommentCounts(hasMetadata); // Set the cell factory every time - this forces the list view to update listView.setCellFactory(list -> new IssuePanelCell(model, IssuePanel.this, columnIndex, issuesWithNewComments)); listView.saveSelection(); // Supposedly this also causes the list view to update - not sure // if it actually does on platforms other than Linux... listView.setItems(null); listView.setItems(getIssueList()); issueCount = getIssueList().size(); listView.restoreSelection(); this.setId(model.getDefaultRepo() + "_col" + columnIndex); } } private void setupListView() { setVgrow(listView, Priority.ALWAYS); setupKeyboardShortcuts(); listView.setOnItemSelected(i -> { TurboIssue issue = listView.getItems().get(i); ui.triggerEvent( new IssueSelectedEvent(issue.getRepoId(), issue.getId(), columnIndex, issue.isPullRequest()) ); // Save the stored comment count as its own comment count. // The refreshItems(false) call that follows will remove the highlighted effect of the comment bubble. // (if it was there before) issueCommentCounts.put(issue.getId(), issue.getCommentCount()); issueNonSelfCommentCounts.put(issue.getId(), issue.getMetadata().getNonSelfCommentCount()); // We assume we already have metadata, so we pass true to avoid refreshItems from trying to get // metadata after clicking. refreshItems(true); }); } private void setupKeyboardShortcuts() { filterTextField.addEventHandler(KeyEvent.KEY_RELEASED, event -> { if (keyCombBoxToList.match(event)) { event.consume(); listView.selectFirstItem(); } if (event.getCode() == KeyCode.SPACE) { event.consume(); } if (KeyPress.isDoublePress(KeyCode.SPACE, event.getCode())) { event.consume(); listView.selectFirstItem(); } if (maximizeWindow.match(event)) { ui.maximizeWindow(); } if (minimizeWindow.match(event)) { ui.minimizeWindow(); } if (defaultSizeWindow.match(event)) { ui.setDefaultWidth(); } }); addEventHandler(KeyEvent.KEY_RELEASED, event -> { if (event.getCode() == KeyCode.E) { Optional<TurboIssue> item = listView.getSelectedItem(); if (!item.isPresent()) { return; } TurboIssue issue = item.get(); LocalDateTime now = LocalDateTime.now(); ui.prefs.setMarkedReadAt(issue.getRepoId(), issue.getId(), now); issue.setMarkedReadAt(Optional.of(now)); issue.setIsCurrentlyRead(true); parentColumnControl.refresh(); } if (event.getCode() == KeyCode.U) { Optional<TurboIssue> item = listView.getSelectedItem(); if (!item.isPresent()) { return; } TurboIssue issue = item.get(); ui.prefs.clearMarkedReadAt(issue.getRepoId(), issue.getId()); issue.setMarkedReadAt(Optional.empty()); issue.setIsCurrentlyRead(false); parentColumnControl.refresh(); } if (event.getCode() == KeyCode.F5) { ui.logic.refresh(); } if (event.getCode() == KeyCode.F1) { ui.getBrowserComponent().showDocs(); } if (keyCombListToBox.match(event)) { setFocusToFilterBox(); } if (event.getCode() == KeyCode.SPACE && KeyPress.isDoublePress(KeyCode.SPACE, event.getCode())) { setFocusToFilterBox(); } if (event.getCode() == KeyCode.I) { if (KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showIssues(); } } if (event.getCode() == KeyCode.P) { if (KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showPullRequests(); } } if (event.getCode() == KeyCode.H) { if (KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showDocs(); } } if (event.getCode() == KeyCode.K) { if (KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showKeyboardShortcuts(); } } if (event.getCode() == KeyCode.D) { if (KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showContributors(); event.consume(); } } if (event.getCode() == KeyCode.U) { ui.getBrowserComponent().scrollToTop(); } if (event.getCode() == KeyCode.N) { if (!minimizeWindow.match(event)) { ui.getBrowserComponent().scrollToBottom(); } } if (event.getCode() == KeyCode.J || event.getCode() == KeyCode.K) { ui.getBrowserComponent().scrollPage(event.getCode() == KeyCode.K); } if (event.getCode() == KeyCode.G) { KeyPress.setLastKeyPressedCodeAndTime(event.getCode()); } if (event.getCode() == KeyCode.C && ui.getBrowserComponent().isCurrentUrlIssue()) { ui.getBrowserComponent().jumpToComment(); } if (event.getCode() == KeyCode.L) { if (KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().newLabel(); } else if (ui.getBrowserComponent().isCurrentUrlIssue()) { ui.getBrowserComponent().manageLabels(event.getCode().toString()); } } if (event.getCode() == KeyCode.A && ui.getBrowserComponent().isCurrentUrlIssue()) { ui.getBrowserComponent().manageAssignees(event.getCode().toString()); } if (event.getCode() == KeyCode.M) { if (KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showMilestones(); } else if (ui.getBrowserComponent().isCurrentUrlIssue()) { ui.getBrowserComponent().manageMilestones(event.getCode().toString()); } } if (maximizeWindow.match(event)) { ui.maximizeWindow(); } if (minimizeWindow.match(event)) { ui.minimizeWindow(); } if (defaultSizeWindow.match(event)) { ui.setDefaultWidth(); } }); } private void setFocusToFilterBox() { filterTextField.requestFocus(); filterTextField.setText(filterTextField.getText().trim()); filterTextField.positionCaret(filterTextField.getLength()); addEventHandler(KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.V || event.getCode() == KeyCode.T) { listView.selectFirstItem(); } }); } public int getIssueCount() { return issueCount; } public TurboIssue getSelectedIssue() { return listView.getSelectedItem().get(); } }
package org.carlspring.strongbox.services.impl; import static org.carlspring.strongbox.providers.layout.LayoutProviderRegistry.getLayoutProvider; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.security.NoSuchAlgorithmException; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import javax.transaction.Transactional; import org.carlspring.maven.commons.util.ArtifactUtils; import org.carlspring.strongbox.artifact.coordinates.ArtifactCoordinates; import org.carlspring.strongbox.client.ArtifactTransportException; import org.carlspring.strongbox.configuration.Configuration; import org.carlspring.strongbox.configuration.ConfigurationManager; import org.carlspring.strongbox.domain.ArtifactEntry; import org.carlspring.strongbox.event.artifact.ArtifactEventListenerRegistry; import org.carlspring.strongbox.io.ArtifactOutputStream; import org.carlspring.strongbox.providers.ProviderImplementationException; import org.carlspring.strongbox.providers.io.RepositoryFileAttributes; import org.carlspring.strongbox.providers.io.RepositoryPath; import org.carlspring.strongbox.providers.layout.LayoutProvider; import org.carlspring.strongbox.providers.layout.LayoutProviderRegistry; import org.carlspring.strongbox.providers.search.SearchException; import org.carlspring.strongbox.services.ArtifactEntryService; import org.carlspring.strongbox.services.ArtifactManagementService; import org.carlspring.strongbox.services.ArtifactResolutionService; import org.carlspring.strongbox.services.VersionValidatorService; import org.carlspring.strongbox.storage.ArtifactStorageException; import org.carlspring.strongbox.storage.Storage; import org.carlspring.strongbox.storage.checksum.ArtifactChecksum; import org.carlspring.strongbox.storage.checksum.ChecksumCacheManager; import org.carlspring.strongbox.storage.repository.Repository; import org.carlspring.strongbox.storage.validation.resource.ArtifactOperationsValidator; import org.carlspring.strongbox.storage.validation.version.VersionValidationException; import org.carlspring.strongbox.storage.validation.version.VersionValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Sergey Bespalov * */ public abstract class AbstractArtifactManagementService implements ArtifactManagementService { private static final Logger logger = LoggerFactory.getLogger(AbstractArtifactManagementService.class); @Inject protected ArtifactOperationsValidator artifactOperationsValidator; @Inject protected VersionValidatorService versionValidatorService; @Inject protected ConfigurationManager configurationManager; @Inject protected ArtifactEntryService artifactEntryService; @Inject protected LayoutProviderRegistry layoutProviderRegistry; @Inject protected ArtifactResolutionService artifactResolutionService; @Inject protected ChecksumCacheManager checksumCacheManager; @Inject protected ArtifactEventListenerRegistry artifactEventListenerRegistry; @Override @Transactional public void validateAndStore(String storageId, String repositoryId, String path, InputStream is) throws IOException, ProviderImplementationException, NoSuchAlgorithmException { performRepositoryAcceptanceValidation(storageId, repositoryId, path); Storage storage = layoutProviderRegistry.getStorage(storageId); Repository repository = storage.getRepository(repositoryId); LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); RepositoryPath repositoryPath = layoutProvider.resolve(repository).resolve(path); store(repositoryPath, is); } @Override @Transactional public void store(RepositoryPath repositoryPath, InputStream is) throws IOException, ProviderImplementationException, NoSuchAlgorithmException { try (final ArtifactOutputStream aos = getLayoutProvider(repositoryPath.getFileSystem().getRepository(), layoutProviderRegistry).getOutputStream(repositoryPath)) { storeArtifact(repositoryPath, is, aos); storeArtifactEntry(repositoryPath); } catch (IOException e) { throw new ArtifactStorageException(e); } } private void storeArtifact(RepositoryPath repositoryPath, InputStream is, final ArtifactOutputStream aos) throws IOException, ProviderImplementationException { Repository repository = repositoryPath.getFileSystem().getRepository(); Storage storage = repository.getStorage(); String repositoryId = repository.getId(); String storageId = storage.getId(); String artifactPathRelative = repositoryPath.getResourceLocation(); String artifactPath = storageId + "/" + repositoryId + "/" + artifactPathRelative; LayoutProvider layoutProvider = getLayoutProvider(repository, layoutProviderRegistry); boolean updatedMetadataFile = false; boolean updatedArtifactFile = false; boolean updatedArtifactChecksumFile = false; if (Files.exists(repositoryPath.getTarget())) { if (layoutProvider.isMetadata(artifactPath)) { updatedMetadataFile = true; } else if (layoutProvider.isChecksum(repositoryPath)) { updatedArtifactChecksumFile = true; } else { updatedArtifactFile = true; } } Boolean checksumAttribute = (Boolean) Files.getAttribute(repositoryPath, RepositoryFileAttributes.CHECKSUM); // If we have no digests, then we have a checksum to store. if (Boolean.TRUE.equals(checksumAttribute)) { aos.setCacheOutputStream(new ByteArrayOutputStream()); } if (repository.isHostedRepository()) { artifactEventListenerRegistry.dispatchArtifactUploadingEvent(storageId, repositoryId, artifactPath); } else { artifactEventListenerRegistry.dispatchArtifactDownloadingEvent(storageId, repositoryId, artifactPath); } int readLength; byte[] bytes = new byte[4096]; while ((readLength = is.read(bytes, 0, bytes.length)) != -1) { // Write the artifact aos.write(bytes, 0, readLength); aos.flush(); } if (updatedMetadataFile) { // If this is a metadata file and it has been updated: artifactEventListenerRegistry.dispatchArtifactMetadataFileUpdatedEvent(storageId, repositoryId, artifactPath); artifactEventListenerRegistry.dispatchArtifactMetadataFileUploadedEvent(storageId, repositoryId, artifactPath); } if (updatedArtifactChecksumFile) { // If this is a checksum file and it has been updated: artifactEventListenerRegistry.dispatchArtifactChecksumFileUpdatedEvent(storageId, repositoryId, artifactPath); } if (updatedArtifactFile) { // If this is an artifact file and it has been updated: artifactEventListenerRegistry.dispatchArtifactUploadedEvent(storageId, repositoryId, artifactPath); } Map<String, String> digestMap = aos.getDigestMap(); if (Boolean.FALSE.equals(checksumAttribute) && !digestMap.isEmpty()) { // Store artifact digests in cache if we have them. addChecksumsToCacheManager(digestMap, artifactPath); } if (Boolean.TRUE.equals(checksumAttribute)) { byte[] checksumValue = ((ByteArrayOutputStream) aos.getCacheOutputStream()).toByteArray(); if (checksumValue != null && checksumValue.length > 0 && !updatedArtifactChecksumFile) { artifactEventListenerRegistry.dispatchArtifactChecksumUploadedEvent(storageId, repositoryId, artifactPath); // Validate checksum with artifact digest cache. validateUploadedChecksumAgainstCache(checksumValue, artifactPath); } } } private void storeArtifactEntry(RepositoryPath path) throws IOException { Repository repository = path.getFileSystem().getRepository(); Storage storage = repository.getStorage(); ArtifactCoordinates artifactCoordinates = (ArtifactCoordinates) Files.getAttribute(path, RepositoryFileAttributes.COORDINATES); String artifactPath = path.getResourceLocation(); ArtifactEntry artifactEntry = artifactEntryService.findOneAritifact(storage.getId(), repository.getId(), artifactPath) .orElse(createArtifactEntry(artifactCoordinates, storage.getId(), repository.getId(), artifactPath)); artifactEntry = artifactEntryService.save(artifactEntry); } private void validateUploadedChecksumAgainstCache(byte[] checksum, String artifactPath) throws ArtifactStorageException { logger.debug("Received checksum: " + new String(checksum)); String artifactBasePath = artifactPath.substring(0, artifactPath.lastIndexOf('.')); String checksumExtension = artifactPath.substring(artifactPath.lastIndexOf('.') + 1, artifactPath.length()); if (!matchesChecksum(checksum, artifactBasePath, checksumExtension)) { logger.error(String.format("The checksum for %s [%s] is invalid!", artifactPath, new String(checksum))); } checksumCacheManager.removeArtifactChecksum(artifactBasePath); } private boolean matchesChecksum(byte[] pChecksum, String artifactBasePath, String checksumExtension) { String checksum = new String(pChecksum); ArtifactChecksum artifactChecksum = checksumCacheManager.getArtifactChecksum(artifactBasePath); if (artifactChecksum == null) { return false; } Map<Boolean, Set<String>> matchingMap = artifactChecksum.getChecksums() .entrySet() .stream() .collect(Collectors.groupingBy(e -> e.getValue() .equals(checksum), Collectors.mapping( e -> e.getKey(), Collectors.toSet()))); Set<String> matched = matchingMap.get(Boolean.TRUE); Set<String> unmatched = matchingMap.get(Boolean.FALSE); logger.debug(String.format("Artifact checksum matchings: artifact-[%s]; ext-[%s]; matched-[%s];" + " unmatched-[%s]; checksum-[%s]", artifactBasePath, checksumExtension, matched, unmatched, new String(checksum))); return matched != null && !matched.isEmpty(); } private void addChecksumsToCacheManager(Map<String, String> digestMap, String artifactPath) { digestMap.entrySet() .stream() .forEach(e -> checksumCacheManager.addArtifactChecksum(artifactPath, e.getKey(), e.getValue())); } private ArtifactEntry createArtifactEntry(ArtifactCoordinates artifactCoordinates, String storageId, String repositoryId, String path) { ArtifactEntry artifactEntry = new ArtifactEntry(); artifactEntry.setStorageId(storageId); artifactEntry.setRepositoryId(repositoryId); artifactEntry.setArtifactCoordinates(artifactCoordinates); artifactEntry.setArtifactPath(path); return artifactEntry; } private boolean performRepositoryAcceptanceValidation(String storageId, String repositoryId, String path) throws IOException, ProviderImplementationException { logger.info(String.format("Validate artifact with path [%s]", path)); artifactOperationsValidator.validate(storageId, repositoryId, path); final Storage storage = getStorage(storageId); final Repository repository = storage.getRepository(repositoryId); if (!path.contains("/maven-metadata.") && !ArtifactUtils.isMetadata(path) && !ArtifactUtils.isChecksum(path)) { LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); ArtifactCoordinates coordinates = layoutProvider.getArtifactCoordinates(path); logger.info(String.format("Validate artifact with coordinates [%s]", coordinates)); try { final Set<VersionValidator> validators = versionValidatorService.getVersionValidators(); for (VersionValidator validator : validators) { if (validator.supports(repository)) { validator.validate(repository, coordinates); } } } catch (VersionValidationException e) { throw new ArtifactStorageException(e); } artifactOperationsValidator.checkAllowsRedeployment(repository, coordinates); artifactOperationsValidator.checkAllowsDeployment(repository); } return true; } @Override public Storage getStorage(String storageId) { return getConfiguration().getStorages().get(storageId); } @Override public Configuration getConfiguration() { return configurationManager.getConfiguration(); } @Override public InputStream resolve(String storageId, String repositoryId, String path) throws IOException, ArtifactTransportException, ProviderImplementationException { try { return artifactResolutionService.getInputStream(storageId, repositoryId, path); } catch (IOException | NoSuchAlgorithmException e) { // This is not necessarily an error. It could simply be a check // whether a resource exists, before uploading/updating it. logger.debug("The requested path does not exist: /" + storageId + "/" + repositoryId + "/" + path); } return null; } @Override public void delete(String storageId, String repositoryId, String artifactPath, boolean force) throws IOException { artifactOperationsValidator.validate(storageId, repositoryId, artifactPath); final Storage storage = getStorage(storageId); final Repository repository = storage.getRepository(repositoryId); artifactOperationsValidator.checkAllowsDeletion(repository); try { LayoutProvider layoutProvider = getLayoutProvider(repository, layoutProviderRegistry); layoutProvider.delete(storageId, repositoryId, artifactPath, force); } catch (IOException | ProviderImplementationException | SearchException e) { throw new ArtifactStorageException(e.getMessage(), e); } } }
package com.facebook.presto.block; import com.facebook.presto.block.Cursor.AdvanceResult; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Ordering; import com.google.common.primitives.Longs; import static com.facebook.presto.block.Cursor.AdvanceResult.FINISHED; import static com.facebook.presto.block.Cursor.AdvanceResult.MUST_YIELD; public class Cursors { public static boolean advanceNextPositionNoYield(Cursor cursor) { AdvanceResult result = cursor.advanceNextPosition(); if (result == MUST_YIELD) { throw new IllegalStateException("Cursor must yield but support yield is not supported here"); } return result != FINISHED; } public static boolean advanceNextValueNoYield(Cursor cursor) { AdvanceResult result = cursor.advanceNextValue(); if (result == MUST_YIELD) { throw new IllegalStateException("Cursor requested caller to yield but yield is not supported here"); } return result != FINISHED; } public static boolean advanceToPositionNoYield(Cursor cursor, long position) { AdvanceResult result = cursor.advanceToPosition(position); if (result == MUST_YIELD) { throw new IllegalStateException("Cursor requested caller to yield but yield is not supported here"); } return result != FINISHED; } /** * Advances all cursors to the next position * @return true if all cursors were advanced. Otherwise, false. */ public static boolean advanceNextPositionNoYield(Cursor... cursors) { return advanceNextPositionNoYield(ImmutableList.copyOf(cursors)); } public static boolean advanceNextPositionNoYield(Iterable<Cursor> cursors) { boolean advancedAll = true; for (Cursor cursor : cursors) { advancedAll = advanceNextPositionNoYield(cursor) && advancedAll; } return advancedAll; } public static Ordering<Cursor> orderByPosition() { return new Ordering<Cursor>() { @Override public int compare(Cursor left, Cursor right) { return Longs.compare(left.getPosition(), right.getPosition()); } }; } public static Predicate<Cursor> isFinished() { return new Predicate<Cursor>() { @Override public boolean apply(Cursor input) { return input.isFinished(); } }; } }
package webmattr.react; import elemental.client.Browser; import elemental.dom.Document; import elemental.html.Console; import elemental.html.Window; import jsinterop.annotations.JsIgnore; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import webmattr.Bus; import webmattr.Func; import webmattr.Reflection; import webmattr.action.AbstractAction; import webmattr.action.ActionCall; import webmattr.action.ActionCalls; import webmattr.action.ActionDispatcher; import webmattr.dom.DOM; import webmattr.router.History; import javax.inject.Inject; import javax.inject.Provider; /** * @param <P> * @param <S> */ public abstract class Component<P, S> { protected final Console console = Browser.getWindow().getConsole(); protected final Document document = Browser.getDocument(); protected final Window window = Browser.getWindow(); @JsProperty private final boolean __webmattr_component__$$__ = true; // Lifecycle @JsProperty private final Func.Run1<P> componentWillReceiveProps = Func.bind(this::componentWillReceiveProps0); @JsProperty private final Func.Run2<P, S> componentWillUpdate = Func.bind(this::componentWillUpdate0); @JsProperty private final Func.Run2<P, S> componentDidUpdate = Func.bind(this::componentDidUpdate0); @JsProperty private final Func.Run componentDidMount = Func.bind(this::componentDidMount0); @JsProperty private final Func.Run componentWillUnmount = Func.bind(this::componentWillUnmount0); // Defaults @JsProperty private String displayName = ""; @JsProperty private ContextTypes contextTypes = new ContextTypes(); // Props private Provider<P> propsProvider; @JsProperty private final Func.Call<P> getDefaultProps = Func.bind(this::getDefaultProps); private P propsType; // State private Provider<S> stateProvider; @JsProperty private final Func.Call2<Boolean, P, S> shouldComponentUpdate = Func.bind(this::shouldComponentUpdate0); @JsProperty private final Func.Call<S> getInitialState = Func.bind(this::getInitialState); private S stateType; @JsProperty private final Func.Run componentWillMount = Func.bind(this::componentWillMount0); // Render @JsProperty private final Func.Call<ReactElement> render = Func.bind(this::render0); private Object reactClass; private Bus bus; private History history; public Component() { addContextTypes(contextTypes); displayName = getDisplayName(); } public static native boolean is(Object obj) /*-{ return obj && obj['__webmattr_component__$$__']; }-*/; // Build Context Types Object. protected void addContextTypes(ContextTypes contextTypes) { } // Injected @Inject void setPropsProvider(Provider<P> provider) { this.propsProvider = provider; propsType = provider.get(); } @Inject void setStateProvider(Provider<S> provider) { this.stateProvider = provider; stateType = provider.get(); } public Bus bus() { return bus; } @Inject void setBus(Bus bus) { this.bus = bus; } public History getHistory() { return history; } @Inject void setHistory(History history) { this.history = history; } // MyEventBus public String getDisplayName() { return getClass().getSimpleName(); } private P getPropsType() { return propsType; } private S getStateType() { return stateType; } /** * @param $this * @return */ public P getProps(ReactComponent $this) { return Reflection.copy(React.getProps($this), getPropsType()); } /** * @param $this * @return */ public S getState(ReactComponent $this) { return Reflection.copy(React.getState($this), getStateType()); } /** * @param $this * @param state */ public void setState(ReactComponent $this, S state) { $this.setState(state); } protected P getDefaultProps(ReactComponent<P, S> $this) { P props = props(); initProps($this, props); return props; } /** * Invoked once when the component is mounted. * Values in the mapping will be set on this.props if that prop is not specified by the parent component (i.e. using an in check). * This method is invoked before onGetInitialState and therefore cannot rely on this.state or use this.setState. */ @JsIgnore protected P initProps(ReactComponent<P, S> $this, P props) { return props; } @JsIgnore protected S getInitialState(ReactComponent<P, S> $this) { P props = getProps($this); return this.initState($this, props, stateProvider.get()); } /** * @return */ @JsIgnore protected S initState(ReactComponent<P, S> $this, P props, S state) { return state; } /** * Invoked before rendering when new props or state are being received. * This method is not called for the initial render or when forceUpdate is used. * Use this as an opportunity to return false when you're certain that the transition to the new props and state will not require a component update. * By default, shouldComponentUpdate always returns true to prevent subtle bugs when state is mutated in place, * but if you are careful to always treat state as immutable and to read only from props and state in render() * then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements. * <p/> * If performance is a bottleneck, especially with dozens or hundreds of components, use shouldComponentUpdate to speed up your app. * * @param nextProps the props object that the component will receive * @param nextState the state object that the component will receive */ @JsIgnore protected boolean shouldComponentUpdate0(final ReactComponent<P, S> $this, Object nextProps, Object nextState) { return shouldComponentUpdate( $this, Reflection.copy(nextProps, propsProvider.get()), Reflection.copy(nextState, stateProvider.get()) ); } protected boolean shouldComponentUpdate(final ReactComponent<P, S> $this, P nextProps, S nextState) { return true; } /** * The render() method is required. When called, it should examine this.props and this.state and return a single child component. * This child component can be either a virtual representation of a native DOM component (such as <div /> or React.DOM.div()) * or another composite component that you've defined yourself. * The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, * and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using setTimeout). * If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. * Keeping render() pure makes server rendering more practical and makes components easier to think about. */ protected ReactElement render0(final ReactComponent<P, S> $this) { P props = getProps($this); S state = getState($this); ChildCounter.get().scope(); try { return render($this, props, state); } finally { ChildCounter.get().pop(); } } protected abstract ReactElement render(final ReactComponent<P, S> $this, P props, S state); @JsIgnore private void componentWillMount0(final ReactComponent $this) { if ($this != null) { // Register event handlers. Reflection.set($this, React.ACTION_CALLS, new ActionCalls()); Reflection.set($this, React.ACTION, action()); Reflection.set($this, React.GET_REF, (Func.Call1<Object, Ref>) ref -> ref.get($this)); Reflection.set($this, React.GET_PROPS, (Func.Call<P>) () -> getProps($this)); Reflection.set($this, React.GET_STATE, (Func.Call<S>) () -> getState($this)); Reflection.set($this, React.GET_PROPERTY, (Func.Call1<Object, String>) name -> Reflection.get($this, name)); } componentWillMount($this, getProps($this), getState($this)); } private <H extends AbstractAction<IN, OUT>, IN, OUT> Func.Call1<ActionCall<IN, OUT>, Provider<H>> action() { return new Func.Call1<ActionCall<IN, OUT>, Provider<H>>() { @Override public ActionCall<IN, OUT> call(Provider<H> value) { return ActionDispatcher.action(value); } }; } /** * @param $this * @param action * @param <H> * @param <IN> * @param <OUT> * @return */ protected <H extends AbstractAction<IN, OUT>, IN, OUT> ActionCall<IN, OUT> dispatch( ReactComponent $this, Provider<H> action ) { ActionCalls calls = Reflection.get($this, React.ACTION_CALLS); if (calls == null) { calls = new ActionCalls(); Reflection.set($this, React.ACTION_CALLS, calls); } final ActionCall<IN, OUT> call = ActionDispatcher.action(action); calls.add(call); return call; } /** * Invoked immediately before rendering occurs.`` * If you call setState within this method, render() will see the updated state and will be executed only once despite the state change. */ @JsIgnore protected void componentWillMount(final ReactComponent<P, S> $this, P props, S state) { } @JsIgnore private void componentDidMount0(final ReactComponent<P, S> $this) { if ($this != null) { Reflection.set($this, React.EVENT_BUS_REGISTRATIONS, new Object()); } componentDidMount($this); } /** * Invoked immediately after rendering occurs. * At this point in the lifecycle, the component has a DOM representation which you can access via the rootNode argument or by calling this.getDOMNode(). * If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, * or send AJAX requests, perform those operations in this method. */ @JsIgnore protected void componentDidMount(final ReactComponent<P, S> $this) { } @JsIgnore private void componentWillReceiveProps0(final ReactComponent<P, S> $this, P nextProps) { componentWillReceiveProps($this, nextProps); } /** * Invoked when a component is receiving new props. This method is not called for the initial render. * <p/> * Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). * The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render. * * @param nextProps the props object that the component will receive */ @JsIgnore protected void componentWillReceiveProps(final ReactComponent<P, S> $this, P nextProps) { } @JsIgnore private void componentWillUpdate0(final ReactComponent<P, S> $this, P nextProps, S nextState) { componentWillUpdate($this, nextProps, nextState); } /** * Invoked immediately before rendering when new props or state are being received. This method is not called for the initial render. * Use this as an opportunity to perform preparation before an update occurs. * * @param nextProps the props object that the component has received * @param nextState the state object that the component has received */ @JsIgnore protected void componentWillUpdate(final ReactComponent<P, S> $this, P nextProps, S nextState) { } @JsIgnore private void componentDidUpdate0(final ReactComponent<P, S> $this, P nextProps, S nextState) { componentDidUpdate($this, nextProps, nextState); } /** * Invoked immediately after updating occurs. This method is not called for the initial render. * Use this as an opportunity to operate on the DOM when the component has been updated. * * @param nextProps the props object that the component has received * @param nextState the state object that the component has received */ @JsIgnore protected void componentDidUpdate(final ReactComponent<P, S> $this, P nextProps, S nextState) { } @JsIgnore private void componentWillUnmount0(final ReactComponent<P, S> $this) { // Cleanup event registrations. // HandlerRegistration registrations = React.get($this, React.EVENT_BUS_REGISTRATIONS); // if (registrations != null) { // registrations.removeHandler(); // React.delete($this, React.EVENT_BUS_REGISTRATIONS); // TODO: Cleanup. // React.set($this, React.ACTION_CALLS, new ActionCalls()); // React.set($this, React.ACTION, action()); // React.set($this, React.GET_REF, (Func.Call1<Object, Ref>) ref -> ref.get($this)); // React.set($this, React.GET_PROPS, (Func.Call<P>) () -> getProps($this)); // React.set($this, React.GET_STATE, (Func.Call<S>) () -> getState($this)); // React.set($this, React.GET_PROPERTY, (Func.Call1<Object, String>) name -> React.get($this, name)); componentWillUnmount($this); } /** * Invoked immediately before a component is unmounted from the DOM. * Perform any necessary cleanup in this method, such as invalidating timers or cleaning up any DOM elements that were created in componentDidMount. */ @JsIgnore protected void componentWillUnmount(final ReactComponent<P, S> $this) { } // Factory Methods public Object getReactClass() { if (reactClass == null) { reactClass = React.createClass(this); } return reactClass; } protected P props() { // Create Props. final P props = propsProvider.get(); try { // Init props. initProps(null, props); } catch (Throwable e) { // Ignore. } // Set key manually. final Object key = Reflection.get(props, "key"); if (key == null) { Reflection.set(props, "key", ChildCounter.get().newKey()); } // Return props. return props; } /** * @param children * @return */ public ReactElement $(Object... children) { return React.createElement(getReactClass(), props(), children); } /** * @return */ public ReactElement $() { return React.createElement(getReactClass(), props()); } /** * @param props * @return */ public ReactElement $(P props) { return React.createElement(getReactClass(), props); } /** * @param props * @param childCallback * @return */ public ReactElement $(P props, Func.Run1<DOM.ChildList> childCallback) { final DOM.ChildList childList = new DOM.ChildList(); if (childCallback != null) { childCallback.run(childList); } return React.createElement(getReactClass(), props, childList.toArray()); } /** * @param propsCallback * @param childCallback * @return */ public ReactElement $(Func.Run1<P> propsCallback, Func.Run1<DOM.ChildList> childCallback) { final P props = props(); if (propsCallback != null) { propsCallback.run(props); } final DOM.ChildList childList = new DOM.ChildList(); if (childCallback != null) { childCallback.run(childList); } return React.createElement(getReactClass(), props, childList.toArray()); } /** * @param callback * @return */ public ReactElement $(Func.Run2<P, DOM.ChildList> callback) { final P props = props(); final DOM.ChildList childList = new DOM.ChildList(); if (callback != null) { callback.run(props, childList); } return React.createElement(getReactClass(), props, childList.toArray()); } /** * @param propsCallback * @return */ public ReactElement $(Func.Run1<P> propsCallback) { final P props = props(); if (propsCallback != null) { propsCallback.run(props); } return React.createElement(getReactClass(), props); } /** * @param propsCallback * @param children * @return */ public ReactElement $(Func.Run1<P> propsCallback, Object... children) { final P props = props(); if (propsCallback != null) { propsCallback.run(props); } return React.createElement(getReactClass(), props, children); } /** * @param childCallback * @return */ public ReactElement $$(Func.Run1<DOM.ChildList> childCallback) { final P props = props(); final DOM.ChildList childList = new DOM.ChildList(); if (childCallback != null) { childCallback.run(childList); } return React.createElement(getReactClass(), props, childList.toArray()); } @JsType public static class ContextTypes { @JsIgnore public <T> T get(String name) { return Reflection.get(this, name); } @JsIgnore public <T> void set(String name, T value) { Reflection.set(this, name, value); } } }
package com.fenbi.ytklearn.data.gbdt; import com.fenbi.ytklearn.data.Constants; import com.fenbi.ytklearn.data.Tuple; import com.fenbi.ytklearn.feature.gbdt.FeatureSplitType; import com.fenbi.ytklearn.utils.NumConvertUtils; import com.fenbi.ytklearn.utils.CheckUtils; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * regression tree data structure * @author wufan */ public class Tree { public static String innerNodePatternStr = "(\\S+):\\[f_(\\S+)<=(\\S+)\\] yes=(\\S+),no=(\\S+),missing=(\\S+),gain=(\\S+),hess_sum=(\\S+),sample_cnt=(\\S+)"; public static String leafPatternStr = "(\\S+):leaf=(\\S+),hess_sum=(\\S+),sample_cnt=(\\S+)"; private List<TreeNode> nodes; private List<TreeNodeStat> stats; public Tree() { nodes = new ArrayList<>(); stats = new ArrayList<>(); } protected int AllocTreeNode() { int nid = nodes.size(); CheckUtils.check(nid < Integer.MAX_VALUE, "number of nodes in the tree exceed Integer.MAX_VALUE"); nodes.add(new TreeNode()); stats.add(new TreeNodeStat()); return nid; } public void addChilds(int nid) { int left = AllocTreeNode(); int right = AllocTreeNode(); nodes.get(nid).setLeftChild(left); nodes.get(nid).setRightChild(right); nodes.get(left).setParent(nid); nodes.get(right).setParent(nid); } public int getDepth(int nid) { int depth = 0; while (!nodes.get(nid).isRoot()) { depth++; nid = nodes.get(nid).getParent(); } return depth; } private int maxDepthToLeaf(int nid) { if (nodes.get(nid).isLeaf()) { return 0; } return Math.max(maxDepthToLeaf(nodes.get(nid).getLeftChild()), maxDepthToLeaf(nodes.get(nid).getRightChild())) + 1; } public int getMaxDepth() { int maxd = maxDepthToLeaf(0); return maxd; } private void getLeafCnt(int nid, int[] leafCnt) { TreeNode node = nodes.get(nid); if (node.isLeaf()) { leafCnt[0]++; } else { getLeafCnt(node.getLeftChild(), leafCnt); getLeafCnt(node.getRightChild(), leafCnt); } } public int getLeafCnt() { int[] leafCnt = new int[]{0}; getLeafCnt(0, leafCnt); return leafCnt[0]; } public double predict(Map<String, Float> features) { // for online predict, k-v features int pid = getLeafIndex(features); return nodes.get(pid).getLeafValue(); } public int getLeafIndex(Map<String, Float> features) { int pid = 0; String splitFeaName = ""; while (!nodes.get(pid).isLeaf()) { splitFeaName = nodes.get(pid).getSplitFeatureName(); Float feaVal = features.get(splitFeaName); if (feaVal == null) { pid = getNext(pid, 0, true); } else { pid = getNext(pid, feaVal, false); } } return pid; } public float predict(int[] feaMatrix, int instOffset, boolean isOriginTree) { // used in train phase, featureMatrix flatten int pid = getLeafIndex(feaMatrix, instOffset, isOriginTree); return nodes.get(pid).getLeafValue(); } public int getLeafIndex(int[] feaMatrix, int instOffset, boolean isOriginTree) { int pid = 0; int splitIndex = 0; while (!nodes.get(pid).isLeaf()) { splitIndex = nodes.get(pid).getSplitFeatureIndex(); if (isOriginTree) { pid = getNext(pid, NumConvertUtils.int2float(feaMatrix[instOffset + splitIndex]), feaMatrix[instOffset + splitIndex] == Constants.INT_MISSING_VALUE); } else { //train phase: missing value is filled pid = getNext(pid, feaMatrix[instOffset + splitIndex], false); } } return pid; } private int getNext(int pid, float feaVal, boolean isMissing) { TreeNode node = nodes.get(pid); if (isMissing) { return node.getDefualtChild(); } else { float splitVal = node.getSplitCond(); if (feaVal <= splitVal) { return node.getLeftChild(); } else { return node.getRightChild(); } } } public int getNodeNum() { return nodes.size(); } public TreeNode getNode(int index) { return nodes.get(index); } public TreeNodeStat getNodeStat(int index) { return stats.get(index); } // init a tree, add root public void init() { TreeNode node = new TreeNode(); node.setParent(-1); node.setLeaf(0.0f); nodes.add(node); stats.add(new TreeNodeStat()); } public void loadModel(BufferedReader reader, Pattern innerNodePattern, Pattern leafPattern) throws IOException, ClassNotFoundException { CheckUtils.check(nodes.size() == 0, "[GBDT] RegTree load model error! node num is not 0, num_nodes=" + nodes.size()); int nodeNum = Integer.parseInt(reader.readLine().split(",")[1].split("=")[1]); CheckUtils.check(nodeNum > 0, String.format("[GBDT] load invalid model, nodeNum=%d should > 0", nodeNum)); nodes = new ArrayList<>(nodeNum); stats = new ArrayList<>(nodeNum); for (int i = 0; i < nodeNum; i++) { nodes.add(new TreeNode()); stats.add(new TreeNodeStat()); } for (int i = 0; i < nodeNum; i++) { String line = reader.readLine(); if (line.indexOf("leaf") >= 0) { parseLeaf(leafPattern, line); } else { parseInnerNode(innerNodePattern, line); } } } private void parseLeaf(Pattern leafP, String nodeStr) { Matcher m = leafP.matcher(nodeStr); CheckUtils.check(m.find() == true, "[GBDT] parse model error, leaf line:" + nodeStr); int nid = Integer.parseInt(m.group(1)); float leafVal = Float.parseFloat(m.group(2)); float hessSum = Float.parseFloat(m.group(3)); long sampleCnt = Long.parseLong(m.group(4)); nodes.get(nid).setLeaf(leafVal); stats.get(nid).setHessSum(hessSum); stats.get(nid).setNodeSampleCnt(sampleCnt); } private void parseInnerNode(Pattern innerNodeP, String nodeStr) { Matcher m = innerNodeP.matcher(nodeStr); CheckUtils.check(m.find() == true, "[GBDT] parse model error, non-leaf line:" + nodeStr); int nid = Integer.parseInt(m.group(1)); String splitFeatName = m.group(2); float splitFeatVal = Float.parseFloat(m.group(3)); int leftChild = Integer.parseInt(m.group(4)); int rightChild = Integer.parseInt(m.group(5)); boolean isDefaultLeft = Integer.parseInt(m.group(6)) == leftChild; float gain = Float.parseFloat(m.group(7)); float hessSum = Float.parseFloat(m.group(8)); long sampleCnt = Long.parseLong(m.group(9)); TreeNode node = nodes.get(nid); node.setLeftChild(leftChild); node.setRightChild(rightChild); node.setSplitFeatureName(splitFeatName); node.setSplit(-1, splitFeatVal); node.setDefaultDirection(isDefaultLeft); nodes.get(leftChild).setParent(nid); nodes.get(rightChild).setParent(nid); TreeNodeStat stat = stats.get(nid); stat.setLossChg(gain); stat.setHessSum(hessSum); stat.setNodeSampleCnt(sampleCnt); } public String dumpModel(int iter, boolean withStats) { int nodeNum = nodes.size(); CheckUtils.check(nodeNum > 0, String.format("[GBDT] save invalid model, nodeNum=%d should > 0", nodeNum)); StringBuffer sb = new StringBuffer(""); sb.append(String.format("booster[%d] depth=%d,node_num=%d,leaf_cnt=%d\n", iter + 1, getMaxDepth(), nodeNum, getLeafCnt())); dump(0, sb, 0, withStats); return sb.toString(); } private void dump(int nid, StringBuffer sb, int depth, boolean withStats) { for (int i = 0; i < depth; i++) { sb.append("\t"); } TreeNode node = nodes.get(nid); if (node.isLeaf()) { sb.append(String.format("%d:leaf=%s", nid, Float.toString(node.getLeafValue()))); if (withStats) { sb.append(getNodeStat(nid).print(true)); } sb.append("\n"); } else { String splitFeaName = node.getSplitFeatureName(); float cond = node.getSplitCond(); sb.append(String.format("%d:[f_%s<=%s] yes=%d,no=%d,missing=%d", nid, splitFeaName, Float.toString(cond), node.getLeftChild(), node.getRightChild(), node.getDefualtChild())); if (withStats) { sb.append(getNodeStat(nid).print(false)); } sb.append("\n"); dump(node.getLeftChild(), sb, depth + 1, withStats); dump(node.getRightChild(), sb, depth + 1, withStats); } } public void convertFeatureSplitValueInModel(Map<Integer, float[]> globalFeaSplitValsSorted, FeatureSplitType fsType) { CheckUtils.check(globalFeaSplitValsSorted != null && globalFeaSplitValsSorted.size() > 0, "[GBDT] global sorted feature split values map is empty, convert model error!"); TreeNode node; for (int i = 0; i < nodes.size(); i++) { node = nodes.get(i); if (node.isLeaf()) { continue; } int splitFeaIndex = node.getSplitFeatureIndex(); int[] interval = node.getSplitFeaApproSlotInterval(); // size = 2 float[] feaSplitValSorted = globalFeaSplitValsSorted.get(splitFeaIndex); float splitFeaVal = fsType.getFeatureSplit(feaSplitValSorted, interval); node.setSplit(splitFeaIndex, splitFeaVal); } } public void addFeatureNameInModel(Map<Integer, String> fIndex2Name) { // convert feature split index to name, called before saveModel or dumpModel TreeNode node; int feaIndex; String feaName; for (int i = 0; i < nodes.size(); i++) { node = nodes.get(i); if (node.isLeaf()) { continue; } feaIndex = node.getSplitFeatureIndex(); feaName = fIndex2Name.get(node.getSplitFeatureIndex()); CheckUtils.check(feaName != null, "[GBDT] inner error! can't find feature name for feature index(" + feaIndex + ")"); node.setSplitFeatureName(feaName); } } public void updateFeatureIndexInModel(Map<String, Integer> fName2Index) { // convert feature split name to index, called after loadModel TreeNode node; Integer feaIndex; String feaName; for (int i = 0; i < nodes.size(); i++) { node = nodes.get(i); if (node.isLeaf()) { continue; } feaName = node.getSplitFeatureName(); feaIndex = fName2Index.get(feaName); CheckUtils.check(feaIndex != null, "[GBDT] inner error! can't find feature index for feature name(" + feaName + ")"); node.setSplitFeatureIndex(feaIndex); } } public List<Integer> getLeafNodes() { List<Integer> leafNodes = new ArrayList<>(); TreeNode node; for (int i = 0; i < nodes.size(); i++) { node = nodes.get(i); if (node.isLeaf()) { leafNodes.add(i); } } return leafNodes; } public void addDefaultDirection(float[] missValueArr) { if (missValueArr == null || missValueArr.length == 0) { return; } TreeNode node; for (int i = 0; i < nodes.size(); i++) { node = nodes.get(i); if (node.isLeaf()) { continue; } int splitFeaIndex = node.getSplitFeatureIndex(); float splitFeaVal = node.getSplitCond(); if (missValueArr[splitFeaIndex] < splitFeaVal) { node.setDefaultDirection(true); } else { node.setDefaultDirection(false); } } } public void genFeatureDict(Map<String, Integer> feaDictMap) { TreeNode node; String splitFeaName; for (int i = 0; i < nodes.size(); i++) { node = nodes.get(i); if (node.isLeaf()) { continue; } splitFeaName = node.getSplitFeatureName(); Integer index = feaDictMap.get(splitFeaName); if (index == null) { feaDictMap.put(splitFeaName, feaDictMap.size()); } } } public void featureImportance(Map<String, Tuple<Integer, Double>> feaImpMap) { TreeNode node; String splitFeaName; for (int i = 0; i < nodes.size(); i++) { node = nodes.get(i); if (node.isLeaf()) { continue; } splitFeaName = node.getSplitFeatureName(); Tuple<Integer, Double> imp = feaImpMap.get(splitFeaName); if (imp == null) { feaImpMap.put(splitFeaName, new Tuple<>(1, (double)stats.get(i).getLossChg())); } else { imp.v1++; imp.v2 += stats.get(i).getLossChg(); } } } }
package com.github.sd4324530.jtuple; import java.io.Serializable; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.Objects.isNull; import static java.util.Objects.requireNonNull; /** * * * * * * @author peiyu * @see Tuple2 */ public abstract class Tuple implements Iterable<Object>, Serializable { private final List<Object> valueList; Tuple(final Object... objects) { //ListListapi this.valueList = Arrays.asList(objects); } /** * * * @return */ public final List<Object> toList() { return new ArrayList<>(this.valueList); } /** * * * @return */ public final Object[] toArray() { return this.valueList.toArray(); } /** * * * @return */ public final int size() { return this.valueList.size(); } /** * * * @param pos * @param <T> * @return */ @SuppressWarnings("unchecked") public final <T> T get(final int pos) { return (T) this.valueList.get(pos); } /** * * * @param value * @return */ public final boolean contains(final Object value) { return this.valueList.contains(value); } @Override public final Iterator<Object> iterator() { return this.valueList.iterator(); } @Override public final Spliterator<Object> spliterator() { return this.valueList.spliterator(); } /** * * * @return */ public final Stream<Object> stream() { return this.valueList.stream(); } /** * * * @return */ public final Stream<Object> parallelStream() { return this.valueList.parallelStream(); } /** * * * @param action */ @Override public final void forEach(final Consumer<? super Object> action) { requireNonNull(action, "action is null"); this.valueList.forEach(action); } /** * * * @param action */ public final void forEachWithIndex(final BiConsumer<Integer, ? super Object> action) { requireNonNull(action, "action is null"); for (int i = 0, length = this.valueList.size(); i < length; i++) action.accept(i, this.valueList.get(i)); } /** * * * @param start * @param end * @return */ public final Tuple subTuple(final int start, final int end) { if (start < 0 || end < 0) throw new IllegalArgumentException("start, end must >= 0"); if (end >= this.valueList.size()) throw new IllegalArgumentException("this tuple's size is" + this.valueList.size()); int length = end - start + 1; if (length <= 0) throw new IllegalArgumentException("end must >= start"); if (start == 0 && end == this.valueList.size() - 1) return this; switch (length) { case 1: return Tuple1.with(this.valueList.get(start)); case 2: return Tuple2.with(this.valueList.get(start), this.valueList.get(end)); case 3: return Tuple3.with(this.valueList.get(start), this.valueList.get(start + 1), this.valueList.get(end)); case 4: return Tuple4.with(this.valueList.get(start), this.valueList.get(start + 1), this.valueList.get(start + 2), this.valueList.get(end)); case 5: return Tuple5.with(this.valueList.get(start), this.valueList.get(start + 1), this.valueList.get(start + 2), this.valueList.get(start + 3), this.valueList.get(end)); default: return TupleN.with(this.valueList.subList(start, end)); } } /** * * * @param tuples * @return */ public final Tuple add(final Tuple... tuples) { requireNonNull(tuples, "tuples is null"); if (tuples.length == 0) return this; List<Object> temp = this.toList(); for (Tuple t : tuples) temp.addAll(t.valueList); switch (temp.size()) { case 1: return Tuple1.with(temp.get(0)); case 2: return Tuple2.with(temp.get(0), temp.get(1)); case 3: return Tuple3.with(temp.get(0), temp.get(1), temp.get(2)); case 4: return Tuple4.with(temp.get(0), temp.get(1), temp.get(2), temp.get(3)); case 5: return Tuple5.with(temp.get(0), temp.get(1), temp.get(2), temp.get(3), temp.get(4)); default: return TupleN.with(temp.toArray()); } } /** * * * @param objs * @return */ public final Tuple add(final Object... objs) { requireNonNull(objs, "objs is null"); if (Arrays.stream(objs).anyMatch(obj -> obj instanceof Tuple)) throw new IllegalArgumentException("The parameter of this method cannot be Tuple"); return this.add(TupleN.with(objs)); } /** * * * @param times * @return */ public final Tuple repeat(final int times) { if (times < 0) throw new IllegalArgumentException("times must >= 0"); if (times == 0) return this; return TupleN.with(IntStream.range(0, times) .mapToObj(i -> this.valueList.toArray()) .reduce((a, b) -> { Object[] temp = new Object[a.length + b.length]; System.arraycopy(a, 0, temp, 0, a.length); System.arraycopy(b, 0, temp, a.length, b.length); return temp; }).get()); } /** * 2 * * * @param obj * @return */ @Override public final boolean equals(final Object obj) { if (isNull(obj)) return false; if (obj == this) return true; if (obj instanceof Tuple) return ((Tuple) obj).valueList.equals(this.valueList); return false; } @Override public final int hashCode() { return this.valueList.hashCode(); } /** * (123, 456) * * @return */ @Override public final String toString() { return this.valueList.stream() .map(Objects::toString) .collect(Collectors.joining(", ", "(", ")")); } /** * * * * @return */ public abstract Tuple reverse(); }
package org.xwiki.test.integration; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.builder.fluent.Parameters; import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecuteResultHandler; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteWatchdog; import org.apache.commons.exec.PumpStreamHandler; import org.apache.commons.exec.ShutdownHookProcessDestroyer; import org.apache.commons.exec.environment.EnvironmentUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Start and stop an XWiki instance. * * @version $Id$ * @since 2.0RC1 */ public class XWikiExecutor { /** * Only start XWiki if the System property {@code xwiki.test.startXWiki} is undefined or has a value of true. This * allows the build to start XWiki (this is the case for example when running functional tests with Docker). */ private static final boolean SHOULD_START_XWIKI = Boolean.valueOf(System.getProperty("xwiki.test.startXWiki", "true")); protected static final Logger LOGGER = LoggerFactory.getLogger(XWikiExecutor.class); /** * If defined then we check for an existing running XWiki instance before trying to start XWiki. */ public static final String VERIFY_RUNNING_XWIKI_AT_START = System.getProperty("xwiki.test.verifyRunningXWikiAtStart", "true"); public static final String BASEDIR = System.getProperty("basedir"); public static final String URL = System.getProperty("xwiki.test.baseURL", "http://localhost"); /** * By default assume that XWiki is deployed under the "xwiki" Servlet context. Pass an empty string to singify the * root context. Note the "/" suffix which is required. */ public static final String DEFAULT_CONTEXT = System.getProperty("xwiki.test.context", "/xwiki"); public static final String DEFAULT_PORT = System.getProperty("xwikiPort", "8080"); public static final String DEFAULT_STOPPORT = System.getProperty("xwikiStopPort", "8079"); public static final String DEFAULT_RMIPORT = System.getProperty("rmiPort", "9010"); private static final String DEFAULT_EXECUTION_DIRECTORY = System.getProperty("xwikiExecutionDirectory"); private static final String START_COMMAND = System.getProperty("xwikiExecutionStartCommand"); private static final String STOP_COMMAND = System.getProperty("xwikiExecutionStopCommand"); private static final boolean DEBUG = System.getProperty("debug", "false").equalsIgnoreCase("true"); private static final String WEBINF_PATH = "/webapps/xwiki/WEB-INF"; private static final String XWIKICFG_PATH = WEBINF_PATH + "/xwiki.cfg"; private static final String XWIKIPROPERTIES_PATH = WEBINF_PATH + "/xwiki.properties"; private static final long PROCESS_FINISH_TIMEOUT = 5 * 60L * 1000L; private static final int VERIFY_RUNNING_XWIKI_AT_START_TIMEOUT = Integer.valueOf(System.getProperty("xwiki.test.verifyRunningXWikiAtStartTimeout", "15")); private static final int DEBUG_PORT = 5005; private int port; private int stopPort; private int rmiPort; private String executionDirectory; private Map<String, String> environment = new HashMap<>(); private DefaultExecuteResultHandler startedProcessHandler; private FileBasedConfigurationBuilder<PropertiesConfiguration> xwikipropertiesBuilder; /** * Was XWiki server already started. We don't try to stop it if it was already started. */ private boolean wasStarted; /** * @see #isManaged() */ private boolean managed; private XWikiWatchdog watchdog = new XWikiWatchdog(); // TODO: Put back timeout of 120 once we understand why on ci.xwiki.org we get xwiki startup timeouts for our // functional tests. private long startTimeout = Long.valueOf(System.getProperty("xwikiExecutionStartTimeout", "240")); private int debugPort ; public XWikiExecutor(int index) { // resolve ports String portString = System.getProperty("xwikiPort" + index); this.port = portString != null ? Integer.valueOf(portString) : (Integer.valueOf(DEFAULT_PORT) + index); String stopPortString = System.getProperty("xwikiStopPort" + index); this.stopPort = stopPortString != null ? Integer.valueOf(stopPortString) : (Integer.valueOf(DEFAULT_STOPPORT) - index); String rmiPortString = System.getProperty("rmiPort" + index); this.rmiPort = rmiPortString != null ? Integer.valueOf(rmiPortString) : (Integer.valueOf(DEFAULT_RMIPORT) + index); this.debugPort = DEBUG_PORT + index; // Resolve the execution directory, which should point to a location where an XWiki distribution is located // and can be started (directory where the start_xwiki.sh|bat files are located). this.executionDirectory = System.getProperty("xwikiExecutionDirectory" + index); if (this.executionDirectory == null) { this.executionDirectory = DEFAULT_EXECUTION_DIRECTORY; if (this.executionDirectory == null) { if (BASEDIR != null) { this.executionDirectory = BASEDIR + '/'; } else { this.executionDirectory = ""; } this.executionDirectory += "target/xwiki"; } if (index > 0) { this.executionDirectory += "-" + index; } } // Make sure the execution directory exists try { FileUtils.forceMkdir(new File(this.executionDirectory)); } catch (Exception e) { throw new RuntimeException(String.format("Failed to create directory [%s]", this.executionDirectory), e); } } public int getPort() { return this.port; } public int getStopPort() { return this.stopPort; } public int getRMIPort() { return this.rmiPort; } public int getDebugPort() { return this.debugPort; } public String getExecutionDirectory() { if (this.executionDirectory == null) { throw new RuntimeException("Invalid configuration for the execution directory. The " + "[xwikiExecutionDirectory] system property must be specified."); } return this.executionDirectory; } public void setXWikiOpts(String opts) { addEnvironmentVariable("XWIKI_OPTS", opts); } /** * Change the timeout checked when starting and initializing XWiki. * * @since 10.11RC1 */ public void setTimeoutSeconds(long timeoutSeconds) { this.startTimeout = timeoutSeconds; } public void addEnvironmentVariable(String key, String value) { this.environment.put(key, value); } /** * @return true the XWiki instance was (successfully) started by the executor itself (other possibilities being * failed startup or already running instance). * @since 9.7RC1 */ public boolean isManaged() { return this.managed; } /** * Start XWiki using the following strategy: * <ul> * <li>If the {@code xwiki.test.startXWiki} system property is set to "false" then don't start/stop XWiki</li> * <li>If the {@link #VERIFY_RUNNING_XWIKI_AT_START} property is set then checks if an XWiki instance is already * running before trying to start XWiki and if so, reuse it and don't start XWiki</li> * <li>If the {@link #VERIFY_RUNNING_XWIKI_AT_START} property is set to false then verify if some XWiki instance is * already running by verifying if the port is free and fail if so. Otherwise start XWiki.</li> * </ul> * * @throws Exception when failing to start XWiki */ public void start() throws Exception { if (!SHOULD_START_XWIKI) { return; } this.wasStarted = false; if (VERIFY_RUNNING_XWIKI_AT_START.equals("true")) { LOGGER.info("Checking if an XWiki server is already started at [{}]", getURL()); // First, verify if XWiki is started. If it is then don't start it again. this.wasStarted = !this.watchdog.isXWikiStarted(getURL(), VERIFY_RUNNING_XWIKI_AT_START_TIMEOUT).timedOut; } if (!this.wasStarted) { LOGGER.info("Stopping any potentially running XWiki server at [{}]", getURL()); stopInternal(); LOGGER.info("Starting XWiki server at [{}], using stop port [{}] and RMI port [{}]", getURL(), getStopPort(), getRMIPort()); startXWiki(); waitForXWikiToLoad(); this.managed = true; } else { LOGGER.info("XWiki server is already started at [{}]", getURL()); } } private DefaultExecuteResultHandler executeCommand(String commandLine) throws Exception { // The command line to execute CommandLine command = CommandLine.parse(commandLine); // Execute the process asynchronously so that we don't block. DefaultExecuteResultHandler resultHandler = new XWikiDefaultExecuteResultHandler(commandLine); // Send Process output and error streams to our logger. PumpStreamHandler streamHandler = new PumpStreamHandler(new XWikiLogOutputStream()); // Make sure we end the process when the JVM exits ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer(); // Prevent the process from running indefinitely and kill it after 1 hour... // FIXME: some tests requires XWiki to run more than 1 hour (escaping and webstandards tests) // so increasing this to 2 hours ExecuteWatchdog watchDog = new ExecuteWatchdog(120L * 60L * 1000L); // The executor to execute the command DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(streamHandler); executor.setWorkingDirectory(new File(getExecutionDirectory())); executor.setProcessDestroyer(processDestroyer); executor.setWatchdog(watchDog); // Inherit the current process's environment variables and add the user-defined ones @SuppressWarnings("unchecked") Map<String, String> newEnvironment = EnvironmentUtils.getProcEnvironment(); newEnvironment.putAll(this.environment); executor.execute(command, newEnvironment, resultHandler); return resultHandler; } /** * Starts XWiki and returns immediately. */ private void startXWiki() throws Exception { File dir = new File(getExecutionDirectory()); if (dir.exists()) { String startCommand = getDefaultStartCommand(getPort(), getStopPort(), getRMIPort(), getDebugPort()); LOGGER.debug("Executing command: [{}]", startCommand); this.startedProcessHandler = executeCommand(startCommand); } else { throw new Exception(String.format("Invalid directory from where to start XWiki [%s]. If you're starting " + "a functional test from your IDE, make sure to either have started an XWiki instance beforehand or " + "configure your IDE so that either the [basedir] or [xwikiExecutionDirectory] properties have been " + "defined so that the test framework can start XWiki for you. If you set [basedir] make it point to " + "the directory containing the [target/] directory of your project. The test framework will then try " + "to locate an XWiki instance in [<basedir>/target/xwiki]. If the XWiki instance you wish to start is " + "elsewhere then define the [xwikiExecutionDirectory] System property to point to it.", this.executionDirectory)); } } private void waitForXWikiToLoad() throws Exception { // Wait till the main page becomes available which means the server is started fine LOGGER.info("Checking that XWiki is up and running..."); // If we're in debug mode then don't use a timeout (or rather use a very long one - we use 1 day) since we'll // start XWiki in debug mode and wait to connect to it (suspend = true). long timeout = DEBUG ? 60*60*24 : this.startTimeout; WatchdogResponse response = this.watchdog.isXWikiStarted(getURL(), timeout); if (response.timedOut) { String message = String.format("Failed to start XWiki in [%s] seconds, last error code [%s], message [%s]", timeout, response.responseCode, response.responseBody); LOGGER.info(message); stop(); throw new RuntimeException(message); } else { LOGGER.info("Server is answering to [{}]... cool", getURL()); } } public void stop() throws Exception { if (!SHOULD_START_XWIKI) { return; } LOGGER.debug("Checking if we need to stop the XWiki server running at [{}]...", getURL()); // Do not try to stop XWiki if we've not been successful in starting it! if (!this.managed) { return; } // Stop XWiki if it was started by start() if (!this.wasStarted) { stopInternal(); // Now wait for the start process to be stopped, waiting a max of 5 minutes! if (this.startedProcessHandler != null) { waitForProcessToFinish(this.startedProcessHandler, PROCESS_FINISH_TIMEOUT); } LOGGER.info("XWiki server running at [{}] has been stopped", getURL()); } else { LOGGER.info("XWiki server not stopped since we didn't start it (it was already started)"); } } private void stopInternal() throws Exception { String stopCommand = getDefaultStopCommand(getPort(), getStopPort()); LOGGER.debug("Executing command: [{}]", stopCommand); DefaultExecuteResultHandler stopProcessHandler = executeCommand(stopCommand); // First wait for the stop process to have stopped, waiting a max of 5 minutes! // It's going to stop the start process... waitForProcessToFinish(stopProcessHandler, PROCESS_FINISH_TIMEOUT); } private void waitForProcessToFinish(DefaultExecuteResultHandler handler, long timeout) throws Exception { // Wait for the process to finish. handler.waitFor(timeout); // Check the exit value and fail the test if the process has not properly finished. if (handler.getExitValue() != 0 || !handler.hasResult()) { if (handler.getExitValue() == 143) { LOGGER.warn("XWiki instance was killed with SIGTERM (usually mean it took to long to stop by itself)"); } else { String message = String.format("Process failed to close properly after [%d] seconds, process ended [%b].", timeout, handler.hasResult()); if (handler.hasResult()) { message = String.format("%s Exit code [%d], message [%s].", message, handler.getExitValue(), handler.getException().getMessage()); } message = String.format("%s Failing test.", message); throw new RuntimeException(message); } } } public String getWebInfDirectory() { return getExecutionDirectory() + WEBINF_PATH; } public String getXWikiCfgPath() { return getExecutionDirectory() + XWIKICFG_PATH; } public String getXWikiPropertiesPath() { return getExecutionDirectory() + XWIKIPROPERTIES_PATH; } public Properties loadXWikiCfg() throws Exception { return getProperties(getXWikiCfgPath()); } public Properties loadXWikiProperties() throws Exception { return getProperties(getXWikiPropertiesPath()); } public PropertiesConfiguration loadXWikiPropertiesConfiguration() throws Exception { return getPropertiesConfiguration(getXWikiPropertiesPath()); } /** * @deprecated since 4.2M1 use {@link #getPropertiesConfiguration(String)} instead */ @Deprecated private Properties getProperties(String path) throws Exception { Properties properties = new Properties(); FileInputStream fis; try { fis = new FileInputStream(path); try { properties.load(fis); } finally { fis.close(); } } catch (FileNotFoundException e) { LOGGER.debug("Failed to load properties [{}]", path, e); } return properties; } /** * @since 4.2M1 */ private PropertiesConfiguration getPropertiesConfiguration(String path) throws ConfigurationException { this.xwikipropertiesBuilder = new FileBasedConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class) .configure(new Parameters().properties().setListDelimiterHandler(new DefaultListDelimiterHandler(',')) .setFileName(path)); return xwikipropertiesBuilder.getConfiguration(); } public void saveXWikiCfg(Properties properties) throws Exception { saveProperties(getXWikiCfgPath(), properties); } /** * @deprecated since 4.2M1 use {@link #saveXWikiProperties()} instead */ @Deprecated public void saveXWikiProperties(Properties properties) throws Exception { saveProperties(getXWikiPropertiesPath(), properties); } /** * @since 4.2M1 */ public void saveXWikiProperties() throws Exception { this.xwikipropertiesBuilder.save(); } private void saveProperties(String path, Properties properties) throws Exception { FileOutputStream fos = new FileOutputStream(path); try { properties.store(fos, null); } finally { fos.close(); } } public String getURL() { // We use "get" action for 2 reasons: // 1) the page loads faster since it doesn't need to display the skin // 2) if the page doesn't exist it won't return a 404 HTTP Response code return URL + ":" + getPort() + DEFAULT_CONTEXT + "/bin/get/Main/"; } private String getDefaultStartCommand(int port, int stopPort, int rmiPort, int debugPort) { String startCommand = START_COMMAND; if (startCommand == null) { String scriptNamePrefix = DEBUG ? "start_xwiki_debug" : "start_xwiki"; if (SystemUtils.IS_OS_WINDOWS) { startCommand = String.format("cmd /c %s.bat %s %s", scriptNamePrefix, port, stopPort); } else { String debugParams = DEBUG ? String.format("-dp %d --suspend", debugPort) : ""; startCommand = String.format("bash %s.sh -p %s -sp %s %s -ni", scriptNamePrefix, port, stopPort, debugParams); } } else { startCommand = startCommand.replaceFirst(DEFAULT_PORT, String.valueOf(port)); startCommand = startCommand.replaceFirst(DEFAULT_STOPPORT, String.valueOf(stopPort)); startCommand = startCommand.replaceFirst(DEFAULT_RMIPORT, String.valueOf(rmiPort)); } return startCommand; } private String getDefaultStopCommand(int port, int stopPort) { String stopCommand = STOP_COMMAND; if (stopCommand == null) { if (SystemUtils.IS_OS_WINDOWS) { stopCommand = String.format("cmd /c stop_xwiki.bat %s", stopPort); } else { stopCommand = String.format("bash stop_xwiki.sh -p %s -sp %s", port, stopPort); } } else { stopCommand = stopCommand.replaceFirst(DEFAULT_PORT, String.valueOf(port)); stopCommand = stopCommand.replaceFirst(DEFAULT_STOPPORT, String.valueOf(stopPort)); } return stopCommand; } }
package com.ls.utils; import com.ls.drupalcon.model.PreferencesManager; import org.jetbrains.annotations.NotNull; import android.content.Context; import android.support.annotation.Nullable; import android.text.format.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class DateUtils { private SimpleDateFormat mDateFormat; private TimeZone mTimezone; private static DateUtils mUtils; public DateUtils() { mDateFormat = new SimpleDateFormat("", Locale.ENGLISH); mTimezone = PreferencesManager.getInstance().getServerTimeZoneObject(); mDateFormat.setTimeZone(mTimezone); } public synchronized void setTimezone(String theTimezoneId) { mTimezone = TimeZone.getTimeZone(theTimezoneId); mDateFormat.setTimeZone(mTimezone); } @NotNull public static DateUtils getInstance() { if (mUtils == null) { mUtils = new DateUtils(); } return mUtils; } @Nullable public synchronized Date convertEventDayDate(String day) { mDateFormat.applyPattern("d-MM-yyyy"); try { return mDateFormat.parse(day); } catch (ParseException e) { e.printStackTrace(); } return null; } public boolean isToday(long millis) { boolean isToday = false; Calendar currCalendar = Calendar.getInstance(); currCalendar.setTimeZone(mTimezone); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(millis); calendar.setTimeZone(mTimezone); int currYear = currCalendar.get(Calendar.YEAR); int currMonth = currCalendar.get(Calendar.MONTH); int currDay = currCalendar.get(Calendar.DAY_OF_MONTH); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); if (currYear == year && currMonth == month && currDay == day) { isToday = true; } return isToday; } public boolean isAfterCurrentFate(long millis) { boolean isAfter = false; Calendar currCalendar = Calendar.getInstance(); currCalendar.setTimeZone(mTimezone); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(millis); calendar.setTimeZone(mTimezone); if (calendar.after(currCalendar)) { isAfter = true; } return isAfter; } public synchronized String getTime(Context context, long millis) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(millis); calendar.setTimeZone(mTimezone); if (DateFormat.is24HourFormat(context)) { mDateFormat.applyPattern("HH:mm"); return mDateFormat.format(new Date(millis)); } else { mDateFormat.applyPattern("hh:mm aa"); return mDateFormat.format(new Date(millis)); } } public String getWeekDay(long millis) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(millis); calendar.setTimeZone(mTimezone); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US); } public synchronized String getWeekNameAndDate(long millis) { mDateFormat.applyPattern("EEE d"); return mDateFormat.format(new Date(millis)); } public TimeZone getTimeZone() { return mTimezone; } }
package com.ideaheap; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class LoopsBasedCalculator { public Map<String, String> getStringTransition( final Set<String> stringSet, final Map<String, Double> stringCosts) { String[] stringArray = stringSet.toArray(new String[0]); Map.Entry<String, Double>[] stringCostArray = stringCosts .entrySet() .toArray(new Map.Entry[0]); return stringCosts.keySet().parallelStream().collect( Collectors.toConcurrentMap( (state) -> state, (state) -> stringTransitionCost( state, stringArray, stringCostArray ) ) ); } private String stringTransitionCost( final String state, final String[] stringSet, final Map.Entry<String, Double>[] expectedUtilities) { String maxString = null; double maxStringValue = Double.NEGATIVE_INFINITY; for (String str : stringSet) { double stringValue = 0.0; for (Map.Entry<String, Double> entry : expectedUtilities) { stringValue += getStateProbability(state, str, entry.getKey()) * entry.getValue(); } if (maxString == null || stringValue > maxStringValue) { maxStringValue = stringValue; maxString = str; } } return maxString; } private Double getStateProbability(String state, String act, String key) { return 5.0; } }
package com.imsweb.seerapi.client; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.TimeZone; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; import org.codehaus.jackson.annotate.JsonMethod; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig.Feature; import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion; import org.glassfish.jersey.message.GZipEncoder; import com.imsweb.seerapi.client.disease.Disease; import com.imsweb.seerapi.client.disease.DiseaseChangelogResults; import com.imsweb.seerapi.client.disease.DiseaseSearch; import com.imsweb.seerapi.client.disease.DiseaseSearchResults; import com.imsweb.seerapi.client.disease.DiseaseVersion; import com.imsweb.seerapi.client.disease.PrimarySite; import com.imsweb.seerapi.client.disease.SamePrimaries; import com.imsweb.seerapi.client.disease.SiteCategory; import com.imsweb.seerapi.client.glossary.Glossary; import com.imsweb.seerapi.client.glossary.GlossaryChangelogResults; import com.imsweb.seerapi.client.glossary.GlossarySearch; import com.imsweb.seerapi.client.glossary.GlossarySearchResults; import com.imsweb.seerapi.client.glossary.GlossaryVersion; import com.imsweb.seerapi.client.naaccr.NaaccrField; import com.imsweb.seerapi.client.naaccr.NaaccrFieldName; import com.imsweb.seerapi.client.naaccr.NaaccrVersion; import com.imsweb.seerapi.client.rx.Rx; import com.imsweb.seerapi.client.rx.RxChangelogResults; import com.imsweb.seerapi.client.rx.RxSearch; import com.imsweb.seerapi.client.rx.RxSearchResults; import com.imsweb.seerapi.client.rx.RxVersion; import com.imsweb.seerapi.client.shared.Version; import com.imsweb.seerapi.client.siterecode.SiteRecode; import com.imsweb.seerapi.client.staging.SchemaLookup; import com.imsweb.seerapi.client.staging.StagingAlgorithm; import com.imsweb.seerapi.client.staging.StagingData; import com.imsweb.seerapi.client.staging.StagingSchema; import com.imsweb.seerapi.client.staging.StagingSchemaInfo; import com.imsweb.seerapi.client.staging.StagingTable; import com.imsweb.seerapi.client.staging.StagingVersion; import com.imsweb.seerapi.client.surgery.SurgeryTable; /** * Entry point for Java API into SEER*API. */ public final class SeerApi { // output all dates in ISO-8061 format and UTC time private static final DateFormat _DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // define the JSON provider which uses Jackson and a customized ObjectMapper private static final JacksonJsonProvider _JACKSON_PROVIDER = new JacksonJsonProvider(); static { _DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); ObjectMapper mapper = new ObjectMapper(); // do not write null values mapper.configure(Feature.WRITE_NULL_MAP_VALUES, false); mapper.setSerializationInclusion(Inclusion.NON_NULL); // set Date objects to output in readable customized format mapper.configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.setDateFormat(_DATE_FORMAT); mapper.setVisibility(JsonMethod.ALL, Visibility.NONE); mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); _JACKSON_PROVIDER.setMapper(mapper); } private Client _client; private String _baseUrl; private String _apiKey; /** * Creates a client API root object * @param baseUrl base URL for API * @param apiKey API key */ private SeerApi(String baseUrl, String apiKey) { if (baseUrl.endsWith("/")) baseUrl = baseUrl.substring(0, baseUrl.length() - 1); this._baseUrl = baseUrl; this._apiKey = apiKey; _client = ClientBuilder.newClient() .register(_JACKSON_PROVIDER) .register(GZipEncoder.class) .register(ErrorResponseFilter.class); } /** * Creates a connection to the API * @param baseUrl base URL for API * @param apiKey API key * @return a new SeerApi instance */ protected static SeerApi connect(String baseUrl, String apiKey) { return new SeerApi(baseUrl, apiKey); } /** * Helper method to return a base web target * @param path the API path which is added onto the base URL * @return a WebTarget using the base URL and the passed path */ private WebTarget createTarget(String path) { if (_apiKey == null || _apiKey.isEmpty()) throw new IllegalStateException("This operation requires a credential but none is given to the SeerApi constructor"); return _client.target(_baseUrl).path(path); } /** * Builds the default invocation builder. All requests are currently JSON and are GZIP encoded. * @param target the WebTarget for the API call * @return a Builder instance using the passed target and including default header information that is used on all our calls */ private Builder getBuilder(WebTarget target) { return target.request(MediaType.APPLICATION_JSON_TYPE).header("X-SEERAPI-Key", _apiKey).acceptEncoding("gzip"); } /** * Return the version of the SEER Site Recode database. * @return a String representing the database version */ public String siteRecodeVersion() { WebTarget target = createTarget("/recode/version"); return getBuilder(target).get(Version.class).getVersion(); } /** * Return the SEER Site Group for the site/histology combination, or 99999 if the combination is unknown. * @param site Primary Site O3 * @param histology Histology O3 * @return a SiteRecode object based on the site and histology */ public SiteRecode siteRecode(String site, String histology) { WebTarget target = createTarget("/recode/sitegroup").queryParam("site", site).queryParam("hist", histology); return getBuilder(target).get(SiteRecode.class); } /** * Return a collection of NaaccrVersion objects which descibe the available versions * @return a list of the available NAACCR versions and information about each of them */ public List<NaaccrVersion> naaccrVersions() { WebTarget target = createTarget("/naaccr/versions"); return getBuilder(target).get(new GenericType<List<NaaccrVersion>>() {}); } /** * Return a list of all the field identifiers and names from a specified NAACCR version * @param version NAACCR version * @return a list of NaaccrFieldName objects */ public List<NaaccrFieldName> naaccrFieldNames(String version) { WebTarget target = createTarget("/naaccr/{version}").resolveTemplate("version", version); return getBuilder(target).get(new GenericType<List<NaaccrFieldName>>() {}); } /** * Return a list of all the field identifiers and names from a specified NAACCR version * @param version NAACCR version * @param item NAACCR item number * @return a list of NaaccrFieldName objects */ public NaaccrField naaccrField(String version, Integer item) { WebTarget target = createTarget("/naaccr/{version}/item/{item}").resolveTemplate("version", version).resolveTemplate("item", item); return getBuilder(target).get(NaaccrField.class); } /** * Return a list of all disease versions and information about them * @return a list of DiseaseVersion objects */ public List<DiseaseVersion> diseaseVersions() { WebTarget target = createTarget("/disease/versions"); return getBuilder(target).get(new GenericType<List<DiseaseVersion>>() {}); } /** * Return the changelog entries for the passed database version * @param version Disease version * @param fromDate if not null, only include changes from this date forward (YYYY-MM-DD) * @param toDate if not null, only include changes prior to this date (YYYY-MM-DD) * @param count if not null, limit the number returned * @return a list of DiseaseChangelogResults objects */ public DiseaseChangelogResults diseaseChangelogs(String version, String fromDate, String toDate, Integer count) { WebTarget target = createTarget("/disease/{version}/changelog") .resolveTemplate("version", version) .queryParam("from", fromDate) .queryParam("to", toDate) .queryParam("count", count); return getBuilder(target).get(DiseaseChangelogResults.class); } /** * Return a list of matching diseases * @param version Disease version * @param search DiseaseSearch object * @return a DiseaseSearchResults object */ public DiseaseSearchResults diseaseSearch(String version, DiseaseSearch search) { WebTarget target = createTarget("/disease/{version}").resolveTemplate("version", version); target = target.queryParam("q", search.getQuery()) .queryParam("type", search.getType()) .queryParam("site_category", search.getSiteCategory()) .queryParam("mode", search.getMode()) .queryParam("status", search.getStatus()) .queryParam("assigned_to", search.getAssignedTo()) .queryParam("modified_from", search.getModifiedFrom()) .queryParam("modified_to", search.getModifiedTo()) .queryParam("published_from", search.getPublishedFrom()) .queryParam("published_to", search.getPublishedTo()) .queryParam("been_published", search.getBeenPublished()) .queryParam("hidden", search.getHidden()) .queryParam("count", search.getCount()) .queryParam("offset", search.getOffset()) .queryParam("order", search.getOrderBy()) .queryParam("output_type", search.getOutputType()); return getBuilder(target).get(DiseaseSearchResults.class); } /** * Return a complete disease entity based in identifier. Note that by default the disease entity does not include relevant glossary references. * @param version Disease version * @param id Disease identifier * @return a Disease object */ public Disease diseaseById(String version, String id) { return diseaseById(version, id, false); } /** * Return a complete disease entity based in identifier * @param version Disease version * @param id Disease identifier * @param includeGlossary if true, include the glossary * @return a Disease object */ public Disease diseaseById(String version, String id, boolean includeGlossary) { WebTarget target = createTarget("/disease/{version}/id/{id}") .resolveTemplate("version", version) .resolveTemplate("id", id) .queryParam("glossary", includeGlossary); return getBuilder(target).get(Disease.class); } /** * Return a list of all primary sites and labels * @return a List of PrimarySite objects */ public List<PrimarySite> diseasePrimarySites() { WebTarget target = createTarget("/disease/primary_site"); return getBuilder(target).get(new GenericType<List<PrimarySite>>() {}); } /** * Return a single primary site and label * @param primarySite Primary Site O3 * @return a PrimarySite object */ public List<PrimarySite> diseasePrimarySiteCode(String primarySite) { WebTarget target = createTarget("/disease/primary_site/{code}").resolveTemplate("code", primarySite); return getBuilder(target).get(new GenericType<List<PrimarySite>>() {}); } /** * Return a complete list of site categories and definitions * @return a list of SiteCategory objects */ public List<SiteCategory> diseaseSiteCategories() { WebTarget target = createTarget("/disease/site_categories"); return getBuilder(target).get(new GenericType<List<SiteCategory>>() {}); } /** * Return whether the 2 morphologies represent the same primary for the given year. * @param version Disease version * @param morphology1 ICD O3 Morphology * @param morphology2 ICD O3 Morphology * @param year Year of Diagnosis * @return a SamePrimary object */ public SamePrimaries diseaseSamePrimaries(String version, String morphology1, String morphology2, String year) { WebTarget target = createTarget("/disease/{version}/same_primary") .resolveTemplate("version", version) .queryParam("d1", morphology1) .queryParam("d2", morphology2) .queryParam("year", year); return getBuilder(target).get(SamePrimaries.class); } /** * Returns the reportable year range of the supplied disease. * @param disease Disease object * @return a Disease object with the reportability field filled in */ public Disease diseaseReportability(Disease disease) { WebTarget target = createTarget("/disease/reportability"); return getBuilder(target).post(Entity.json(disease), Disease.class); } /** * Return a list of all glossary versions and information about them * @return a list of GlossaryVersion objects */ public List<GlossaryVersion> glossaryVersions() { WebTarget target = createTarget("/glossary/versions"); return getBuilder(target).get(new GenericType<List<GlossaryVersion>>() {}); } /** * Return a complete glossary entity based in identifier * @param version Glossary version * @param id Glossary identifier * @return a Glossary object */ public Glossary glossaryById(String version, String id) { WebTarget target = createTarget("/glossary/{version}/id/{id}").resolveTemplate("version", version).resolveTemplate("id", id); return getBuilder(target).get(Glossary.class); } /** * Return a list of matching glossaries * @param version Glossary version * @param search GlossarySearch object * @return a GlossarySearchResults object */ public GlossarySearchResults glossarySearch(String version, GlossarySearch search) { WebTarget target = createTarget("/glossary/{version}").resolveTemplate("version", version); target = target.queryParam("q", search.getQuery()) .queryParam("mode", search.getMode()) .queryParam("status", search.getStatus()) .queryParam("assigned_to", search.getAssignedTo()) .queryParam("modified_from", search.getModifiedFrom()) .queryParam("modified_to", search.getModifiedTo()) .queryParam("published_from", search.getPublishedFrom()) .queryParam("published_to", search.getPublishedTo()) .queryParam("been_published", search.getBeenPublished()) .queryParam("hidden", search.getHidden()) .queryParam("count", search.getCount()) .queryParam("offset", search.getOffset()) .queryParam("order", search.getOrderBy()) .queryParam("output_type", search.getOutputType()); // list parameters need to passed as an object array to get multiple query parameters; otherwise there is a single query // parameter with a list of values, which the API won't understand if (search.getCategory() != null) target = target.queryParam("category", search.getCategory().toArray()); return getBuilder(target).get(GlossarySearchResults.class); } /** * Return the changelog entries for the passed database version * @param version Glossary version * @param fromDate if not null, only include changes from this date forward (YYYY-MM-DD) * @param toDate if not null, only include changes prior to this date (YYYY-MM-DD) * @param count if not null, limit the number returned * @return a list of GlossaryChangelogResults objects */ public GlossaryChangelogResults glossaryChangelogs(String version, String fromDate, String toDate, Integer count) { WebTarget target = createTarget("/glossary/{version}/changelog") .resolveTemplate("version", version) .queryParam("from", fromDate) .queryParam("to", toDate) .queryParam("count", count); return getBuilder(target).get(GlossaryChangelogResults.class); } /** * Return a collection of Version objects which descibe the available versions * @return a list of the available site-specific surgery versions and information about each of them */ public List<Version> siteSpecificSurgeryVersions() { WebTarget target = createTarget("/surgery/versions"); return getBuilder(target).get(new GenericType<List<Version>>() {}); } /** * Return a list of all the site-specific surgery table titles from a specific version * @param version version * @return a list of site-specific surgery table titles */ public List<String> siteSpecificSurgeryTables(String version) { WebTarget target = createTarget("/surgery/{version}/tables").resolveTemplate("version", version); return getBuilder(target).get(new GenericType<List<String>>() {}); } /** * Return a specific site-specific surgary table from a specific version * @param version version * @param title site title (optional if the site/histology is provided) * @param site primary site (optional if the title is provided) * @param histology histology (optional if the title is provided) * @return a site-specific surgery table */ public SurgeryTable siteSpecificSurgeryTable(String version, String title, String site, String histology) { WebTarget target = createTarget("/surgery/{version}/table") .resolveTemplate("version", version) .queryParam("title", title) .queryParam("site", site) .queryParam("hist", histology); return getBuilder(target).get(SurgeryTable.class); } /** * Return a list of all Rx versions and information about them. Note that by default the Rx entity does not include relevant glossary references. * @return a list of RxVersion objects */ public List<RxVersion> rxVersions() { WebTarget target = createTarget("/rx/versions"); return getBuilder(target).get(new GenericType<List<RxVersion>>() {}); } /** * Return a complete Rx entity based in identifier * @param version Rx version * @param id Rx identifier * @return a Rx object */ public Rx rxById(String version, String id) { return rxById(version, id, false); } /** * Return a complete Rx entity based in identifier * @param version Rx version * @param id Rx identifier * @param includeGlossary if true, include the glossary * @return a Rx object */ public Rx rxById(String version, String id, boolean includeGlossary) { WebTarget target = createTarget("/rx/{version}/id/{id}") .resolveTemplate("version", version) .resolveTemplate("id", id) .queryParam("glossary", includeGlossary); return getBuilder(target).get(Rx.class); } /** * Return a list of matching Rx entities * @param version Rx version * @param search RxSearch object * @return a RxSearchResults object */ public RxSearchResults rxSearch(String version, RxSearch search) { WebTarget target = createTarget("/rx/{version}").resolveTemplate("version", version); target = target.queryParam("q", search.getQuery()) .queryParam("type", search.getType()) .queryParam("do_not_code", search.getDoNotCode()) .queryParam("category", search.getCategory()) .queryParam("mode", search.getMode()) .queryParam("status", search.getStatus()) .queryParam("assigned_to", search.getAssignedTo()) .queryParam("modified_from", search.getModifiedFrom()) .queryParam("modified_to", search.getModifiedTo()) .queryParam("published_from", search.getPublishedFrom()) .queryParam("published_to", search.getPublishedTo()) .queryParam("been_published", search.getBeenPublished()) .queryParam("hidden", search.getHidden()) .queryParam("count", search.getCount()) .queryParam("offset", search.getOffset()) .queryParam("order", search.getOrderBy()) .queryParam("output_type", search.getOutputType()); return getBuilder(target).get(RxSearchResults.class); } /** * Return the changelog entries for the passed database version * @param version Rx version * @param fromDate if not null, only include changes from this date forward (YYYY-MM-DD) * @param toDate if not null, only include changes prior to this date (YYYY-MM-DD) * @param count if not null, limit the number returned * @return a list of RxChangelogResults objects */ public RxChangelogResults rxChangelogs(String version, String fromDate, String toDate, Integer count) { WebTarget target = createTarget("/rx/{version}/changelog") .resolveTemplate("version", version) .queryParam("from", fromDate) .queryParam("to", toDate) .queryParam("count", count); return getBuilder(target).get(RxChangelogResults.class); } /** * Return a list of all supported staging algorithms * @return a list of StagingAlgorithm objects */ public List<StagingAlgorithm> stagingAlgorithms() { WebTarget target = createTarget("/staging/algorithms"); return getBuilder(target).get(new GenericType<List<StagingAlgorithm>>() {}); } /** * Return a list of supported versions for the passed algorithm * @param algorithm an algorithm identifier * @return */ public List<StagingVersion> stagingAlgorithmVersions(String algorithm) { WebTarget target = createTarget("/staging/{algorithm}/versions").resolveTemplate("algorithm", algorithm); return getBuilder(target).get(new GenericType<List<StagingVersion>>() {}); } /** * Return a list of matching schemas * @param algorithm an algorithm identifier * @param version a version * @param query an optional text query * @return a list of schemas */ public List<StagingSchemaInfo> stagingSchemas(String algorithm, String version, String query) { WebTarget target = createTarget("/staging/{algorithm}/{version}/schemas") .resolveTemplate("algorithm", algorithm) .resolveTemplate("version", version) .queryParam("q", query); return getBuilder(target).get(new GenericType<List<StagingSchemaInfo>>() {}); } /** * Perform a schema lookup * @param algorithm an algorithm identifier * @param version a version * @param data a StagingData object containing the input for the lookup * @return */ public List<StagingSchemaInfo> stagingSchemaLookup(String algorithm, String version, SchemaLookup data) { WebTarget target = createTarget("/staging/{algorithm}/{version}/schemas/lookup") .resolveTemplate("algorithm", algorithm) .resolveTemplate("version", version); return getBuilder(target).post(Entity.json(data.getInputs()), new GenericType<List<StagingSchemaInfo>>() {}); } /** * Return a single schema definition by schema identifier * @param algorithm an algorithm identifier * @param version a version * @param id a schema identifier * @return a schema object */ public StagingSchema stagingSchemaById(String algorithm, String version, String id) { WebTarget target = createTarget("/staging/{algorithm}/{version}/schema/{id}") .resolveTemplate("algorithm", algorithm) .resolveTemplate("version", version) .resolveTemplate("id", id); return getBuilder(target).get(StagingSchema.class); } /** * Return a list of tables which are involved in the specified schema * @param algorithm an algorithm identifier * @param version a version * @param id a schema identifier */ public List<StagingTable> stagingSchemaInvolvedTables(String algorithm, String version, String id) { WebTarget target = createTarget("/staging/{algorithm}/{version}/schema/{id}/tables") .resolveTemplate("algorithm", algorithm) .resolveTemplate("version", version) .resolveTemplate("id", id); return getBuilder(target).get(new GenericType<List<StagingTable>>() {}); } /** * Return a list of matching tables * @param algorithm an algorithm identifier * @param version a version * @param query an optional text query * @return */ public List<StagingTable> stagingTables(String algorithm, String version, String query) { WebTarget target = createTarget("/staging/{algorithm}/{version}/tables") .resolveTemplate("algorithm", algorithm) .resolveTemplate("version", version) .queryParam("q", query); return getBuilder(target).get(new GenericType<List<StagingTable>>() {}); } /** * Return a single table definition by table identifier * @param algorithm an algorithm identifier * @param version a version * @param id a table identifier * @return */ public StagingTable stagingTableById(String algorithm, String version, String id) { WebTarget target = createTarget("/staging/{algorithm}/{version}/table/{id}") .resolveTemplate("algorithm", algorithm) .resolveTemplate("version", version) .resolveTemplate("id", id); return getBuilder(target).get(StagingTable.class); } /** * Return a list of schemas which the specified table is involved in * @param algorithm an algorithm identifier * @param version a version * @param id a table identifier */ public List<StagingSchema> stagingTableInvolvedSchemas(String algorithm, String version, String id) { WebTarget target = createTarget("/staging/{algorithm}/{version}/table/{id}/schemas") .resolveTemplate("algorithm", algorithm) .resolveTemplate("version", version) .resolveTemplate("id", id); return getBuilder(target).get(new GenericType<List<StagingSchema>>() {}); } /** * Stage the passed input * @param algorithm an algorithm identifier * @param version a version * @param data a StagingData object containing the input for the staging call * @return */ public StagingData stagingStage(String algorithm, String version, StagingData data) { WebTarget target = createTarget("/staging/{algorithm}/{version}/stage") .resolveTemplate("algorithm", algorithm) .resolveTemplate("version", version); return getBuilder(target).post(Entity.json(data.getInput()), StagingData.class); } }
package org.orbeon.oxf.xforms.processor; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Attribute; import org.orbeon.oxf.test.ResourceManagerTestBase; import org.orbeon.oxf.xforms.xbl.XBLUtils; import org.orbeon.oxf.xforms.XFormsConstants; import org.orbeon.oxf.xml.XMLUtils; import org.orbeon.oxf.xml.XPathUtils; import org.orbeon.oxf.xml.XMLConstants; import org.orbeon.oxf.xml.dom4j.Dom4jUtils; import org.orbeon.oxf.util.XPathCache; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.saxon.dom4j.DocumentWrapper; import org.orbeon.saxon.dom4j.NodeWrapper; import org.orbeon.saxon.Configuration; import java.util.HashMap; import java.util.Map; import java.util.List; public class XFormsDocumentAnnotatorContentHandlerTest extends ResourceManagerTestBase { private static final HashMap BASIC_NAMESPACE_MAPPINGS = new HashMap(); static { BASIC_NAMESPACE_MAPPINGS.put(XFormsConstants.XFORMS_PREFIX, XFormsConstants.XFORMS_NAMESPACE_URI); BASIC_NAMESPACE_MAPPINGS.put(XFormsConstants.XXFORMS_PREFIX, XFormsConstants.XXFORMS_NAMESPACE_URI); BASIC_NAMESPACE_MAPPINGS.put(XFormsConstants.XML_EVENTS_PREFIX, XFormsConstants.XML_EVENTS_NAMESPACE_URI); BASIC_NAMESPACE_MAPPINGS.put(XMLConstants.XHTML_PREFIX, XMLConstants.XHTML_NAMESPACE_URI); } public void testFormNamespaceElements() { final Map mappings = new HashMap(); final XFormsDocumentAnnotatorContentHandler ch = new XFormsDocumentAnnotatorContentHandler(mappings); XMLUtils.urlToSAX("oxf:/org/orbeon/oxf/xforms/processor/test-form.xml", ch, false, false); // Test that ns information is provided for those elements Map result = (Map) mappings.get("output-in-title"); assertNotNull(result); result = (Map) mappings.get("html"); assertNotNull(result); result = (Map) mappings.get("main-instance"); assertNotNull(result); result = (Map) mappings.get("dateTime-component"); assertNotNull(result); result = (Map) mappings.get("dateTime1-control"); assertNotNull(result); result = (Map) mappings.get("value1-control"); assertNotNull(result); result = (Map) mappings.get("output-in-label"); assertNotNull(result); result = (Map) mappings.get("img-in-label"); assertNotNull(result); result = (Map) mappings.get("span"); assertNotNull(result); // Test that ns information is NOT provided for those elements (because processed as part of shadow tree processing) result = (Map) mappings.get("instance-in-xbl"); assertNull(result); result = (Map) mappings.get("div-in-xbl"); assertNull(result); // Test that ns information is NOT provided for those elements (because in instances or schemas) result = (Map) mappings.get("instance-root"); assertNull(result); result = (Map) mappings.get("instance-value"); assertNull(result); result = (Map) mappings.get("xbl-instance-root"); assertNull(result); result = (Map) mappings.get("xbl-instance-value"); assertNull(result); result = (Map) mappings.get("schema-element"); assertNull(result); } // Test that xxforms:attribute elements with @id and @for were created for public void testXXFormsAttribute() { final Map mappings = new HashMap(); final Document document = Dom4jUtils.readFromURL("oxf:/org/orbeon/oxf/xforms/processor/test-form.xml", false, false); final Document annotatedDocument = XBLUtils.annotateShadowTree(document, mappings, ""); final DocumentWrapper documentWrapper = new DocumentWrapper(annotatedDocument, null, new Configuration()); // Check there is an xxforms:attribute for "html" with correct name List result = XPathCache.evaluate(new PipelineContext(), documentWrapper, "//xxforms:attribute[@for = 'html']", BASIC_NAMESPACE_MAPPINGS, null, null, null, null, null); assertNotNull(result); assertEquals(1, result.size()); Element resultElement = (Element) ((NodeWrapper) result.get(0)).getUnderlyingNode(); assertTrue(resultElement.attributeValue("id").trim().length() > 0); assertEquals("lang", resultElement.attributeValue("name")); // Check there is an xxforms:attribute for "span" with correct name result = XPathCache.evaluate(new PipelineContext(), documentWrapper, "//xxforms:attribute[@for = 'span']", BASIC_NAMESPACE_MAPPINGS, null, null, null, null, null); assertNotNull(result); assertEquals(1, result.size()); resultElement = (Element) ((NodeWrapper) result.get(0)).getUnderlyingNode(); assertTrue(resultElement.attributeValue("id").trim().length() > 0); assertEquals("style", resultElement.attributeValue("name")); } }
package pixelInRadiusFinder; import java.util.ArrayList; public class NaiveRadiusChecker { /** * Computed all integer points centered around the vertex given the radius * r. <br> * This uses a naive radius checker which just checks all points in the * circle's AABB to see if there are within the correct radius or not. * * @param vertex the center of the circle. * @param r the radius of the circle. * @return an arraylist of all integer based points inside the circle. */ public static ArrayList<int[]> getAllPoints(int[] vertex, int r) { ArrayList<int[]> allPts = new ArrayList<int[]>((int) (Math.PI * r * r * 1.5)); int startX = -r; int endX = r; int startY = -r; int endY = r; int rSq = r * r; for (int x = startX; x <= endX; x++) { for (int y = startY; y <= endY; y++) { if ((x * x) + (y * y) <= rSq) { allPts.add(new int[] { x + vertex[0], y + vertex[1] }); } } } return allPts; } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by CDS Networks, Inc. // 4. The name of CDS Networks, Inc. may not be used to endorse or promote // products derived from this software without specific prior // THIS SOFTWARE IS PROVIDED BY CDS NETWORKS, INC. ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL CDS NETWORKS, INC. BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. package net.sourceforge.jtds.jdbc; import java.math.BigDecimal; import java.math.BigInteger; import java.net.Socket; import java.sql.*; import java.util.*; import net.sourceforge.jtds.util.Logger; /** * Implement the TDS protocol. * *@author Craig Spannring *@author Igor Petrovski *@author The FreeTDS project *@created March 17, 2001 *@version $Id: Tds.java,v 1.20 2004-01-29 22:04:23 bheineman Exp $ */ public class Tds implements TdsDefinitions { /** * Cancel the current SQL if the timeout expires. * * @author Craig Spannring * @created March 17, 2001 */ private class TimeoutHandler extends Thread { private Tds tds; private SQLWarningChain wChain; private int timeout; TimeoutHandler(Tds tds, SQLWarningChain wChain, int timeout) { this.tds = tds; this.wChain = wChain; this.timeout = timeout; } public void run() { try { sleep(timeout * 1000); // SAfe The java.sql.Statement.cancel() javadoc says an SQLException // must be thrown if the execution timed out, so that's what // we're going to do. wChain.addException(new SQLException("Query has timed out.")); tds.cancel(); } // Ignore interrupts (this is how we know all was ok) catch( java.lang.InterruptedException e ) { // nop } // SAfe Add an exception if anything else goes wrong catch( Exception ex ) { wChain.addException(new SQLException(ex.toString())); } } } private Socket sock = null; private TdsComm comm = null; private String databaseProductName; private String databaseProductVersion; private int databaseMajorVersion; private TdsConnection connection; // @todo SAfe Remove this field private TdsStatement statement; private String host; private int serverType = -1; // either Tds.SYBASE or Tds.SQLSERVER private int port; // Port numbers are _unsigned_ 16 bit, short is too small private String database; private String user; private String password; private String appName; private String serverName; private String progName; private String domain; //mdb: used for NTLM authentication; if blank, then use sql auth. private String procNameGeneratorName = null; private String procNameTableName = null; // SAfe Access to both of these fields is synchronized on procedureCache private HashMap procedureCache = null; private ArrayList proceduresOfTra = null; private CancelController cancelController = null; private SqlMessage lastServerMessage = null; private EncodingHelper encoder = null; private String charset = null; /** * This is set if the user specifies an explicit charset, so that we'll ignore the server * charset. */ private boolean charsetSpecified = false; // Jens Jakobsen 1999-01-10 // Until TDS_END_TOKEN is reached we assume that there are outstanding // UpdateCounts or ResultSets private boolean moreResults = true; // Added 2000-06-07. Used to control TDS version-specific behavior. private int tdsVer = Tds.TDS70; // RMK 2000-06-12. Time zone offset on client (disregarding DST). private final int zoneOffset = Calendar.getInstance().get(Calendar.ZONE_OFFSET); private int maxRows = 0; /** * Description of the Field */ public final static String cvsVersion = "$Id: Tds.java,v 1.20 2004-01-29 22:04:23 bheineman Exp $"; /** * The last transaction isolation level set for this <code>Tds</code>. */ private int transactionIsolationLevel = java.sql.Connection.TRANSACTION_READ_COMMITTED; /** * The last auto commit mode set on this <code>Tds</code>. */ private boolean autoCommit = true; /** * The context of the result set currently being parsed. */ private Context currentContext; /** * If set character parameters are sent as Unicode (NTEXT, NVARCHAR), * otherwise they are sent using the default encoding. */ private boolean useUnicode; public Tds( TdsConnection connection_, Properties props_) throws java.io.IOException, java.net.UnknownHostException, java.sql.SQLException, net.sourceforge.jtds.jdbc.TdsException { connection = connection_; host = props_.getProperty(PROP_HOST); serverType = Integer.parseInt(props_.getProperty(PROP_SERVERTYPE)); port = Integer.parseInt(props_.getProperty(PROP_PORT)); // SAfe We don't know what database we'll get (probably master) database = null; user = props_.getProperty(PROP_USER); password = props_.getProperty(PROP_PASSWORD); appName = props_.getProperty(PROP_APPNAME, "jTDS"); serverName = props_.getProperty(PROP_SERVERNAME, host); progName = props_.getProperty(PROP_PROGNAME, "jTDS"); String verString = props_.getProperty(PROP_TDS, "7.0"); useUnicode = "true".equalsIgnoreCase(props_.getProperty(PROP_USEUNICODE, "true")); procedureCache = new HashMap(); // new Vector(); // XXX as proceduresOfTra = new ArrayList(); //mdb: if the domain is set, then the user wants NT auth (instead of SQL) domain = props_.getProperty(PROP_DOMAIN, ""); //mdb: get the instance port, if it is specified... String instanceName = props_.getProperty(PROP_INSTANCE, ""); if( instanceName.length() > 0 ) { MSSqlServerInfo info = new MSSqlServerInfo(host); port = info.getPortForInstance(instanceName); if( port == -1 ) throw new SQLException( "Server " + host + " has no instance named " + instanceName); } // XXX This driver doesn't properly support TDS 5.0, AFAIK. // Added 2000-06-07. if (verString.equals("5.0")) { tdsVer = Tds.TDS50; } else if (verString.equals("4.2")) { tdsVer = Tds.TDS42; } cancelController = new CancelController(); // Send the logon packet to the server sock = new Socket(host, port); sock.setTcpNoDelay(true); comm = new TdsComm(sock, tdsVer); String cs = props_.getProperty("CHARSET"); cs = cs==null ? props_.getProperty("charset") : cs; // Adellera charsetSpecified = setCharset(cs); // These are set by initSettings (who uses sqlStatementToInitialize() // to obtain a full setup query). autoCommit = connection.getAutoCommit(); transactionIsolationLevel = connection.getTransactionIsolation(); if( !logon(props_.getProperty(PROP_DBNAME)) ) throw new SQLException("Logon failed. " + lastServerMessage); } /** * Set the <code>TdsStatement</code> currently using the Tds. */ public void setStatement(TdsStatement s) { statement = s; } /** * Get the <code>Statement</code> currently using the Tds. */ public TdsStatement getStatement() { return statement; } /** * Get the <code>Statement</code> currently using the Tds. */ public String getDatabase() { return database; } /* * cvtNativeTypeToJdbcType() */ /** * Return the type of server that we attempted to connect to. * * @return TdsDefinitions.SYBASE or TdsDefinitions.SQLSERVER */ public int getServerType() { return serverType; } /** * Create a new and unique name for a store procedure. This routine will * return a unique name for a stored procedure that will be associated with * a PreparedStatement(). * <p> * Since SQLServer supports temporary procedure names we can just use * UniqueId.getUniqueId() to generate a unique (for the connection) name. * <p> * Sybase does not support temporary procedure names so we will have to * have a per user table devoted to storing user specific stored * procedures. The table name will be of the form * database.user.jdbc_temp_stored_proc_names. The table will be defined as * <code>CREATE TABLE database.user.jdbc_temp_stored_proc_names ( id * NUMERIC(10, 0) IDENTITY; session int not null; name char(29) )</code> * This routine will use that table to track names that are being used. * * @return The UniqueProcedureName value * @exception java.sql.SQLException Description of Exception */ public String getUniqueProcedureName() throws java.sql.SQLException { String result = null; if (serverType == SYBASE) { if (null == procNameTableName) { procNameTableName = database + "." + user + ".jdbc_temp_stored_proc_names"; procNameGeneratorName = user + ".jdbc_gen_temp_sp_names"; } // Attempt to create the table for the stored procedure names // If it already exists we'll get an error, but we don't care. // Also create a stored procedure for generating the unique // names. createStoredProcedureNameTable(); result = generateUniqueProcName(); } else { result = "#jdbc#" + UniqueId.getUniqueId(); } return result; } /** * Determine if the next subpacket is a result set. * <p> * This does not eat any input. * * @return true if the next piece of data to read is a result set. * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isResultSet() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); /* * XXX to support 5.0 we need to expand our view of what a result * set is. */ return type == TDS_COL_NAME_TOKEN || type == TDS_COLMETADATA; } /** * Determine if the next subpacket is a ret stat. * <p> * This does not eat any input. * * @return true if the next piece of data to read is a return status. * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isRetStat() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); return type == TDS_RETURNSTATUS; } /** * Determine if the next subpacket is a result row or a computed result row. * <p> * This does not eat any input. * * @return true if the next piece of data to read is a result row. * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isResultRow() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); return type == TDS_ROW /*|| type == TDS_CMP_ROW_TOKEN*/; } /** * Determine if the next subpacket is an end of result set marker. * <p> * This does not eat any input. * * @return true if the next piece of data to read is end of result set marker. * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isEndOfResults() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); return type == TDS_DONE || type == TDS_DONEPROC || type == TDS_DONEINPROC; } /** * Determine if the next subpacket is a DONEINPROC marker. * <p> * This does not eat any input. * * @return <code>true</code> if the next packet is a DONEINPROC packet * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isDoneInProc() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); return type == TDS_DONEINPROC; } /** * Determine if the next subpacket is a message packet. * <p> * This does not eat any input. * * @return true if the next piece of data to read is message * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isMessagePacket() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); return type == TDS_INFO; } /** * Determine if the next subpacket is an output parameter from a stored proc. * <p> * This does not eat any input. * * @return true if the next piece of data to read is an output parameter * * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isParamResult() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); return type==TDS_PARAM; } /** * Determine if the next subpacket is a text update packet. * <p> * This does not eat any input. * * @return true if the next piece of data to read is text update * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ /* strange replaced by paramToken public synchronized boolean isTextUpdate() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); return type == TDS_TEXT_UPD_TOKEN; } */ /** * Determine if the next subpacket is an error packet. * <p> * This does not eat any input. * * @return true if the next piece of data to read is an error * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isErrorPacket() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); return type == TDS_ERROR; } /** * Determine if the next subpacket is an procid subpacket. * <p> * This does not eat any input. * * @return true if the next piece of data to read is a procedure id. * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isProcId() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte type = comm.peek(); return type == TDS_PROCID; } /** * Determine if the next subpacket is an environment change subpacket. * <p> * This does not eat any input. * * @return true if the next piece of data to read is an environment * change token. * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized boolean isEnvChange() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { return comm.peek() == TDS_ENVCHANGE; } public void close() { comm.close(); try { sock.close(); } catch (java.io.IOException e) { // XXX should do something here } } public String toString() { return "" + database + ", " + sock.getLocalAddress() + ":" + sock.getLocalPort() + " -> " + sock.getInetAddress() + ":" + sock.getPort(); } /** * Change the connection transaction isolation level and the database. * * @param database the database name to change to */ private void initSettings(String database, SQLWarningChain wChain) { try { if( database.length() > 0 ) changeDB(database, wChain); changeSettings(sqlStatementToInitialize()); } catch (net.sourceforge.jtds.jdbc.TdsUnknownPacketSubType e) { wChain.addException( new SQLException("Unknown response. " + e.getMessage())); } catch (java.io.IOException e) { wChain.addException( new SQLException("Network problem. " + e.getMessage())); } catch (net.sourceforge.jtds.jdbc.TdsException e) { wChain.addException( new SQLException(e.getMessage())); } catch( SQLException ex ) { wChain.addException(ex); } } public void cancel() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { // This is synched by the CancelController and, respectively, TdsComm, // so there is no need to synchronize it here especially since it has // to be asynchronous anyway. ;) cancelController.doCancel(comm); } public boolean moreResults() { return moreResults; } /** * @param sql Description of Parameter * @param chain Description of Parameter * @exception SQLException Description of Exception */ public synchronized void submitProcedure(String sql, SQLWarningChain chain) throws SQLException { PacketResult tmp = null; try { executeQuery(sql, null, null, 0); boolean done; do // skip to end, why not ? { tmp = processSubPacket(); if( tmp instanceof PacketMsgResult ) chain.addOrReturn((PacketMsgResult)tmp); done = (tmp instanceof PacketEndTokenResult) && (! ((PacketEndTokenResult)tmp).moreResults()); } while (! done); } catch (java.io.IOException e) { throw new SQLException("Network error" + e.getMessage()); } catch (net.sourceforge.jtds.jdbc.TdsUnknownPacketSubType e) { throw new SQLException(e.getMessage()); } catch (net.sourceforge.jtds.jdbc.TdsException e) { throw new SQLException(e.getMessage()); } chain.checkForExceptions(); } /** * Execute a stored procedure on the SQLServer.<p> * * @param procedureName * @param formalParameterList * @param actualParameterList * @param stmt * @param timeout * @exception java.sql.SQLException * @exception net.sourceforge.jtds.jdbc.TdsException */ public synchronized void executeProcedure( String procedureName, ParameterListItem[] formalParameterList, ParameterListItem[] actualParameterList, TdsStatement stmt, SQLWarningChain wChain, int timeout) throws java.sql.SQLException, net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { // SAfe We need to check if all cancel requests were processed and wait // for any outstanding cancel. It could happen that we sent the // CANCEL after the server sent us all the data, so the answer is // going to come in a packet of its own. if( cancelController.outstandingCancels() > 0 ) { processSubPacket(); if( cancelController.outstandingCancels() > 0 ) throw new SQLException("Something went completely wrong. A cancel request was lost."); } // A stored procedure has a packet type of 0x03 in the header packet. // for non-image date the packets consists of // offset length desc. // 0 1 The length of the name of the stored proc // 1 N1 The name of the stored proc // N1 + 1 2 unknown (filled with zeros?) // N1 + 3 2 unknown prefix for param 1 (zero filled?) // N1 + 5 1 datatype for param 1 // N1 + 6 1 max length of param 1 // N1 + 7 N2 parameter 1 data // For image data (datatype 0x22) the packet consists of // 0 1 The length of the name of the stored proc // 1 N1 The name of the stored proc // N1 + 1 2 unknown (filled with zeros?) // N1 + 3 2 unknown prefix for param 1 (zero filled?) // N1 + 5 1 datatype for param 1 // N1 + 6 4 length of param 1 // N1 + 10 4 length of param 1 (duplicated?) // N1 + 7 N2 parameter 1 data checkMaxRows(stmt); int i; try { // SAfe We must not do this here, if an exception is thrown before // the packet is actually sent, we will deadlock in skipToEnd // with nothing to read. // moreResults = true; // Start sending the procedure execute packet. comm.startPacket(TdsComm.PROC); if (tdsVer == Tds.TDS70) { comm.appendTdsShort((short) (procedureName.length())); comm.appendChars(procedureName); } else { byte[] nameBytes = encoder.getBytes(procedureName); comm.appendByte((byte) nameBytes.length); comm.appendBytes(nameBytes, nameBytes.length, (byte) 0); } // SAfe I think if this is set to 2 it means "don't return column // information" (useful for scrollable statements, to reduce // the amount of data passed around). comm.appendShort((byte) 0); // Now handle the parameters for( i=0; i<formalParameterList.length; i++ ) { // SAfe We could try using actualParameterList here, instead // of formalParameterList. If it works (although it // shouldn't) it will solve a lot of problems. byte nativeType = cvtJdbcTypeToNativeType(formalParameterList[i].type); comm.appendByte((byte) 0); if (actualParameterList[i].isOutput) { comm.appendByte((byte)1); if (nativeType == SYBBIT && actualParameterList[i].value == null) { actualParameterList[i].value = Boolean.FALSE; } } else { comm.appendByte((byte) 0); } if (actualParameterList[i].value == null && (nativeType == SYBINT1 || nativeType == SYBINT2 || nativeType == SYBINT4)) { nativeType = SYBINTN; } switch (nativeType) { case SYBCHAR: { String val; try { val = (String)actualParameterList[i].value; } catch (ClassCastException e) { if( actualParameterList[i].value instanceof Boolean ) val = ((Boolean)actualParameterList[i].value).booleanValue() ? "1" : "0"; else val = actualParameterList[i].value.toString(); } if( tdsVer<TDS70 && val!=null && val.length()==0 ) val = " "; int len = val != null ? val.length() : 0; int max = formalParameterList[i].maxLength; // MJH - Do not use the formalType from the actual parameters as // this will be null where a cached stored procedure is reused by a // different PreparedStatement from the one that created it in the fist // place. Use the formalParameter data instead. //if (actualParameterList[i].formalType != null && // actualParameterList[i].formalType.startsWith("n")) { if( formalParameterList[i].formalType != null && formalParameterList[i].formalType.startsWith("n") ) { /* * This is a Unicode column, save to assume TDS 7.0 */ if (max > 4000) { comm.appendByte(SYBNTEXT); comm.appendTdsInt(max * 2); if (val == null) { comm.appendTdsInt(0xFFFFFFFF); } else { comm.appendTdsInt(len * 2); comm.appendChars(val); } } else { comm.appendByte((byte) (SYBNVARCHAR | 0x80)); comm.appendTdsShort((short) (max * 2)); if (val == null) { comm.appendTdsShort((short) 0xFFFF); } else { // MJH - Trap silent truncation problem if( val.length() > 4000 ) throw new java.io.IOException("Field too long"); comm.appendTdsShort((short) (len * 2)); comm.appendChars(val); } } } else { /* * Either VARCHAR or TEXT, TEXT can not happen * with TDS 7.0 as we would always use NTEXT there */ if (tdsVer != TDS70 && max > 255) { // TEXT comm.appendByte(SYBTEXT); if( actualParameterList[i].value instanceof byte[] ) sendSybImage((byte[]) actualParameterList[i].value); else sendSybImage(encoder.getBytes(val)); } else { // VARCHAR sendSybChar(val, formalParameterList[i].maxLength); } } break; } case SYBINTN: comm.appendByte(SYBINTN); comm.appendByte((byte)4); // maximum length of the field, if (actualParameterList[i].value == null) { comm.appendByte((byte)0); // actual length } else { comm.appendByte((byte)4); // actual length comm.appendTdsInt(((Number)(actualParameterList[i].value)).intValue()); } break; case SYBINT4: comm.appendByte(SYBINT4); comm.appendTdsInt(((Number)(actualParameterList[i].value)).intValue()); break; case SYBINT2: comm.appendByte(SYBINT2); comm.appendTdsShort(((Number)(actualParameterList[i].value)).shortValue()); break; case SYBINT1: comm.appendByte(SYBINT1); comm.appendByte(((Number)(actualParameterList[i].value)).byteValue()); break; case SYBFLT8: case SYBFLTN: { if (actualParameterList[i].value == null) { comm.appendByte(SYBFLTN); comm.appendByte((byte)8); comm.appendByte((byte)0); } else { Number n = (Number)(actualParameterList[i].value); Double d = new Double(n.doubleValue()); comm.appendByte(SYBFLT8); comm.appendFlt8(d); } break; } case SYBDATETIMN: { writeDatetimeValue(actualParameterList[i].value, SYBDATETIMN); break; } case SYBIMAGE: { comm.appendByte(nativeType); sendSybImage((byte[]) actualParameterList[i].value); break; } case SYBTEXT: { comm.appendByte(SYBTEXT); sendSybImage(encoder.getBytes((String) actualParameterList[i]. value)); break; } case SYBBIT: case SYBBITN: { if (actualParameterList[i].value == null) { comm.appendByte(SYBBITN); comm.appendByte((byte)1); comm.appendByte((byte)0); } else { comm.appendByte(SYBBIT); if( actualParameterList[i].value.equals(Boolean.TRUE) ) comm.appendByte((byte)1); else comm.appendByte((byte)0); } break; } case SYBNUMERIC: case SYBDECIMAL: { writeDecimalValue(nativeType, actualParameterList[i].value, 0, -1); break; } case SYBBINARY: case SYBVARBINARY: { byte[] value = (byte[])actualParameterList[i].value; int maxLength = formalParameterList[i].maxLength; if (value == null) { comm.appendByte(SYBVARBINARY); comm.appendByte((byte)(maxLength)); comm.appendByte((byte)0); } else { if (value.length > 255) { if (tdsVer != TDS70) { throw new java.io.IOException("Field too long"); } comm.appendByte(SYBBIGVARBINARY); if (maxLength < 0 || maxLength > 8000) { comm.appendTdsShort((short)8000); } else comm.appendTdsShort((short)maxLength); comm.appendTdsShort((short)(value.length)); } else { comm.appendByte(SYBVARBINARY); comm.appendByte((byte)(maxLength)); comm.appendByte((byte)(value.length)); } comm.appendBytes(value); } break; } case SYBVOID: case SYBVARCHAR: case SYBDATETIME4: case SYBREAL: case SYBMONEY: case SYBDATETIME: case SYBMONEYN: case SYBMONEY4: default: { throw new SQLException("Not implemented for nativeType 0x" + Integer.toHexString(nativeType)); } } } // mark that we are performing a query cancelController.setQueryInProgressFlag(); moreResults = true; comm.sendPacket(); waitForDataOrTimeout(wChain, timeout); } catch (java.io.IOException e) { throw new SQLException("Network error- " + e.getMessage()); } finally { comm.packetType = 0; } } void checkMaxRows(java.sql.Statement stmt) throws java.sql.SQLException, TdsException { if (stmt == null) // internal usage return; int maxRows = stmt.getMaxRows(); if ( maxRows != this.maxRows) { submitProcedure("set rowcount " + maxRows, new SQLWarningChain()); this.maxRows = maxRows; } } /** * send a query to the SQLServer for execution. <p> * * * *@param sql sql statement to * execute. *@param stmt *@param timeout *@exception java.io.IOException *@exception java.sql.SQLException Description of * Exception *@exception TdsException Description of * Exception */ public synchronized void executeQuery(String sql, TdsStatement stmt, SQLWarningChain wChain, int timeout) throws java.io.IOException, java.sql.SQLException, TdsException { // SAfe We need to check if all cancel requests were processed and wait // for any outstanding cancel. It could happen that we sent the // CANCEL after the server sent us all the data, so the answer is // going to come in a packet of its own. if( cancelController.outstandingCancels() > 0 ) { waitForDataOrTimeout(wChain, timeout); // @todo Cycle until we have a cancel confirmation. Also, make sure // the statement/resultset are not left in a wrong state. processSubPacket(); if( cancelController.outstandingCancels() > 0 ) throw new SQLException("Something went completely wrong. A cancel request was lost."); } checkMaxRows(stmt); // If the query has length 0, the server doesn't answer, so we'll hang if( sql.length() > 0 ) { try { comm.startPacket(TdsComm.QUERY); if (tdsVer == Tds.TDS70) { comm.appendChars(sql); } else { byte[] sqlBytes = encoder.getBytes(sql); comm.appendBytes(sqlBytes, sqlBytes.length, (byte) 0); } moreResults = true; cancelController.setQueryInProgressFlag(); //JJ 1999-01-10 comm.sendPacket(); waitForDataOrTimeout(wChain, timeout); } finally { comm.packetType = 0; } } } /** * Skip over and discard any remaining data from a result set. * * @param row Description of Parameter * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException */ public synchronized void discardResultSet(PacketRowResult row, TdsStatement stmt) throws SQLException, java.io.IOException, TdsException { if( !moreResults ) return; while ( isResultRow()) { comm.skip(1); if ( row != null ) { loadRow( row ); } if ( Logger.isActive() ) { Logger.println( "Discarded row." ); } } // SAfe Process everything up to the next TDS_DONE or TDS_DONEINPROC // packet (there must be one, so we won't check the end of the // stream. while( !isEndOfResults() ) processSubPacket(); // SAfe Then, eat up any uninteresting packets. goToNextResult(new SQLWarningChain(), stmt); } public synchronized void discardResultSet(TdsStatement stmt) throws SQLException, java.io.IOException, TdsException { discardResultSet(new PacketRowResult(currentContext), stmt); } public synchronized byte peek() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { return comm.peek(); } /** * Eats up all tokens until the next relevant token (TDS_COLMETADATA or * TDS_DONE for regular Statements or TDS_COLMETADATA, TDS_DONE or * TDS_DONEINPROC for PreparedStatements). */ protected synchronized void goToNextResult(SQLWarningChain warningChain, TdsStatement stmt) throws TdsException, java.io.IOException, SQLException { boolean isPreparedStmt = stmt instanceof PreparedStatement; boolean isCallableStmt = stmt instanceof CallableStatement; // SAfe Need to process messages, output parameters and return values // here, or even better, in the processXXX methods. while( moreResults ) { byte next = peek(); // SAfe If the next packet is a rowcount or ResultSet, break if( next==TDS_DONE || next==TDS_COLMETADATA || next==TDS_COL_NAME_TOKEN || (next==TDS_DONEINPROC && isPreparedStmt && !isCallableStmt) ) { break; } PacketResult res = processSubPacket(); if( res instanceof PacketOutputParamResult && isCallableStmt ) { ((CallableStatement_base)stmt).addOutputParam( ((PacketOutputParamResult)res).getValue() ); } else if( res instanceof PacketEndTokenResult ) { if( ((PacketEndTokenResult)res).wasCanceled() ) warningChain.addException( new SQLException("Query was canceled or timed out.")); } else if( res instanceof PacketMsgResult ) warningChain.addOrReturn( (PacketMsgResult)res ); else if( res instanceof PacketRetStatResult ) stmt.handleRetStat((PacketRetStatResult)res); } } EncodingHelper getEncoder() { return encoder; } /** * Accessor method to determine the TDS level used. * *@return TDS42, TDS50, or TDS70. */ int getTdsVer() { return tdsVer; } /** * Return the name that this database server program calls itself. * *@return The DatabaseProductName value */ String getDatabaseProductName() { return databaseProductName; } /** * Return the version that this database server program identifies itself with. * * @return The DatabaseProductVersion value */ String getDatabaseProductVersion() { return databaseProductVersion; } /** * Return the major version that this database server program identifies itself with. * * @return The databaseMajorVersion value */ int getDatabaseMajorVersion() { return databaseMajorVersion; } /** * Process an output parameter subpacket. * <p> * This routine assumes that the TDS_PARAM byte has already * been read. * * @return a <code>PacketOutputParamResult</code> wrapping an output * parameter * * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException * Thrown if some sort of error occured reading bytes from the network. */ private PacketOutputParamResult processOutputParam() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { getSubPacketLength(); // Packet length comm.getString(comm.getByte()&0xff, encoder); // Column name comm.skip(5); byte colType = comm.getByte(); /** @todo Refactor to combine this code with that in getRow() */ Object element; switch (colType) { case SYBINTN: { comm.getByte(); // Column size element = getIntValue(colType); break; } case SYBINT1: case SYBINT2: case SYBINT4: { element = getIntValue(colType); break; } case SYBIMAGE: { comm.getByte(); // Column size element = getImageValue(); break; } case SYBTEXT: { comm.getByte(); // Column size element = getTextValue(false); break; } case SYBNTEXT: { comm.getByte(); // Column size element = getTextValue(true); break; } case SYBCHAR: case SYBVARCHAR: { comm.getByte(); // Column size element = getCharValue(false, true); break; } case SYBBIGVARBINARY: { comm.getTdsShort(); // Column size int len = comm.getTdsShort(); // if (tdsVer == Tds.TDS70 && len == 0xffff) element = comm.getBytes(len, true); break; } case SYBBIGVARCHAR: { comm.getTdsShort(); // Column size element = getCharValue(false, false); break; } case SYBNCHAR: case SYBNVARCHAR: { comm.getByte(); // Column size element = getCharValue(true, true); break; } case SYBREAL: { element = readFloatN(4); break; } case SYBFLT8: { element = readFloatN(8); break; } case SYBFLTN: { comm.getByte(); // Column size int actual_size = comm.getByte(); element = readFloatN(actual_size); break; } case SYBSMALLMONEY: case SYBMONEY: case SYBMONEYN: { comm.getByte(); // Column size element = getMoneyValue(colType); break; } case SYBNUMERIC: case SYBDECIMAL: { comm.getByte(); // Column size comm.getByte(); // Precision int scale = comm.getByte(); element = getDecimalValue(scale); break; } case SYBDATETIMN: { comm.getByte(); // Column size element = getDatetimeValue(colType); break; } case SYBDATETIME4: case SYBDATETIME: { element = getDatetimeValue(colType); break; } case SYBVARBINARY: case SYBBINARY: { comm.getByte(); // Column size int len = (comm.getByte() & 0xff); element = comm.getBytes(len, true); break; } case SYBBITN: { comm.getByte(); // Column size if (comm.getByte() == 0) element = null; else element = new Boolean((comm.getByte()!=0) ? true : false); break; } case SYBBIT: { int column_size = comm.getByte(); element = new Boolean((column_size != 0) ? true : false); break; } case SYBUNIQUEID: { int len = comm.getByte() & 0xff; element = len==0 ? null : TdsUtil.uniqueIdToString(comm.getBytes(len, false)); break; } default: { element = null; throw new TdsNotImplemented("Don't now how to handle " + "column type 0x" + Integer.toHexString(colType)); } } return new PacketOutputParamResult(element); } /** * Process a subpacket reply.<p> * * <b>Note-</b> All subpackets must be processed through here. This is the * only routine has the proper locking to support the cancel method in the * Statement class. <br> * * *@return packet subtype the was * processed. *@exception TdsUnknownPacketSubType Description of * Exception *@exception java.io.IOException Description of * Exception *@exception net.sourceforge.jtds.jdbc.TdsException Description of * Exception */ PacketResult processSubPacket() throws TdsUnknownPacketSubType, java.io.IOException, net.sourceforge.jtds.jdbc.TdsException, SQLException { return processSubPacket(currentContext); } /** * Process a subpacket reply.<p> * * <b>Note-</b> All subpackets must be processed through here. Only this * routine has the proper locking to support the cancel method in the * Statement class. <br> * * *@param context Description of * Parameter *@return packet subtype the was * processed. *@exception TdsUnknownPacketSubType Description of * Exception *@exception java.io.IOException Description of * Exception *@exception net.sourceforge.jtds.jdbc.TdsException Description of * Exception */ synchronized PacketResult processSubPacket(Context context) throws TdsUnknownPacketSubType, SQLException, java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { // NOTE!!! Before adding anything to this list you must // consider the ramifications to the the handling of cancels // as implemented by the CancelController class. // The CancelController class might implicitly assume it can call // processSubPacket() whenever it is looking for a cancel // acknowledgment. It assumes that any results of the call // can be discarded. PacketResult result = null; byte packetSubType = comm.getByte(); if( Logger.isActive() ) Logger.println("processSubPacket: " + Integer.toHexString(packetSubType & 0xFF) + " " + "moreResults: " + moreResults()); switch (packetSubType) { case TDS_ENVCHANGE: { result = processEnvChange(); break; } case TDS_ERROR: case TDS_INFO: case TDS_MSG50_TOKEN: { result = processMsg(packetSubType); break; } case TDS_PARAM: { result = processOutputParam(); break; } case TDS_LOGINACK: { result = processLoginAck(); break; } case TDS_RETURNSTATUS: { result = processRetStat(); break; } case TDS_PROCID: { result = processProcId(); break; } case TDS_DONE: case TDS_DONEPROC: case TDS_DONEINPROC: { result = processEndToken(packetSubType); moreResults = ((PacketEndTokenResult) result).moreResults(); break; } case TDS_COL_NAME_TOKEN: { result = processColumnNames(); break; } case TDS_COL_INFO_TOKEN: { result = processColumnInfo(); break; } case TDS_UNKNOWN_0xA5: case TDS_UNKNOWN_0xA7: case TDS_UNKNOWN_0xA8: { // XXX Need to figure out what this packet is comm.skip(comm.getTdsShort()); result = new PacketUnknown(packetSubType); break; } case TDS_TABNAME: { result = processTabName(); break; } case TDS_ORDER: { int len = comm.getTdsShort(); comm.skip(len); result = new PacketColumnOrderResult(); break; } case TDS_CONTROL: { int len = comm.getTdsShort(); comm.skip(len); // FIXME - I'm just ignoring this result = new PacketControlResult(); break; } case TDS_ROW: { result = getRow(context); break; } case TDS_COLMETADATA: { result = processTds7Result(); break; } //mdb case TDS_AUTH_TOKEN: { result = processNtlmChallenge(); break; } default: { throw new TdsUnknownPacketSubType(packetSubType); } } return result; } private boolean setCharset(String charset) { // If true at the end of the method, the specified charset was used. Otherwise, iso_1 was. boolean used = charset!=null; if (charset == null || charset.length() > 30) charset = "iso_1"; if( charset.toLowerCase().startsWith("cp") ) charset = "Cp" + charset.substring(2); if( !charset.equals(this.charset) ) { encoder = EncodingHelper.getHelper(charset); if( encoder == null ) { if( Logger.isActive() ) Logger.println("Invalid charset: "+charset+". Trying iso_1 instead."); charset = "iso_1"; encoder = EncodingHelper.getHelper(charset); used = false; } this.charset = charset; } if( Logger.isActive() ) Logger.println("Set charset to "+charset+'/'+encoder.getName()); return used; } /** * Try to figure out what client name we should identify ourselves as. Get * the hostname of this machine, * *@return name we will use as the client. */ private String getClientName() { // This method is thread safe. String tmp; try { tmp = java.net.InetAddress.getLocalHost().getHostName(); } catch (java.net.UnknownHostException e) { tmp = ""; } StringTokenizer st = new StringTokenizer(tmp, "."); if (!st.hasMoreTokens()) { // This means hostname wasn't found for this machine. return "JOHNDOE"; } // Look at the first (and possibly only) word in the name. tmp = st.nextToken(); if (tmp.length() == 0) { // This means the hostname had no leading component. // (This case would be strange.) return "JANEDOE"; } else if (Character.isDigit(tmp.charAt(0))) { // This probably means that the name was a quad-decimal // number. We don't want to send that as our name, // so make one up. return "BABYDOE"; } else { // Ah, Life is good. We have a name. All other // applications I've seen have upper case client names, // and so shall we. return tmp.toUpperCase(); } } /** * Get the length of the current subpacket. <p> * * This will eat two bytes from the input socket. * *@return length of the current * subpacket. *@exception java.io.IOException Description of * Exception *@exception net.sourceforge.jtds.jdbc.TdsException Description of * Exception */ private int getSubPacketLength() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { return comm.getTdsShort(); } /** * determine if a given datatype is a fixed size * *@param nativeColumnType The SQLServer datatype * to check *@return <code>true</code> if * the datatype is a fixed size, <code>false</code> if the datatype is * a variable size *@exception net.sourceforge.jtds.jdbc.TdsException If the <code> * nativeColumnType</code> is not a knowm datatype. */ private boolean isFixedSizeColumn(byte nativeColumnType) throws net.sourceforge.jtds.jdbc.TdsException { switch (nativeColumnType) { case SYBINT1: case SYBINT2: case SYBINT4: case SYBFLT8: case SYBDATETIME: case SYBBIT: case SYBMONEY: case SYBMONEY4: case SYBSMALLMONEY: case SYBREAL: case SYBDATETIME4: { return true; } case SYBINTN: case SYBMONEYN: case SYBVARCHAR: case SYBNVARCHAR: case SYBDATETIMN: case SYBFLTN: case SYBCHAR: case SYBNCHAR: case SYBNTEXT: case SYBIMAGE: case SYBVARBINARY: case SYBBINARY: case SYBDECIMAL: case SYBNUMERIC: case SYBBITN: case SYBUNIQUEID: { return false; } default: { throw new TdsException("Unrecognized column type 0x" + Integer.toHexString(nativeColumnType)); } } } private Object getMoneyValue( int type) throws java.io.IOException, TdsException { int len; Object result; switch( type ) { case SYBSMALLMONEY: case SYBMONEY4: len = 4; break; case SYBMONEY: len = 8; break; case SYBMONEYN: len = comm.getByte(); break; default: throw new TdsException("Not a money value."); } if (len == 0) { result = null; } else { BigInteger x = null; if (len == 4) { x = BigInteger.valueOf(comm.getTdsInt()); } else if (len == 8) { byte b4 = comm.getByte(); byte b5 = comm.getByte(); byte b6 = comm.getByte(); byte b7 = comm.getByte(); byte b0 = comm.getByte(); byte b1 = comm.getByte(); byte b2 = comm.getByte(); byte b3 = comm.getByte(); long l = (long) (b0 & 0xff) + ((long) (b1 & 0xff) << 8) + ((long) (b2 & 0xff) << 16) + ((long) (b3 & 0xff) << 24) + ((long) (b4 & 0xff) << 32) + ((long) (b5 & 0xff) << 40) + ((long) (b6 & 0xff) << 48) + ((long) (b7 & 0xff) << 56); x = BigInteger.valueOf(l); } else { throw new TdsConfused("Don't know what to do with len of " + len); } result = new BigDecimal(x, 4); } return result; } // getMoneyValue /** * Extracts decimal value from the server's results packet. Takes advantage * of Java's superb handling of large numbers, which does all the heavy * lifting for us. Format is: * <UL> * <LI> Length byte <code>len</code> ; count includes sign byte.</LI> * * <LI> Sign byte (0=negative; 1=positive).</LI> * <LI> Magnitude bytes (array of <code>len</code> - 1 bytes, in * little-endian order.</LI> * </UL> * * *@param scale number of decimal digits after the * decimal point. *@return <code>BigDecimal</code> for extracted * value (or ( <code>null</code> if appropriate). *@exception TdsException Description of Exception *@exception java.io.IOException Description of Exception *@exception NumberFormatException Description of Exception */ private Object getDecimalValue(int scale) throws TdsException, java.io.IOException, NumberFormatException { int len = comm.getByte() & 0xff; if (--len < 1) { return null; } // RMK 2000-06-10. Deduced from some testing/packet sniffing. byte[] bytes = new byte[len]; int signum = comm.getByte() == 0 ? -1 : 1; while (len > 0) { bytes[--len] = comm.getByte(); } BigInteger bigInt = new BigInteger(signum, bytes); return new BigDecimal(bigInt, scale); } private Object getDatetimeValue( int type) throws java.io.IOException, TdsException { // Some useful constants final long SECONDS_PER_DAY = 24L * 60L * 60L; final long DAYS_BETWEEN_1900_AND_1970 = 25567L; int len; Object result; if (type == SYBDATETIMN) { len = comm.getByte(); } else if (type == SYBDATETIME4) { len = 4; } else { len = 8; // XXX shouldn't this be an error? } switch (len) { case 0: { result = null; break; } case 8: { // It appears that a datetime is made of of 2 32bit ints // The first one is the number of days since 1900 // The second integer is the number of seconds*300 // The reason the calculations below are sliced up into // such small baby steps is to avoid a bug in JDK1.2.2's // runtime, which got confused by the original complexity. long tdsDays = (long) comm.getTdsInt(); long tdsTime = (long) comm.getTdsInt(); long sqlDays = tdsDays - DAYS_BETWEEN_1900_AND_1970; long seconds = sqlDays * SECONDS_PER_DAY + tdsTime / 300L; long micros = ((tdsTime % 300L) * 1000000L) / 300L; long millis = seconds * 1000L + micros / 1000L - zoneOffset; // Round up if appropriate. if (micros % 1000L >= 500L) { millis++; } result = new Timestamp(millis - getDstOffset(millis)); break; } case 4: { // Accroding to Transact SQL Reference // a smalldatetime is two small integers. // The first is the number of days past January 1, 1900, // the second smallint is the number of minutes past // midnight. long tdsDays = (long) comm.getTdsShort(); long minutes = (long) comm.getTdsShort(); long sqlDays = tdsDays - DAYS_BETWEEN_1900_AND_1970; long seconds = sqlDays * SECONDS_PER_DAY + minutes * 60L; long millis = seconds * 1000L - zoneOffset; result = new Timestamp(millis - getDstOffset(millis)); break; } default: { result = null; throw new TdsNotImplemented("Don't now how to handle " + "date with size of " + len); } } return result; } // getDatetimeValue() /** * Determines the number of milliseconds needed to adjust for daylight * savings time for a given date/time value. Note that there is a problem * with the way SQL Server sends a DATETIME value, since it is constructed * to represent the local time for the server. This means that each fall * there is a window of approximately one hour during which a single value * can represent two different times. * * @param time Description of Parameter * @return The DstOffset value * @todo SAfe Try to find a better way to do this, because it doubles the time it takes to process datetime values!!! */ private long getDstOffset(long time) { Calendar cal = Calendar.getInstance(); cal.setTime(new java.util.Date(time)); return cal.get(Calendar.DST_OFFSET); } private Object getIntValue(int type) throws java.io.IOException, TdsException { Object result; int len; switch (type) { case SYBINTN: { len = comm.getByte(); break; } case SYBINT4: { len = 4; break; } case SYBINT2: { len = 2; break; } case SYBINT1: { len = 1; break; } default: { throw new TdsNotImplemented("Can't handle integer of type " + Integer.toHexString(type)); } } switch (len) { case 4: { result = new Integer(comm.getTdsInt()); break; } case 2: { result = new Integer((short)comm.getTdsShort()); break; } case 1: { result = new Integer(toUInt(comm.getByte())); break; } case 0: { result = null; break; } default: { throw new TdsConfused("Bad SYBINTN length of "+len); } } return result; } // getIntValue() private Object getCharValue(boolean wideChars, boolean outputParam) throws TdsException, java.io.IOException { Object result; boolean shortLen = (tdsVer == Tds.TDS70) && (wideChars || !outputParam); int len = shortLen ? comm.getTdsShort() : (comm.getByte() & 0xFF); // SAfe 2002-08-23 // TDS 7.0 no longer uses 0 length values as NULL if( tdsVer<TDS70 && len==0 || tdsVer==TDS70 && len==0xFFFF ) { result = null; } else if (len >= 0) { if (wideChars) { result = comm.getString(len/2, encoder); } else { result = encoder.getString(comm.getBytes(len, false), 0, len); } // SAfe 2002-08-23 // TDS 7.0 does not use the same logic, one space is one space if( tdsVer<TDS70 && " ".equals(result) ) { // In SQL trailing spaces are stripped from strings // MS SQLServer denotes a zero length string // as a single space. result = ""; } } else { throw new TdsConfused("String with length<0"); } return result; } // getCharValue() private Object getTextValue(boolean wideChars) throws TdsException, java.io.IOException { String result; byte hasValue = comm.getByte(); if (hasValue == 0) { result = null; } else { // XXX Have no idea what these 24 bytes are // 2000-06-06 RMK They are the TEXTPTR (16 bytes) and the TIMESTAMP. comm.skip(24); int len = comm.getTdsInt(); // RMK 2000-06-11 // The logic immediately below does not agree with test t0031, // so I'm commenting it out. On the other hand, it's a bit // puzzling that a column defined as TEXT NOT NULL needs the // hasValue byte read just above, but apparently it does. //if (len == 0) // result = null; //else if (len >= 0) { if (wideChars) { result = comm.getString(len/2, encoder); } else { result = encoder.getString(comm.getBytes(len, false), 0, len); } // SAfe 2002-08-23 // TDS 7.0 does not use the same logic, one space is one space if( tdsVer<TDS70 && " ".equals(result) ) { // In SQL trailing spaces are stripped from strings // MS SQLServer denotes a zero length string // as a single space. result = ""; } } else { throw new TdsConfused("String with length<0"); } } return result; } // getTextValue() private Object getImageValue() throws TdsException, java.io.IOException { byte[] result; byte hasValue = comm.getByte(); if (hasValue == 0) { result = null; } else { // XXX Have no idea what these 24 bytes are // 2000-06-06 RMK They are the TEXTPTR (16 bytes) and the TIMESTAMP. comm.skip(24); int len = comm.getTdsInt(); // RMK 2000-06-11 // The logic immediately below does not agree with test t0031, // so I'm commenting it out. On the other hand, it's a bit // puzzling that a column defined as TEXT NOT NULL needs the // hasValue byte read just above, but apparently it does. //if (len == 0) // result = null; //else if (len >= 0) { result = comm.getBytes(len, true); } else { throw new TdsConfused("String with length<0"); } } return result; } // getImageValue() /** * get one result row from the TDS stream.<p> * * This will read a full row from the TDS stream and store it in a * PacketRowResult object. * *@param result Description of Parameter *@return The Row value *@exception TdsException Description of Exception *@exception java.io.IOException Description of Exception * */ private PacketRowResult loadRow(PacketRowResult result) throws SQLException, TdsException, java.io.IOException { int i; Columns columnsInfo = result.getContext().getColumnInfo(); for (i = 1; i <= columnsInfo.realColumnCount(); i++) { Object element; int colType = columnsInfo.getNativeType(i); if( Logger.isActive() ) Logger.println("colno=" + i + " type=" + colType + " offset=" + Integer.toHexString(comm.inBufferIndex)); switch (colType) { case SYBINTN: case SYBINT1: case SYBINT2: case SYBINT4: { element = getIntValue(colType); break; } case SYBIMAGE: { element = getImageValue(); break; } case SYBTEXT: { element = getTextValue(false); break; } case SYBNTEXT: { element = getTextValue(true); break; } case SYBCHAR: case SYBVARCHAR: { element = getCharValue(false,false); break; } case SYBNCHAR: case SYBNVARCHAR: { element = getCharValue(true,false); break; } case SYBREAL: { element = readFloatN(4); break; } case SYBFLT8: { element = readFloatN(8); break; } case SYBFLTN: { int len; len = comm.getByte(); element = readFloatN(len); break; } case SYBSMALLMONEY: case SYBMONEY: case SYBMONEYN: { element = getMoneyValue(colType); break; } case SYBNUMERIC: case SYBDECIMAL: { element = getDecimalValue(columnsInfo.getScale(i)); break; } case SYBDATETIME4: case SYBDATETIMN: case SYBDATETIME: { element = getDatetimeValue(colType); break; } case SYBVARBINARY: case SYBBINARY: { int len = tdsVer == Tds.TDS70 ? comm.getTdsShort() : (comm.getByte() & 0xff); if (tdsVer == Tds.TDS70 && len == 0xffff) { element = null; } else { element = comm.getBytes(len, true); } break; } case SYBBITN: case SYBBIT: { if (colType == SYBBITN && comm.getByte() == 0) { element = null; } else { element = new Boolean((comm.getByte() != 0) ? true : false); } break; } case SYBUNIQUEID: { int len = comm.getByte() & 0xff; element = len==0 ? null : TdsUtil.uniqueIdToString(comm.getBytes(len, false)); break; } default: { element = null; throw new TdsNotImplemented("Don't now how to handle " + "column type 0x" + Integer.toHexString(colType)); } } result.setElementAt(i, element); } return result; } /** * Creates a <code>PacketRowResult</code> and calls <code>loadRow(PacketRowResult)</code> with * it. */ private PacketRowResult getRow(Context context) throws SQLException, TdsException, java.io.IOException { PacketRowResult result = new PacketRowResult(context); return loadRow( result ); } /** * Log onto the SQLServer.<p> * * This method is not synchronized and does not need to be so long as it * can only be called from the constructor. <p> * * <U>Login Packet</U> <P> * * Packet type (first byte) is 2. The following is from tds.h the numbers * on the left are offsets <I>not including</I> the packet header. <br> * Note: The logical logon packet is split into two physical packets. Each * physical packet has its own header. <br> * <PRE> * * -- 0 -- DBCHAR host_name[30]; -- 30 -- DBTINYINT host_name_length; -- 31 * -- DBCHAR user_name[30]; -- 61 -- DBTINYINT user_name_length; -- 62 -- * DBCHAR password[30]; -- 92 -- DBTINYINT password_length; -- 93 -- DBCHAR * host_process[30]; -- 123 -- DBTINYINT host_process_length; -- 124 -- * DBCHAR magic1[6]; -- here were most of the mystery stuff is -- -- 130 -- * DBTINYINT bulk_copy; -- 131 -- DBCHAR magic2[9]; -- here were most of * the mystery stuff is -- -- 140 -- DBCHAR app_name[30]; -- 170 -- * DBTINYINT app_name_length; -- 171 -- DBCHAR server_name[30]; -- 201 -- * DBTINYINT server_name_length; -- 202 -- DBCHAR magic3; -- 0, dont know * this one either -- -- 203 -- DBTINYINT password2_length; -- 204 -- * DBCHAR password2[30]; -- 234 -- DBCHAR magic4[223]; -- 457 -- DBTINYINT * password2_length_plus2; -- 458 -- DBSMALLINT major_version; -- TDS * version -- -- 460 -- DBSMALLINT minor_version; -- TDS version -- -- 462 * -- DBCHAR library_name[10]; -- Ct-Library or DB-Library -- -- 472 -- * DBTINYINT library_length; -- Ct-Library or DB-Library -- -- 473 -- * DBSMALLINT major_version2; -- program version -- -- 475 -- DBSMALLINT * minor_version2; -- program version -- -- 477 -- DBCHAR magic6[3]; -- ? * last two octets are 13 and 17 -- -- bdw reports last two as 12 and 16 * here -- -- possibly a bitset flag -- -- 480 -- DBCHAR language[30]; -- * ie us-english -- -- second packet -- -- 524 -- DBTINYINT * language_length; -- 10 in this case -- -- 525 -- DBCHAR magic7; -- no * clue... has 1 in the first octet -- -- bdw reports 0x0 -- -- 526 -- * DBSMALLINT old_secure; -- explaination? -- -- 528 -- DBTINYINT * encrypted; -- 1 means encrypted all password fields blank -- -- 529 -- * DBCHAR magic8; -- no clue... zeros -- -- 530 -- DBCHAR sec_spare[9]; -- * explaination -- -- 539 -- DBCHAR char_set[30]; -- ie iso_1 -- -- 569 -- * DBTINYINT char_set_length; -- 5 -- -- 570 -- DBTINYINT magic9; -- 1 -- * -- 571 -- DBCHAR block_size[6]; -- in text -- -- 577 -- DBTINYINT * block_size_length; -- 578 -- DBCHAR magic10[25]; -- lots of stuff * here...no clue --</PRE> This routine will basically eat all of the data * returned from the SQLServer. * * @return Description of the Returned Value * @exception TdsUnknownPacketSubType * @exception net.sourceforge.jtds.jdbc.TdsException * @exception java.io.IOException * @exception java.sql.SQLException */ private boolean logon(String _database) throws java.sql.SQLException, TdsUnknownPacketSubType, java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { boolean isOkay = true; byte pad = (byte) 0; byte[] empty = new byte[0]; try { // Added 2000-06-07. if (tdsVer == Tds.TDS70) { send70Login(_database); _database = ""; } else { comm.startPacket(TdsComm.LOGON); // hostname (offset0) // comm.appendString("TOLEDO", 30, (byte)0); byte[] tmp = encoder.getBytes(getClientName()); comm.appendBytes(tmp, 30, pad); comm.appendByte((byte) (tmp.length < 30 ? tmp.length : 30)); // username (offset 31 0x1f) tmp = encoder.getBytes(user); comm.appendBytes(tmp, 30, pad); comm.appendByte((byte) (tmp.length < 30 ? tmp.length : 30)); // password (offset 62 0x3e) tmp = encoder.getBytes(password); comm.appendBytes(tmp, 30, pad); comm.appendByte((byte) (tmp.length < 30 ? tmp.length : 30)); // hostproc (offset 93 0x5d) tmp = encoder.getBytes("00000116"); comm.appendBytes(tmp, 8, pad); // unused (offset 109 0x6d) comm.appendBytes(empty, (30 - 14), pad); // apptype (offset ) comm.appendByte((byte) 0x0); comm.appendByte((byte) 0xA0); comm.appendByte((byte) 0x24); comm.appendByte((byte) 0xCC); comm.appendByte((byte) 0x50); comm.appendByte((byte) 0x12); // hostproc length (offset ) comm.appendByte((byte) 8); // type of int2 comm.appendByte((byte) 3); // type of int4 comm.appendByte((byte) 1); // type of char comm.appendByte((byte) 6); // type of flt comm.appendByte((byte) 10); // type of date comm.appendByte((byte) 9); // notify of use db comm.appendByte((byte) 1); // disallow dump/load and bulk insert comm.appendByte((byte) 1); // sql interface type comm.appendByte((byte) 0); // type of network connection comm.appendByte((byte) 0); // spare[7] comm.appendBytes(empty, 7, pad); // appname tmp = encoder.getBytes(appName); comm.appendBytes(tmp, 30, pad); comm.appendByte((byte) (tmp.length < 30 ? tmp.length : 30)); // server name tmp = encoder.getBytes(serverName); comm.appendBytes(tmp, 30, pad); comm.appendByte((byte) (tmp.length < 30 ? tmp.length : 30)); // remote passwords comm.appendBytes(empty, 2, pad); tmp = encoder.getBytes(password); comm.appendBytes(tmp, 253, pad); comm.appendByte((byte) (tmp.length < 253 ? tmp.length + 2 : 253 + 2)); // tds version comm.appendByte((byte) 4); comm.appendByte((byte) 2); comm.appendByte((byte) 0); comm.appendByte((byte) 0); // prog name tmp = encoder.getBytes(progName); comm.appendBytes(tmp, 10, pad); comm.appendByte((byte) (tmp.length < 10 ? tmp.length : 10)); // prog version comm.appendByte((byte) 6); // Tell the server we can handle SQLServer version 6 comm.appendByte((byte) 0); // Send zero to tell the server we can't handle any other version comm.appendByte((byte) 0); comm.appendByte((byte) 0); // auto convert short comm.appendByte((byte) 0); // type of flt4 comm.appendByte((byte) 0x0D); // type of date4 comm.appendByte((byte) 0x11); // language tmp = encoder.getBytes("us_english"); comm.appendBytes(tmp, 30, pad); comm.appendByte((byte) (tmp.length < 30 ? tmp.length : 30)); // notify on lang change comm.appendByte((byte) 1); // security label hierachy comm.appendShort((short) 0); // security components comm.appendBytes(empty, 8, pad); // security spare comm.appendShort((short) 0); // security login role comm.appendByte((byte) 0); // charset tmp = encoder.getBytes(charset); comm.appendBytes(tmp, 30, pad); comm.appendByte((byte) (tmp.length < 30 ? tmp.length : 30)); // notify on charset change comm.appendByte((byte) 1); // length of tds packets tmp = encoder.getBytes("512"); comm.appendBytes(tmp, 6, pad); comm.appendByte((byte) 3); // pad out to a longword comm.appendBytes(empty, 8, pad); } moreResults = true; comm.sendPacket(); } finally { comm.packetType = 0; } // Get the reply to the logon packet. PacketResult result; while (!((result = processSubPacket()) instanceof PacketEndTokenResult)) { if (result instanceof PacketErrorResult) { isOkay = false; } // XXX Should really process some more types of packets. //mdb: handle ntlm challenge by sending a response... if( result instanceof PacketAuthTokenResult ) { sendNtlmChallengeResponse((PacketAuthTokenResult)result); } } if (isOkay) { // XXX Should we move this to the Connection class? SQLWarningChain wChain = new SQLWarningChain(); initSettings(_database, wChain); wChain.checkForExceptions(); } // XXX Possible bug. What happend if this is cancelled before the logon // takes place? Should isOkay be false? return isOkay; } /* * New code added to handle TDS 7.0 login, which uses a completely * different packet layout. Logic taken directly from freetds C * code in tds/login.c. Lots of magic values: I don't pretend * to have any idea what most of this means. * * Added 2000-06-05. */ private void send70Login(String _database) throws java.io.IOException, TdsException { String libName = this.progName; byte pad = (byte) 0; byte[] empty = new byte[0]; String appName = this.appName; String clientName = getClientName(); //mdb boolean ntlmAuth = (domain.length() > 0); //mdb:begin-change short packSize = (short)( 86 + 2 * (clientName.length() + appName.length() + serverName.length() + libName.length() + _database.length()) ); short authLen = 0; //NOTE(mdb): ntlm includes auth block; sql auth includes uname and pwd. if( ntlmAuth ) { authLen = (short)(32 + domain.length()); packSize += authLen; } else { authLen = 0; packSize += (2*(user.length()+password.length())); } //mdb:end-change comm.startPacket(TdsComm.LOGON70); comm.appendTdsInt(packSize); // TDS version comm.appendTdsInt(0x70000000); // Magic! comm.appendBytes(empty, 16, pad); comm.appendByte((byte)0xE0); //mdb: this byte controls what kind of auth we do. if( ntlmAuth ) comm.appendByte((byte)0x83); else comm.appendByte((byte)0x03); comm.appendBytes(empty, 10, pad); // Pack up value lengths, positions. short curPos = 86; // Hostname comm.appendTdsShort(curPos); comm.appendTdsShort((short) clientName.length()); curPos += clientName.length() * 2; // Username //mdb: ntlm doesn't send username... if( ! ntlmAuth ) { comm.appendTdsShort(curPos); comm.appendTdsShort((short) user.length()); curPos += user.length() * 2; } else { comm.appendTdsShort(curPos); comm.appendTdsShort((short) 0); } // Password //mdb: ntlm doesn't send username... if( ! ntlmAuth ) { comm.appendTdsShort(curPos); comm.appendTdsShort((short) password.length()); curPos += password.length() * 2; } else { comm.appendTdsShort(curPos); comm.appendTdsShort((short) 0); } // App name comm.appendTdsShort(curPos); comm.appendTdsShort((short) appName.length()); curPos += appName.length() * 2; // Server name comm.appendTdsShort(curPos); comm.appendTdsShort((short) serverName.length()); curPos += serverName.length() * 2; // Unknown comm.appendTdsShort((short) 0); comm.appendTdsShort((short) 0); // Library name comm.appendTdsShort(curPos); comm.appendTdsShort((short) libName.length()); curPos += libName.length() * 2; // Another unknown value // mdb: this is the "language" comm.appendTdsShort(curPos); comm.appendTdsShort((short) 0); // Database comm.appendTdsShort(curPos); comm.appendTdsShort((short) _database.length()); curPos += _database.length() * 2; // MAC address comm.appendBytes(empty, 6, pad); //mdb: location of ntlm auth block. note that for sql auth, authLen==0. comm.appendTdsShort(curPos); comm.appendTdsShort(authLen); //"next position" (same as total packet size) comm.appendTdsInt(packSize); comm.appendChars(clientName); // Pack up the login values. //mdb: for ntlm auth, uname and pwd aren't sent up... if( ! ntlmAuth ) { String scrambledPw = tds7CryptPass(password); comm.appendChars(user); comm.appendChars(scrambledPw); } comm.appendChars(appName); comm.appendChars(serverName); comm.appendChars(libName); comm.appendChars(_database); //mdb: add the ntlm auth info... if( ntlmAuth ) { // host and domain name are _narrow_ strings. byte[] domainBytes = domain.getBytes("UTF8"); //byte[] hostBytes = localhostname.getBytes("UTF8"); byte[] header = { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 }; comm.appendBytes( header ); //header is ascii "NTLMSSP\0" comm.appendTdsInt(1); //sequence number = 1 comm.appendTdsInt(0xb201); //flags (???) //domain info comm.appendTdsShort( (short)domainBytes.length ); comm.appendTdsShort( (short)domainBytes.length ); comm.appendTdsInt(32); //offset, relative to start of auth block. //host info //NOTE(mdb): not sending host info; hope this is ok! comm.appendTdsShort( (short)0 ); comm.appendTdsShort( (short)0 ); comm.appendTdsInt(32); //offset, relative to start of auth block. // add the variable length data at the end... comm.appendBytes( domainBytes ); } } /** * Select a new database to use. * * @param database Name of the database to use. * @exception java.sql.SQLException Description of Exception */ protected synchronized void changeDB(String database, SQLWarningChain wChain) throws java.sql.SQLException { try { PacketResult result; int i; // XXX Check to make sure the database name // doesn't have funny characters. if (database.length() > 32 || database.length() < 1) { wChain.addException( new SQLException("Name too long - " + database)); } for (i = 0; i < database.length(); i++) { char ch; ch = database.charAt(i); if (! ((ch == '_' && i != 0) || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))) { wChain.addException( new SQLException("Bad database name- " + database)); } } String query = tdsVer==TDS70 ? ("use [" + database + ']') : "use " + database; executeQuery(query, null, null, 0); // Get the reply to the change database request. while (!((result = processSubPacket()) instanceof PacketEndTokenResult)) { if (result instanceof PacketMsgResult) { wChain.addOrReturn((PacketMsgResult)result); } // XXX Should really process some more types of packets. } } catch (net.sourceforge.jtds.jdbc.TdsUnknownPacketSubType e) { wChain.addException( new SQLException("Unknown response. " + e.getMessage())); } catch (java.io.IOException e) { wChain.addException( new SQLException("Network problem. " + e.getMessage())); } catch (net.sourceforge.jtds.jdbc.TdsException e) { wChain.addException(new SQLException(e.toString())); } } /** * This will read a error (or warning) message from the SQLServer and * create a SqlMessage object from that message. <p> * * <b>Warning!</b> This is not synchronized because it assumes it will only * be called by processSubPacket() which is synchronized. * *@param packetSubType type of the current * subpacket *@return The message returned by * the SQLServer. *@exception java.io.IOException Description of * Exception *@exception net.sourceforge.jtds.jdbc.TdsException Description of * Exception */ private PacketMsgResult processMsg(byte packetSubType) throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { SqlMessage msg = new SqlMessage(); getSubPacketLength(); // Packet length msg.number = comm.getTdsInt(); msg.state = comm.getByte(); msg.severity = comm.getByte(); int msgLen = comm.getTdsShort(); msg.message = comm.getString(msgLen, encoder); int srvNameLen = comm.getByte() & 0xFF; msg.server = comm.getString(srvNameLen, encoder); if (packetSubType == TDS_INFO || packetSubType == TDS_ERROR) { // nop int procNameLen = comm.getByte() & 0xFF; msg.procName = comm.getString(procNameLen, encoder); } else { throw new TdsConfused("Was expecting a msg or error token. " + "Found 0x" + Integer.toHexString(packetSubType & 0xff)); } msg.line = comm.getTdsShort(); lastServerMessage = msg; if (packetSubType == TDS_ERROR) { return new PacketErrorResult(packetSubType, msg); } else { return new PacketMsgResult(packetSubType, msg); } } /** * Process an env change message (TDS_ENV_CHG_TOKEN).<p> * * <b>Warning!</b> This is not synchronized because it assumes it will only * be called by processSubPacket() which is synchronized. * *@return Description of the * Returned Value *@exception java.io.IOException *@exception net.sourceforge.jtds.jdbc.TdsException */ private PacketResult processEnvChange() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { int len = getSubPacketLength(); int type = comm.getByte(); switch (type) { case TDS_ENV_BLOCKSIZE: { String blocksize; int clen = comm.getByte() & 0xFF; if (tdsVer == TDS70) { blocksize = comm.getString(clen, encoder); comm.skip(len - 2 - clen * 2); } else { blocksize = encoder.getString(comm.getBytes(clen, false), 0, clen); comm.skip(len - 2 - clen); } // SAfe This was only done for TDS70. Why? comm.resizeOutbuf(Integer.parseInt(blocksize)); if( Logger.isActive() ) Logger.println("Changed blocksize to "+blocksize); } break; case TDS_ENV_CHARSET: { int clen = comm.getByte() & 0xFF; String charset; if (tdsVer == TDS70) { charset = comm.getString(clen, encoder); comm.skip(len - 2 - clen * 2); } else { charset = encoder.getString(comm.getBytes(clen, false), 0, clen); comm.skip(len - 2 - clen); } if( !charsetSpecified ) setCharset(charset); else if( Logger.isActive() ) Logger.println("Server charset "+charset+". Ignoring."); break; } case TDS_ENV_DATABASE: { int clen = comm.getByte() & 0xFF; String newDb = comm.getString(clen, encoder); clen = comm.getByte() & 0xFF; String oldDb = comm.getString(clen, encoder); if( database!=null && !oldDb.equalsIgnoreCase(database) ) throw new TdsException("Old database mismatch."); database = newDb; if( Logger.isActive() ) Logger.println("Changed database to "+database); break; } default: { // XXX Should actually look at the env change // instead of ignoring it. comm.skip(len - 1); break; } } return new PacketResult( TDS_ENVCHANGE ); } /** * Process an column name subpacket. <p> * * <p> * * <b>Warning!</b> This is not synchronized because it assumes it will only * be called by processSubPacket() which is synchronized. * *@return Description of the * Returned Value *@exception java.io.IOException Description of * Exception *@exception net.sourceforge.jtds.jdbc.TdsException Description of * Exception */ private PacketColumnNamesResult processColumnNames() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { Columns columns = new Columns(); int totalLen = comm.getTdsShort(); int bytesRead = 0; int i = 0; while (bytesRead < totalLen) { int colNameLen = comm.getByte(); String colName = encoder.getString(comm.getBytes(colNameLen, false), 0, colNameLen); bytesRead = bytesRead + 1 + colNameLen; i++; columns.setName(i, colName); columns.setLabel(i, colName); } currentContext = new Context(columns, encoder); return new PacketColumnNamesResult(columns); } // processColumnNames() /** * Process the columns information subpacket. <p> * * <b>Warning!</b> This is not synchronized because it assumes it will only * be called by processSubPacket() which is synchronized. * *@return Description of the * Returned Value *@exception java.io.IOException Description of * Exception *@exception net.sourceforge.jtds.jdbc.TdsException Description of * Exception */ private PacketColumnInfoResult processColumnInfo() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { Columns columns = new Columns(); int precision; int scale; int totalLen = comm.getTdsShort(); int bytesRead = 0; int numColumns = 0; while (bytesRead < totalLen) { scale = -1; precision = -1; int bufLength=-1, dispSize=-1; byte flagData[] = new byte[4]; for (int i = 0; i < 4; i++) { flagData[i] = comm.getByte(); bytesRead++; } boolean nullable = (flagData[2] & 0x01) > 0; boolean caseSensitive = (flagData[2] & 0x02) > 0; boolean writable = (flagData[2] & 0x0C) > 0; boolean autoIncrement = (flagData[2] & 0x10) > 0; String tableName = ""; // Get the type of column byte columnType = comm.getByte(); bytesRead++; if( columnType == SYBTEXT || columnType == SYBIMAGE ) { // XXX Need to find out what these next 4 bytes are // Could they be the column size? comm.skip(4); bytesRead += 4; int tableNameLen = comm.getTdsShort(); bytesRead += 2; tableName = encoder.getString(comm.getBytes(tableNameLen, false), 0, tableNameLen); bytesRead += tableNameLen; bufLength = 2 << 31 - 1; } else if( columnType == SYBDECIMAL || columnType == SYBNUMERIC ) { bufLength = comm.getByte(); bytesRead++; precision = comm.getByte(); // Total number of digits bytesRead++; scale = comm.getByte(); // # of digits after the decimal point bytesRead++; } else if( isFixedSizeColumn(columnType) ) bufLength = lookupBufferSize(columnType); else { bufLength = (int)comm.getByte() & 0xff; bytesRead++; } numColumns++; populateColumn(columns.getColumn(numColumns), columnType, null, dispSize, bufLength, nullable, autoIncrement, writable, caseSensitive, tableName, precision, scale); } // Don't know what the rest is except that the int skipLen = totalLen - bytesRead; if (skipLen != 0) { throw new TdsException( "skipping " + skipLen + " bytes"); } currentContext.getColumnInfo().merge(columns); return new PacketColumnInfoResult(columns); } // processColumnInfo private PacketTabNameResult processTabName() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { int totalLen = comm.getTdsShort(); // RMK 2000-06-11. Not sure why the original code is bothering // to extract the bytes with such meticulous care if it isn't // going to use the extracted strings for creating the returned // object. At any rate, this approach doesn't work under TDS 7.0, // because (1) the name length is a short, not a byte under 7.0, // and (2) the name string is nameLen wide characters for 7.0, // not 8-bit characters. So I'm commenting the wasted effort // and replacing it with a simple call to TdsComm.skip(). //int bytesRead = 0; //int nameLen = 0; //String tabName = null; //while(bytesRead < totalLen) // nameLen = comm.getByte(); // bytesRead++; // tabName = new String(comm.getBytes(nameLen)); // bytesRead += nameLen; comm.skip(totalLen); return new PacketTabNameResult(); } // processTabName() /** * Process an end subpacket. <p> * * This routine assumes that the TDS_END_TOKEN byte has already been read. * *@param packetType Description of * Parameter *@return a <code>PacketEndTokenResult</code> for the next DONEINPROC, * DONEPROC or DONE packet *@exception net.sourceforge.jtds.jdbc.TdsException *@exception java.io.IOException Thrown if some sort of * error occured reading bytes from the network. */ private PacketEndTokenResult processEndToken( byte packetType) throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { byte status = comm.getByte(); comm.getByte(); byte op = comm.getByte(); comm.getByte(); // comm.skip(3); int rowCount = comm.getTdsInt(); if (op == (byte)0xC1) rowCount = 0; if (packetType == TdsDefinitions.TDS_DONEPROC) rowCount = -1; PacketEndTokenResult result = new PacketEndTokenResult(packetType, status, rowCount); // XXX If we executed something that returns multiple result // sets then we don't want to clear the query in progress flag. // See the CancelController class for details. cancelController.finishQuery(result.wasCanceled(), result.moreResults()); // XXX Problem handling cancels that were sent after the server // send the endToken packet return result; } private PacketDoneInProcResult processDoneInProc( byte packetType) throws SQLException, TdsException, java.io.IOException { byte status = comm.getByte(); comm.skip(3); int rowCount = comm.getTdsInt(); PacketDoneInProcResult result = new PacketDoneInProcResult(packetType, status, rowCount); if (!result.moreResults()) { throw new TdsException("What? No more results with a DONEINPROC!"); } if (result.moreResults() && peek() == TdsDefinitions.TDS_DONEINPROC) { result = (PacketDoneInProcResult) processSubPacket(); } while( result.moreResults() && (peek()==TdsDefinitions.TDS_PROCID || peek()==TdsDefinitions.TDS_RETURNSTATUS) ) { if( peek() == TDS_PROCID ) processSubPacket(); else if( peek() == TDS_RETURNSTATUS ) { PacketRetStatResult tmp = (PacketRetStatResult)processSubPacket(); result.setRetStat(tmp.getRetStat()); } } // XXX If we executed something that returns multiple result // sets then we don't want to clear the query in progress flag. // See the CancelController class for details. cancelController.finishQuery(result.wasCanceled(), result.moreResults()); return result; } /** * Find out how many bytes a particular SQLServer data type takes. * *@param nativeColumnType *@return number of bytes * required by the given type *@exception net.sourceforge.jtds.jdbc.TdsException Thrown if the given * type either doesn't exist or is a variable sized data type. */ private int lookupBufferSize(byte nativeColumnType) throws net.sourceforge.jtds.jdbc.TdsException { switch (nativeColumnType) { case SYBINT1: { return 1; } case SYBINT2: { return 2; } case SYBINT4: { return 4; } case SYBREAL: { return 4; } case SYBFLT8: { return 8; } case SYBDATETIME: { return 8; } case SYBDATETIME4: { return 4; } case SYBBIT: { return 1; } case SYBMONEY: { return 8; } case SYBMONEY4: case SYBSMALLMONEY: { return 4; } default: { throw new TdsException("Not fixed size column " + nativeColumnType); } } } private int lookupDisplaySize(byte nativeColumnType) throws net.sourceforge.jtds.jdbc.TdsException { switch (nativeColumnType) { case SYBINT1: { return 3; } case SYBINT2: { return 6; } case SYBINT4: { return 11; } case SYBREAL: { return 14; } case SYBFLT8: { return 24; } case SYBDATETIME: { return 23; } case SYBDATETIME4: { return 16; } case SYBBIT: { return 1; } case SYBMONEY: { return 21; } case SYBMONEY4: case SYBSMALLMONEY: { return 12; } default: { throw new TdsException("Not fixed size column " + nativeColumnType); } } } private void writeDatetimeValue(Object value_in, int nativeType) throws java.io.IOException { comm.appendByte((byte)nativeType); if( value_in == null ) { comm.appendByte((byte)8); comm.appendByte((byte)0); } else { final int secondsPerDay = 24 * 60 * 60; final int msPerDay = secondsPerDay * 1000; final int nsPerMs = 1000 * 1000; final int msPerMinute = 1000 * 60; // epochsDifference is the number of days between unix // epoch (1970 based) and the sybase epoch (1900 based) final int epochsDifference = 25567; // ms is the number of milliseconds into unix epoch long ms = 0; if (value_in instanceof java.sql.Timestamp) { Timestamp value = (Timestamp)value_in; ms = value.getTime(); // SAfe If the value contains only an integral number of seconds, add the nanoseconds, // otherwise they have probably already been added. This seems to be a problem with // J2SE 1.4 and later, which override the java.util.Date.getTime() implementation // and add the nanos there (although the javadoc comment hasn't changed). if( ms%1000 == 0 ) ms += (value.getNanos()/nsPerMs); } else ms = ((java.util.Date)value_in).getTime(); ms += zoneOffset; ms += getDstOffset(ms); long msIntoCurrentDay = ms % msPerDay; long daysIntoUnixEpoch = ms / msPerDay; // SAfe This happens with dates prior to 1970 (UNIX epoch) if( msIntoCurrentDay < 0 ) { msIntoCurrentDay += msPerDay; daysIntoUnixEpoch -= 1; } if( value_in instanceof java.sql.Date ) msIntoCurrentDay = 0; else if( value_in instanceof java.sql.Time ) daysIntoUnixEpoch = 0; int daysIntoSybaseEpoch = (int)daysIntoUnixEpoch + epochsDifference; // If the number of seconds and milliseconds are set to zero, then // pass this as a smalldatetime parameter. Otherwise, pass it as // a datetime parameter if( (msIntoCurrentDay % msPerMinute)==0 && daysIntoSybaseEpoch > Short.MIN_VALUE && daysIntoSybaseEpoch < Short.MAX_VALUE ) { comm.appendByte((byte)4); comm.appendByte((byte)4); comm.appendTdsShort((short)daysIntoSybaseEpoch); comm.appendTdsShort((short)(msIntoCurrentDay / msPerMinute)); } else { // SAfe Rounding problem: without the +100, 'Jan 4 2003 2:22:39:803' would get passed as // 'Jan 4 2003 2:22:39:800'. Should we use +500 instead? int jiffies = (int)((msIntoCurrentDay*300 + 100) / 1000); comm.appendByte((byte)8); comm.appendByte((byte)8); comm.appendTdsInt(daysIntoSybaseEpoch); comm.appendTdsInt(jiffies); } } } private void writeDecimalValue(byte nativeType, Object o, int scalePar, int precision) throws TdsException, java.io.IOException { comm.appendByte(SYBDECIMAL); if (o == null) { comm.appendByte((byte)0); comm.appendByte((byte)38); comm.appendByte((byte)10); comm.appendByte((byte)0); } else { if (o instanceof Long) { long value = ((Long)o).longValue(); comm.appendByte((byte)9); comm.appendByte((byte)38); comm.appendByte((byte)0); comm.appendByte((byte)9); if (value >= 0L) { comm.appendByte((byte)1); } else { comm.appendByte((byte)0); value = -value; } for (int valueidx = 0; valueidx<8; valueidx++) { // comm.appendByte((byte)(value & 0xFF)); comm.appendByte((byte)(value & 0xFF)); value >>>= 8; } } else { BigDecimal bd; if( o instanceof BigDecimal ) bd = (BigDecimal)o; else if( o instanceof Number ) bd = new BigDecimal(((Number)o).doubleValue()); else if( o instanceof Boolean ) bd = new BigDecimal(((Boolean)o).booleanValue() ? 1 : 0); else bd = new BigDecimal(o.toString()); boolean repeat = false; byte scale; byte signum = (byte)(bd.signum() < 0 ? 0 : 1); byte[] mantisse; byte len; do { scale = (byte)bd.scale(); BigInteger bi = bd.unscaledValue(); mantisse = bi.abs().toByteArray(); len = (byte)(mantisse.length + 1); if (len > 17) { // diminish scale as long as len is to much int dif = len - 17; scale -= dif * 2; if (scale < 0) throw new TdsException("cant sent this BigDecimal"); bd = bd.setScale(scale,BigDecimal.ROUND_HALF_UP); repeat = true; } else break; } while (repeat); byte prec = 38; comm.appendByte(len); comm.appendByte(prec); comm.appendByte(scale); comm.appendByte(len); comm.appendByte(signum); for (int mantidx = mantisse.length - 1; mantidx >= 0 ; mantidx comm.appendByte(mantisse[mantidx]); } } } /* BigDecimal d; if (value == null || value instanceof BigDecimal) { d = (BigDecimal)value; } else if (value instanceof BigInteger) { d = new BigDecimal((BigInteger)value, 0); } else if (value instanceof Number) { d = new BigDecimal(((Number)value).doubleValue()); } else { throw new TdsException("Invalid decimal value"); } byte[] data; int signum; byte scale = (byte)d.scale(); if (value == null) { data = null; signum = 0; if (precision == -1) { precision = 10; } } else { BigInteger unscaled = d.movePointRight(scale).unscaledValue(); BigInteger absunscaled = unscaled.abs(); data = absunscaled.toByteArray(); if (data.length > 0x11) { throw new TdsException("Decimal value too large"); } signum = unscaled.signum(); if (precision == -1) { precision = 10; } int bitLength = absunscaled.bitLength(); int maxLength = (int)(1.0 + (float)bitLength * 0.30103); if (precision < maxLength) { precision = maxLength; } } comm.appendByte(nativeType); comm.appendByte((byte)0x11); // max length in bytes comm.appendByte((byte)precision); // precision comm.appendByte((byte)scale); // scale if (value == null) { comm.appendByte((byte)0); } else { comm.appendByte((byte)(data.length + 1)); comm.appendByte(signum < 0 ? (byte)0 : (byte)1); comm.appendBytes(data); } */ } private Object readFloatN(int len) throws TdsException, java.io.IOException { Object tmp; switch (len) { case 8: { long l = comm.getTdsInt64(); tmp = new Double(Double.longBitsToDouble(l)); break; } case 4: { int i = comm.getTdsInt(); tmp = new Float(Float.intBitsToFloat(i)); break; } case 0: { tmp = null; break; } default: { throw new TdsNotImplemented("Don't now how to handle " + "float with size of " + len + "(0x" + Integer.toHexString(len & 0xff) + ")"); } } return tmp; } // getRow() private boolean createStoredProcedureNameTable() { boolean result = false; String sql = null; try { java.sql.Statement stmt = connection.createStatement(); // ignore any of the exceptions thrown because they either // don't matter or they will make themselves known when we try // to use the name generator stored procedure. try { sql = "" + "create table " + procNameTableName + "( " + " id NUMERIC(10, 0) IDENTITY, " + " session int not null, " + " name char(29) not null " + ") "; stmt.executeUpdate(sql); } catch (java.sql.SQLException e) { // don't care } try { sql = "" + "create procedure " + procNameGeneratorName + " " + "as " + "begin tran " + "insert into " + procNameTableName + " " + " (session, name) " + " values " + " (@@spid, '') " + " " + "update " + procNameTableName + " " + " set name=('" + user + ".jdbctmpsp' + " + " convert(varchar, @@IDENTITY)) " + " where id = @@IDENTITY " + " " + "select name from " + procNameTableName + " " + " where id=@@IDENTITY " + " " + "commit tran " + ""; stmt.execute(sql); stmt.execute("sp_procxmode " + procNameGeneratorName + ", 'anymode' "); } catch (java.sql.SQLException e) { // don't care } stmt = null; } catch (java.sql.SQLException e) { // don't care } return result; } private String generateUniqueProcName() throws java.sql.SQLException { java.sql.Statement stmt = connection.createStatement(); boolean wasRs; wasRs = stmt.execute("exec " + procNameGeneratorName); if (!wasRs) { throw new java.sql.SQLException( "Confused. Was expecting a result set."); } java.sql.ResultSet rs; rs = stmt.getResultSet(); if (!rs.next()) { throw new java.sql.SQLException("Couldn't get stored proc name"); } return rs.getString(1); } /* * executeProcedure() */ private void sendSybImage( byte[] value) throws java.io.IOException { int i; int length = (value == null ? 0 : value.length); // send the lenght of this piece of data comm.appendTdsInt(length); // send the length of this piece of data again comm.appendTdsInt(length); // send the data for (i = 0; i < length; i++) { comm.appendByte(value[i]); } } private void sendSybChar( String value, int maxLength) throws java.io.IOException { byte[] converted; if( value == null ) { comm.appendByte(SYBVARCHAR); comm.appendByte((byte)(maxLength>255 ? 255 : maxLength)); comm.appendByte((byte)0); return; } else converted = encoder.getBytes(value); // set the type of the column // set the maximum length of the field // set the actual lenght of the field. if( tdsVer == TDS70 ) { comm.appendByte((byte) (SYBVARCHAR | 0x80)); comm.appendTdsShort((short) (maxLength)); comm.appendTdsShort((short) (converted.length)); } else { if( maxLength>255 || converted.length>255 ) throw new java.io.IOException("String too long"); comm.appendByte(SYBVARCHAR); comm.appendByte((byte) (maxLength)); if( converted.length != 0 ) comm.appendByte((byte) (converted.length)); else { comm.appendByte((byte)1); comm.appendByte((byte)32); } } comm.appendBytes(converted); } /** * Process a login ack supacket * *@return Description of the * Returned Value *@exception net.sourceforge.jtds.jdbc.TdsException Description of * Exception *@exception java.io.IOException Description of * Exception */ private PacketResult processLoginAck() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { getSubPacketLength(); // Packet length if( tdsVer == Tds.TDS70 ) { comm.skip(5); int nameLen = comm.getByte(); databaseProductName = comm.getString(nameLen, encoder); databaseProductVersion = ("0" + (databaseMajorVersion=comm.getByte()) + ".0" + comm.getByte() + ".0" + ((256 * ((int)comm.getByte()+1)) + comm.getByte())); } else { comm.skip(5); short nameLen = comm.getByte(); databaseProductName = comm.getString(nameLen, encoder); comm.skip(1); databaseProductVersion = ("" + (databaseMajorVersion=comm.getByte()) + "." + comm.getByte()); comm.skip(1); } if (databaseProductName.length() > 1 && -1 != databaseProductName.indexOf('\0')) { int last = databaseProductName.indexOf('\0'); databaseProductName = databaseProductName.substring(0, last); } return new PacketResult(TDS_LOGINACK); } /** * Process an proc id subpacket. <p> * * This routine assumes that the TDS_PROCID byte has already been read. * *@return Description of the * Returned Value *@exception net.sourceforge.jtds.jdbc.TdsException *@exception java.io.IOException Thrown if some sort of * error occured reading bytes from the network. */ private PacketResult processProcId() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { // XXX Try to find out what meaning this subpacket has. comm.skip(8); return new PacketResult(TDS_PROCID); } /** * Process a TDS_RET_STAT_TOKEN subpacket. <p> * * This routine assumes that the TDS_RET_STAT_TOKEN byte has already been * read. * *@return Description of the * Returned Value *@exception net.sourceforge.jtds.jdbc.TdsException *@exception java.io.IOException Thrown if some sort of * error occured reading bytes from the network. */ private PacketRetStatResult processRetStat() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { // XXX Not completely sure of this. return new PacketRetStatResult(comm.getTdsInt()); } /** * Processes a TDS 7.0-style result packet, extracting column information * for the result set. Added 2000-06-05. * *@return Description of the * Returned Value *@exception java.io.IOException Description of * Exception *@exception net.sourceforge.jtds.jdbc.TdsException Description of * Exception */ private PacketResult processTds7Result() throws java.io.IOException, net.sourceforge.jtds.jdbc.TdsException { int numColumns = comm.getTdsShort(); Columns columns = new Columns(numColumns); for (int colNum = 1; colNum <= numColumns; ++colNum) { /* * The freetds C code didn't know what to do with these four * bytes, but initial inspection appears to tentatively confirm * that they serve the same purpose as the flag bytes read by the * Java code for 4.2 column information. */ byte flagData[] = new byte[4]; for (int i = 0; i < 4; i++) { flagData[i] = comm.getByte(); } boolean nullable = (flagData[2] & 0x01) > 0; boolean caseSensitive = (flagData[2] & 0x02) > 0; boolean writable = (flagData[2] & 0x0C) > 0; boolean autoIncrement = (flagData[2] & 0x10) > 0; /* * Get the type of column. Large types have 2-byte size fields and * type codes OR'd with 0x80. Except SYBNCHAR, whose type code * is already above 0x80. */ int columnType = comm.getByte() & 0xFF; if (columnType == 0xEF) { columnType = SYBNCHAR; } int xColType = -1; if (isLargeType(columnType)) { xColType = columnType; if (columnType != SYBNCHAR) { columnType -= 128; } } // Determine the column size. int dispSize=-1, bufLength; String tableName = ""; if (isBlobType(columnType)) { // Text and image columns have 4-byte size fields. bufLength = comm.getTdsInt(); // Get table name. tableName = comm.getString(comm.getTdsShort(), encoder); } // Fixed types have no size field in the packet. else if (isFixedSizeColumn((byte) columnType)) { bufLength = lookupBufferSize((byte) columnType); } else if (isLargeType(xColType)) { bufLength = comm.getTdsShort(); } else { bufLength = comm.getByte(); } // Get precision, scale for decimal types. int precision = -1; int scale = -1; if (columnType == SYBDECIMAL || columnType == SYBNUMERIC) { precision = comm.getByte(); scale = comm.getByte(); } /* * NB: under 7.0 lengths are number of characters, not number of * bytes. The getString() method handles this. */ int colNameLen = comm.getByte(); String columnName = comm.getString(colNameLen, encoder); // Populate the Column object. populateColumn(columns.getColumn(colNum), columnType, columnName, dispSize, bufLength, nullable, autoIncrement, writable, caseSensitive, tableName, precision, scale); } currentContext = new Context(columns, encoder); return new PacketColumnNamesResult(columns); } private void populateColumn(Column col, int columnType, String columnName, int dispSize, int bufLength, boolean nullable, boolean autoIncrement, boolean writable, boolean caseSensitive, String tableName, int precision, int scale) { if( columnName != null ) { col.setName(columnName); col.setLabel(columnName); } col.setType(columnType); col.setBufferSize(bufLength); col.setNullable(nullable ? ResultSetMetaData.columnNullable : ResultSetMetaData.columnNoNulls); col.setAutoIncrement(autoIncrement); col.setReadOnly(!writable); col.setCaseSensitive(caseSensitive); // Set table name (and catalog and schema, if available) if( tableName != null ) { int pos = tableName.lastIndexOf('.'); col.setTableName(tableName.substring(pos+1)); pos = pos==-1 ? 0 : pos; tableName = tableName.substring(0, pos); if( pos > 0 ) { pos = tableName.lastIndexOf('.'); col.setSchema(tableName.substring(pos+1)); pos = pos==-1 ? 0 : pos; tableName = tableName.substring(0, pos); } if( pos > 0 ) col.setCatalog(tableName); } // Set scale switch( columnType ) { case SYBMONEY: case SYBMONEYN: case SYBMONEY4: case SYBSMALLMONEY: col.setScale(4); break; case SYBDATETIME: col.setScale(3); break; case SYBDATETIMN: if( bufLength == 8 ) col.setScale(3); else col.setScale(0); break; default: col.setScale(scale<0 ? 0 : scale); } // Set precision and display size switch( columnType ) { case SYBBINARY: case SYBIMAGE: case SYBVARBINARY: dispSize = 2 * (precision = bufLength); break; case SYBCHAR: case SYBTEXT: case SYBVARCHAR: dispSize = precision = bufLength; break; case SYBNCHAR: case SYBNTEXT: case SYBNVARCHAR: dispSize = precision = bufLength>>1; break; case SYBBIT: dispSize = precision = 1; break; case SYBUNIQUEID: dispSize = precision = 36; break; case SYBDATETIME: dispSize = precision = 23; break; case SYBDATETIME4: dispSize = 3 + (precision = 16); break; case SYBDATETIMN: if( bufLength == 8 ) dispSize = precision = 23; else dispSize = 3 + (precision = 16); break; case SYBDECIMAL: case SYBNUMERIC: dispSize = (bufLength==scale ? 3 : 2) + precision; break; case SYBFLT8: dispSize = 9 + (precision = 15); break; case SYBREAL: dispSize = 7 + (precision = 7); break; case SYBFLTN: if( bufLength == 8 ) dispSize = 9 + (precision = 15); else dispSize = 7 + (precision = 7); break; case SYBINT4: dispSize = 1 + (precision = 10); break; case SYBINT2: dispSize = 1 + (precision = 5); break; case SYBINT1: dispSize = 1 + (precision = 2); break; case SYBINTN: if( bufLength == 4 ) dispSize = 1 + (precision = 10); else if( bufLength == 2 ) dispSize = 1 + (precision = 5); else dispSize = 1 + (precision = 2); break; case SYBMONEY: dispSize = 2 + (precision = 19); break; case SYBMONEY4: case SYBSMALLMONEY: dispSize = 2 + (precision = 10); break; case SYBMONEYN: if( bufLength == 8 ) dispSize = 2 + (precision = 19); else dispSize = 2 + (precision = 10); break; } col.setDisplaySize(dispSize); col.setPrecision(precision); } private void waitForDataOrTimeout(SQLWarningChain wChain, int timeout) throws java.io.IOException, TdsException { // SAfe No synchronization needed, this is only used internally so it's // already synched. if( timeout == 0 || wChain == null ) comm.peek(); else { // start the timeout thread TimeoutHandler t = new TimeoutHandler(this, wChain, timeout); t.start(); // wait until there is at least one byte of data comm.peek(); // kill the timeout thread t.interrupt(); t = null; } } /** * Convert a JDBC java.sql.Types identifier to a SQLServer type identifier * *@param jdbcType JDBC type to convert. Should be one of the constants from java.sql.Types. *@return The corresponding SQLServer type identifier. *@exception TdsNotImplemented Description of Exception */ public static byte cvtJdbcTypeToNativeType(int jdbcType) throws TdsNotImplemented { // This function is thread safe. byte result = 0; switch (jdbcType) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: { result = SYBCHAR; break; } case java.sql.Types.TINYINT: { result = SYBINT1; break; } case java.sql.Types.SMALLINT: { result = SYBINT2; break; } case java.sql.Types.INTEGER: { result = SYBINT4; break; } case java.sql.Types.BIT: { result = SYBBIT; break; } case java.sql.Types.FLOAT: case java.sql.Types.REAL: case java.sql.Types.DOUBLE: { result = SYBFLT8; break; } case java.sql.Types.DATE: case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: { result = SYBDATETIMN; break; } case java.sql.Types.BINARY: { result = SYBBINARY; break; } case java.sql.Types.VARBINARY: { result = SYBVARBINARY; break; } case java.sql.Types.LONGVARBINARY: { result = SYBIMAGE; break; } case java.sql.Types.BIGINT: { result = SYBDECIMAL; break; } case java.sql.Types.NUMERIC: { result = SYBNUMERIC; break; } case java.sql.Types.DECIMAL: { result = SYBDECIMAL; break; } default: { throw new TdsNotImplemented("cvtJdbcTypeToNativeType (" + TdsUtil.javaSqlTypeToString(jdbcType) + ")"); } } return result; } /** * Convert a JDBC java.sql.Types identifier to a SQLServer type identifier * *@param nativeType SQLServer type to convert. *@param size Maximum size of data coming back from server. *@return The corresponding JDBC type identifier. *@exception TdsException Description of Exception */ public static int cvtNativeTypeToJdbcType(int nativeType, int size) throws TdsException { // This function is thread safe. int result = java.sql.Types.OTHER; switch (nativeType) { // XXX We need to figure out how to map _all_ of these types case SYBBINARY: result = java.sql.Types.BINARY; break; case SYBBIT: result = java.sql.Types.BIT; break; case SYBBITN: result = java.sql.Types.BIT; break; case SYBCHAR: result = java.sql.Types.CHAR; break; case SYBNCHAR: result = java.sql.Types.CHAR; break; case SYBDATETIME4: result = java.sql.Types.TIMESTAMP; break; case SYBDATETIME: result = java.sql.Types.TIMESTAMP; break; case SYBDATETIMN: result = java.sql.Types.TIMESTAMP; break; case SYBDECIMAL: result = java.sql.Types.DECIMAL; break; case SYBNUMERIC: result = java.sql.Types.NUMERIC; break; case SYBFLT8: result = java.sql.Types.FLOAT; break; case SYBFLTN: { switch (size) { case 4: result = java.sql.Types.REAL; break; case 8: result = java.sql.Types.FLOAT; break; default: throw new TdsException("Bad size of SYBFLTN"); } break; } case SYBINT1: result = java.sql.Types.TINYINT; break; case SYBINT2: result = java.sql.Types.SMALLINT; break; case SYBINT4: result = java.sql.Types.INTEGER; break; case SYBINTN: { switch (size) { case 1: result = java.sql.Types.TINYINT; break; case 2: result = java.sql.Types.SMALLINT; break; case 4: result = java.sql.Types.INTEGER; break; default: throw new TdsException("Bad size of SYBINTN"); } break; } // XXX Should money types by NUMERIC or OTHER? // SAfe JDBC-ODBC bridge returns DECIMAL case SYBSMALLMONEY: result = java.sql.Types.DECIMAL; break; case SYBMONEY4: result = java.sql.Types.DECIMAL; break; case SYBMONEY: result = java.sql.Types.DECIMAL; break; case SYBMONEYN: result = java.sql.Types.DECIMAL; break; // case SYBNUMERIC: result = java.sql.Types.NUMERIC; break; case SYBREAL: result = java.sql.Types.REAL; break; case SYBTEXT: result = java.sql.Types.LONGVARCHAR; break; case SYBNTEXT: result = java.sql.Types.LONGVARCHAR; break; case SYBIMAGE: // should be : result = java.sql.Types.LONGVARBINARY; result = java.sql.Types.VARBINARY; // work around XXXX break; case SYBVARBINARY: result = java.sql.Types.VARBINARY; break; case SYBVARCHAR: result = java.sql.Types.VARCHAR; break; case SYBNVARCHAR: result = java.sql.Types.VARCHAR; break; // case SYBVOID: result = java.sql.Types. ; break; case SYBUNIQUEID: result = java.sql.Types.VARCHAR; break; default: throw new TdsException("Unknown native data type " + Integer.toHexString( nativeType & 0xff)); } return result; } // processTds7Result() /** * Reports whether the type is for a large object. Name is a bit of a * misnomer, since it returns true for large text types, not just binary * objects (took it over from the freetds C code). * *@param type Description of Parameter *@return The BlobType value */ private static boolean isBlobType(int type) { return type == SYBTEXT || type == SYBIMAGE || type == SYBNTEXT; } /** * Reports whether the type uses a 2-byte size value. * *@param type Description of Parameter *@return The LargeType value */ private static boolean isLargeType(int type) { return type == SYBNCHAR || type > 128; } private static int toUInt(byte b) { int result = ((int) b) & 0x00ff; return result; } /** * This is a <B>very</B> poor man's "encryption." * *@param pw Description of Parameter *@return Description of the Returned Value */ private static String tds7CryptPass(String pw) { int xormask = 0x5A5A; int len = pw.length(); char[] chars = new char[len]; for (int i = 0; i < len; ++i) { int c = (int) (pw.charAt(i)) ^ xormask; int m1 = (c >> 4) & 0x0F0F; int m2 = (c << 4) & 0xF0F0; chars[i] = (char) (m1 | m2); } return new String(chars); } /** * All procedures of the current transaction were submitted. */ synchronized void commit() throws SQLException { // SAfe Consume all outstanding packets first skipToEnd(); // MJH Move commit code from TdsStatement to Tds as this // object represents the connection which the server uses // to control the session. String sql = "IF @@TRANCOUNT>0 COMMIT TRAN"; submitProcedure(sql, new SQLWarningChain()); synchronized( procedureCache ) { proceduresOfTra.clear(); } } /** * All procedures of the current transaction were rolled back. */ synchronized void rollback() throws SQLException { // SAfe Consume all outstanding packets first skipToEnd(); // MJH Move the rollback code from TdsStatement to Tds as this // object represents the connection which the server uses // to control the session. // Also reinstate code to add back procedures after rollback as // this does lead to performance benefits with EJB. SQLException exception = null; try { submitProcedure("IF @@TRANCOUNT>0 ROLLBACK TRAN", new SQLWarningChain()); } catch( SQLException e ) { exception = e; } synchronized( procedureCache ) { // SAfe No need to reinstate procedures. This ONLY leads to performance // benefits if the statement is reused. The overhead is the same // (plus some memory that's freed and reallocated). Iterator it = proceduresOfTra.iterator(); while( it.hasNext() ) { Procedure p = (Procedure)it.next(); // MJH Use signature (includes parameters) // rather than rawSqlQueryString procedureCache.remove(p.getSignature()); } proceduresOfTra.clear(); } if( exception != null ) throw exception; } // SAfe This method is *completely* unsafe (although I was the brilliant // mind who wrote it :o( ). It will have to wait until the Tds will // manage its own Context; that way it will know exactly how to deal // with packages. Anyway, it seems a little bit useless. Or not? // SAfe No longer true! The method should work just fine, now that we have // a Tds-managed Context. :o) synchronized void skipToEnd() throws java.sql.SQLException { PacketResult tmp; try { while( moreResults ) { tmp = processSubPacket(); moreResults = !(tmp instanceof PacketEndTokenResult) || ((PacketEndTokenResult)tmp).moreResults(); } } catch( Exception ex ) { if( ex instanceof SQLException ) throw (SQLException)ex; throw new SQLException( "Error occured while consuming output: " + ex); } } private String sqlStatementToInitialize() throws SQLException { StringBuffer statement = new StringBuffer(100); if (serverType == Tds.SYBASE) { statement.append("set quoted_identifier on set textsize 50000 "); } else if (tdsVer == TDS70) { // Patch 861821: Seems like there is some kind of initial limitation to // the size of the written data to 4000 characters (???) // Yes - SQL Server 2000 Developer Edition defaults to 4k... statement.append("set textsize 2147483647 "); } // SAfe We also have to add these until we find out how to put them in // the login packet (if that is possible at all) statement.append(sqlStatementToSetTransactionIsolationLevel()); statement.append(' '); statement.append(sqlStatementToSetCommit()); return statement.toString(); } private String sqlStatementToSetTransactionIsolationLevel() throws SQLException { StringBuffer sql = new StringBuffer(64); sql.append("set transaction isolation level "); switch (transactionIsolationLevel) { case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED: sql.append("read uncommitted"); break; case java.sql.Connection.TRANSACTION_READ_COMMITTED: sql.append("read committed"); break; case java.sql.Connection.TRANSACTION_REPEATABLE_READ: sql.append("repeatable read"); break; case java.sql.Connection.TRANSACTION_SERIALIZABLE: sql.append("serializable"); break; case java.sql.Connection.TRANSACTION_NONE: default: throw new SQLException("Bad transaction level"); } return sql.toString(); } private String sqlStatementToSetCommit() { String result; if (serverType == Tds.SYBASE) { if (autoCommit) { result = "set CHAINED off"; } else { result = "set CHAINED on"; } } else { if (autoCommit) { result = "set implicit_transactions off"; } else { result = "set implicit_transactions on"; } } return result; } private String sqlStatementForSettings( boolean autoCommit, int transactionIsolationLevel) throws SQLException { StringBuffer res = new StringBuffer(64); // SAfe The javadoc for setAutoCommit states that "if the method is // called during a transaction, the transaction is committed" // @todo SAfe Only execute this when setAutoCommit is called, not for // setTransactionIsolationLevel res.append("IF @@TRANCOUNT>0 COMMIT TRAN "); if( autoCommit != this.autoCommit ) { this.autoCommit = autoCommit; // SAfe We must *NOT* do this! The user must do this himself or // otherwise it will be rolled back when the connection is // closed. // if( autoCommit ) // res.append("if @@trancount>0 commit tran "); res.append(sqlStatementToSetCommit()).append(' '); } if( transactionIsolationLevel != this.transactionIsolationLevel ) { this.transactionIsolationLevel = transactionIsolationLevel; res.append(sqlStatementToSetTransactionIsolationLevel()).append(' '); } res.setLength(res.length()-1); return res.toString(); } protected synchronized void changeSettings( boolean autoCommit, int transactionIsolationLevel) throws SQLException { String query = sqlStatementForSettings(autoCommit, transactionIsolationLevel); if( query != null ) try { skipToEnd(); changeSettings(query); } catch( SQLException ex ) { throw ex; } catch( Exception ex ) { throw new SQLException(ex.toString()); } } private boolean changeSettings(String query) throws TdsUnknownPacketSubType, TdsException, java.io.IOException, SQLException { boolean isOkay = true; PacketResult result; if( query.length() == 0 ) return true; executeQuery(query, null, null, 0); boolean done = false; while (!done) { result = processSubPacket(); done = (result instanceof PacketEndTokenResult) && !((PacketEndTokenResult) result).moreResults(); if (result instanceof PacketErrorResult) { isOkay = false; } // XXX Should really process some more types of packets. } return isOkay; } /** * Process an ntlm challenge... * Added by mdb to handle NT authentication to MS SQL Server */ private PacketResult processNtlmChallenge() throws net.sourceforge.jtds.jdbc.TdsException, java.io.IOException { int packetLength = getSubPacketLength(); // Packet length final int headerLength = 40; if (packetLength < headerLength) throw new TdsException("NTLM challenge: packet is too small:"+packetLength); comm.skip(8); //header "NTLMSSP\0" int seq = comm.getTdsInt(); //sequence number (2) if( seq != 2 ) throw new TdsException("NTLM challenge: got unexpected sequence number:"+seq); comm.skip(4); //domain length (repeated 2x) comm.skip(4); //domain offset comm.skip(4); //flags byte[] nonce = comm.getBytes(8, true); // this is what we really care about comm.skip(8); //?? unknown //skip the end, which may include the domain name, among other things... comm.skip(packetLength-headerLength); return new PacketAuthTokenResult(nonce); } private void sendNtlmChallengeResponse(PacketAuthTokenResult authToken) throws TdsException, java.io.IOException { try { comm.startPacket(TdsComm.NTLMAUTH); // host and domain name are _narrow_ strings. //byte[] domainBytes = domain.getBytes("UTF8"); //byte[] user = user.getBytes("UTF8"); byte[] header = { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 }; comm.appendBytes( header ); //header is ascii "NTLMSSP\0" comm.appendTdsInt(3); //sequence number = 3 int domainLenInBytes = domain.length()*2; int userLenInBytes = user.length()*2; //mdb: not sending hostname; I hope this is ok! int hostLenInBytes = 0; //localhostname.length()*2; int pos = 64 + domainLenInBytes + userLenInBytes + hostLenInBytes; // lan man response: length and offset comm.appendTdsShort( (short)24 ); comm.appendTdsShort( (short)24 ); comm.appendTdsInt(pos); pos += 24; // nt response: length and offset comm.appendTdsShort( (short)24 ); comm.appendTdsShort( (short)24 ); comm.appendTdsInt(pos); pos = 64; //domain comm.appendTdsShort( (short)domainLenInBytes ); comm.appendTdsShort( (short)domainLenInBytes ); comm.appendTdsInt(pos); pos += domainLenInBytes; //user comm.appendTdsShort( (short)userLenInBytes ); comm.appendTdsShort( (short)userLenInBytes ); comm.appendTdsInt(pos); pos += userLenInBytes; //local hostname comm.appendTdsShort( (short)hostLenInBytes ); comm.appendTdsShort( (short)hostLenInBytes ); comm.appendTdsInt(pos); pos += hostLenInBytes; //unknown comm.appendTdsShort( (short)0 ); comm.appendTdsShort( (short)0 ); comm.appendTdsInt(pos); //flags comm.appendTdsInt(0x8201); //flags (???) //variable length stuff... comm.appendChars(domain); comm.appendChars(user); //Not sending hostname...I hope this is OK! //comm.appendChars(localhostname); //the response to the challenge... byte[] lmAnswer = NtlmAuth.answerLmChallenge(password, authToken.getNonce()); byte[] ntAnswer = NtlmAuth.answerNtChallenge(password, authToken.getNonce()); comm.appendBytes(lmAnswer); comm.appendBytes(ntAnswer); comm.sendPacket(); } finally { //TODO(mdb): why do I have to do this? comm.packetType = 0; } } public Context getContext() { return currentContext; } public Procedure findCompatibleStoredProcedure(String signature) { synchronized( procedureCache ) { return (Procedure)procedureCache.get(signature); } } public void addStoredProcedure(Procedure procedure) throws SQLException { synchronized( procedureCache ) { // store the procedure in the procedureCache // MJH Use the signature (includes parameters) // rather than rawQueryString procedureCache.put( procedure.getSignature(), procedure ); // MJH Only record the proc name in proceduresOfTra if in manual commit mode if( !connection.getAutoCommit() ) proceduresOfTra.add( procedure ); } } public boolean useUnicode() { return useUnicode; } }
package com.axelor.apps.supplychain.service.declarationofexchanges; import com.axelor.apps.ReportFactory; import com.axelor.apps.account.db.Invoice; import com.axelor.apps.account.db.repo.InvoiceRepository; import com.axelor.apps.base.db.Address; import com.axelor.apps.base.db.Period; import com.axelor.apps.base.db.Product; import com.axelor.apps.report.engine.ReportSettings; import com.axelor.apps.stock.db.ModeOfTransport; import com.axelor.apps.stock.db.NatureOfTransaction; import com.axelor.apps.stock.db.Regime; import com.axelor.apps.stock.db.StockMove; import com.axelor.apps.stock.db.StockMoveLine; import com.axelor.apps.stock.db.repo.StockMoveLineRepository; import com.axelor.apps.stock.db.repo.StockMoveRepository; import com.axelor.apps.stock.service.StockMoveToolService; import com.axelor.apps.supplychain.db.DeclarationOfExchanges; import com.axelor.apps.supplychain.report.IReport; import com.axelor.apps.tool.file.CsvTool; import com.axelor.auth.AuthUtils; import com.axelor.common.StringUtils; import com.axelor.exception.AxelorException; import com.axelor.exception.db.repo.TraceBackRepository; import com.axelor.i18n.I18n; import com.axelor.inject.Beans; import com.google.common.io.MoreFiles; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; import java.util.Set; public class DeclarationOfExchangesExporterGoods extends DeclarationOfExchangesExporter { protected static final String NAME_GOODS = "Declaration of exchanges of goods" ; protected static final String LINE_NUM = "Line number" ; protected static final String NOMENCLATURE = "Nomenclature" ; protected static final String SRC_DST_COUNTRY = "Source or destination country" ; protected static final String FISC_VAL = "Fiscal value" ; protected static final String REGIME = "Regime" ; protected static final String MASS = "Net mass" ; protected static final String UNITS = "Supplementary unit" ; protected static final String NAT_TRANS = "Nature of transaction" ; protected static final String TRANSP = "Mode of transport" ; protected static final String DEPT = "Department" ; protected static final String COUNTRY_ORIG = "Country of origin" ; protected static final String ACQUIRER = "Acquirer" ; protected static final String PRODUCT_CODE = "Product code" ; protected static final String PRODUCT_NAME = "Product name" ; protected static final String PARTNER_SEQ = "Partner" ; protected static final String INVOICE = "Invoice" ; protected StockMoveToolService stockMoveToolService; public DeclarationOfExchangesExporterGoods( DeclarationOfExchanges declarationOfExchanges, ResourceBundle bundle) { super( declarationOfExchanges, bundle, NAME_GOODS, new ArrayList<>( Arrays.asList( LINE_NUM, NOMENCLATURE, SRC_DST_COUNTRY, FISC_VAL, REGIME, MASS, UNITS, NAT_TRANS, TRANSP, DEPT, COUNTRY_ORIG, ACQUIRER, PRODUCT_CODE, PRODUCT_NAME, PARTNER_SEQ, INVOICE))); this.stockMoveToolService = Beans.get(StockMoveToolService.class); } @Override public String exportToCSV() throws AxelorException { Path path = getFilePath(); Period period = declarationOfExchanges.getPeriod(); List<StockMoveLine> stockMoveLines = Beans.get(StockMoveLineRepository.class) .findForDeclarationOfExchanges( period.getFromDate(), period.getToDate(), declarationOfExchanges.getProductTypeSelect(), declarationOfExchanges.getStockMoveTypeSelect(), declarationOfExchanges.getCountry(), declarationOfExchanges.getCompany()) .fetch(); List<String[]> dataList = new ArrayList<>(stockMoveLines.size()); int lineNum = 1; for (StockMoveLine stockMoveLine : stockMoveLines) { String[] data = exportLineToCsv(stockMoveLine, lineNum); if (data != null && data.length != 0) { dataList.add(data); lineNum++; } } try { MoreFiles.createParentDirectories(path); CsvTool.csvWriter( path.getParent().toString(), path.getFileName().toString(), ';', getTranslatedHeaders(), dataList); } catch (IOException e) { throw new AxelorException( e, TraceBackRepository.CATEGORY_CONFIGURATION_ERROR, e.getLocalizedMessage()); } return attach(path.toString()); } protected String[] exportLineToCsv(StockMoveLine stockMoveLine, int lineNum) throws AxelorException { String[] data = new String[columnHeadersList.size()]; StockMove stockMove = stockMoveLine.getStockMove(); String customsCode = stockMoveLine.getCustomsCode(); Product product = stockMoveLine.getProduct(); if (StringUtils.isBlank(customsCode)) { if (product == null) { customsCode = I18n.get("Product is missing."); } if (product != null && product.getCustomsCodeNomenclature() != null) { customsCode = product.getCustomsCodeNomenclature().getCode(); } if (StringUtils.isBlank(customsCode)) { customsCode = String.format( I18n.get("Customs code nomenclature is missing on product %s."), product.getCode()); } } BigDecimal fiscalValue = stockMoveLine .getCompanyUnitPriceUntaxed() .multiply(stockMoveLine.getRealQty()) .setScale(0, RoundingMode.HALF_UP); // Only positive fiscal value should be take into account if (fiscalValue.compareTo(BigDecimal.ZERO) <= 0) { return new String[0]; } Regime regime = stockMoveLine.getRegime(); if (regime == null) { if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_OUTGOING) { regime = Regime.EXONERATED_SHIPMENT_AND_TRANSFER; } else if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_INCOMING) { regime = Regime.INTRACOMMUNITY_ACQUISITION_TAXABLE_IN_FRANCE; } } BigDecimal totalNetMass = stockMoveLine.getTotalNetMass().setScale(0, RoundingMode.HALF_UP); BigInteger supplementaryUnit = stockMoveLine.getRealQty().setScale(0, RoundingMode.CEILING).toBigInteger(); NatureOfTransaction natTrans = stockMoveLine.getNatureOfTransaction(); if (natTrans == null) { natTrans = stockMove.getIsReversion() ? NatureOfTransaction.RETURN_OF_GOODS : NatureOfTransaction.FIRM_PURCHASE_OR_SALE; } ModeOfTransport modeOfTransport = stockMove.getModeOfTransport(); if (modeOfTransport == null) { modeOfTransport = ModeOfTransport.CONSIGNMENTS_BY_POST; } String srcDstCountry; String dept; try { Address partnerAddress = stockMoveToolService.getPartnerAddress(stockMoveLine.getStockMove()); srcDstCountry = partnerAddress.getAddressL7Country().getAlpha2Code(); } catch (AxelorException e) { srcDstCountry = e.getMessage(); } try { Address companyAddress = stockMoveToolService.getCompanyAddress(stockMoveLine.getStockMove()); dept = companyAddress.getCity().getDepartment().getCode(); } catch (AxelorException e) { dept = e.getMessage(); } String countryOrigCode; if (stockMoveLine.getCountryOfOrigin() != null) { countryOrigCode = stockMoveLine.getCountryOfOrigin().getAlpha2Code(); } else { if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_INCOMING) { countryOrigCode = srcDstCountry; } else { countryOrigCode = ""; } } String taxNbr; if (stockMove.getTypeSelect() == StockMoveRepository.TYPE_OUTGOING && stockMoveLine.getRegime() != Regime.OTHER_EXPEDITIONS) { if (stockMove.getPartner() == null) { taxNbr = String.format(I18n.get("Partner is missing on stock move %s."), stockMove.getName()); } else if (StringUtils.isBlank(stockMove.getPartner().getTaxNbr())) { taxNbr = String.format( I18n.get("Tax number is missing on partner %s."), stockMove.getPartner().getName()); } else { taxNbr = stockMove.getPartner().getTaxNbr(); } } else { taxNbr = ""; } String partnerSeq = ""; if (stockMove.getPartner() != null) { partnerSeq = stockMove.getPartner().getPartnerSeq(); } String productCode = ""; String productName = ""; if (product != null) { productCode = product.getCode(); productName = product.getName(); } String invoiceId = ""; Set<Invoice> invoiceSet = stockMove.getInvoiceSet(); if (invoiceSet != null) { for (Invoice invoice : invoiceSet) { if (invoice.getStatusSelect() == InvoiceRepository.STATUS_VENTILATED) { invoiceId += invoice.getInvoiceId() + "|"; } } if (invoiceId != null && !invoiceId.isEmpty()) { invoiceId = invoiceId.substring(0, invoiceId.length() - 1); } } data[columnHeadersList.indexOf(LINE_NUM)] = String.valueOf(lineNum); data[columnHeadersList.indexOf(NOMENCLATURE)] = customsCode; data[columnHeadersList.indexOf(SRC_DST_COUNTRY)] = srcDstCountry; data[columnHeadersList.indexOf(FISC_VAL)] = String.valueOf(fiscalValue); data[columnHeadersList.indexOf(REGIME)] = String.valueOf(regime.getValue()); data[columnHeadersList.indexOf(MASS)] = String.valueOf(totalNetMass); data[columnHeadersList.indexOf(UNITS)] = String.valueOf(supplementaryUnit); data[columnHeadersList.indexOf(NAT_TRANS)] = String.valueOf(natTrans.getValue()); data[columnHeadersList.indexOf(TRANSP)] = String.valueOf(modeOfTransport.getValue()); data[columnHeadersList.indexOf(DEPT)] = dept; data[columnHeadersList.indexOf(COUNTRY_ORIG)] = countryOrigCode; data[columnHeadersList.indexOf(ACQUIRER)] = taxNbr; data[columnHeadersList.indexOf(PRODUCT_CODE)] = productCode; data[columnHeadersList.indexOf(PRODUCT_NAME)] = productName; data[columnHeadersList.indexOf(PARTNER_SEQ)] = partnerSeq; data[columnHeadersList.indexOf(INVOICE)] = invoiceId; return data; } @Override protected String exportToPDF() throws AxelorException { return ReportFactory.createReport(IReport.DECLARATION_OF_EXCHANGES_OF_GOODS, getTitle()) .addParam("DeclarationOfExchangesId", declarationOfExchanges.getId()) .addParam("UserId", AuthUtils.getUser().getId()) .addParam("Locale", ReportSettings.getPrintingLocale()) .addFormat(declarationOfExchanges.getFormatSelect()) .toAttach(declarationOfExchanges) .generate() .getFileLink(); } }
//Namespace package com.katujo.web.utils; //Java imports import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //Scannotation imports import org.scannotation.AnnotationDB; import org.scannotation.WarUrlFinder; //Google imports import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * The router filter that routes incoming request to the annotated classes using the package and * the method name as the path. * @author Johan Hertz * */ public class RouterFilter implements Filter { //The map to hold the routes <String=path, Route> private final Map<String, Route> routes = new ConcurrentHashMap<String, Route>(); //The map/set to hold the path where to mask request data on error (String=path, IGNORE) private final Map<String, Object> maskOnError = new ConcurrentHashMap<String, Object>(); //The no parameters object private static final Object[] NO_PARAMETERS = new Object[]{}; //The JSON content type private static final String JSON_CONTENT_TYPE = "application/json"; //The character encoding to use when sending back JSON data private static final String JSON_CHARACTER_ENCODING = "ISO-8859-1"; //The binary array content type private static final String BINARY_CONTENT_TYPE = "application/octet-stream"; //The thread local field to hold the HTTP request data private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<>(); //The thread local field to hold the HTTP response data private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<>(); /* * Init the filter. * (non-Javadoc) * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ @Override public void init(FilterConfig config) throws ServletException { //Try to init the filter try { //Get the path where to mask request data for(String path : maskRequestDataOnError(config)) maskOnError.put(path, NO_PARAMETERS); //Get the scanned classes Set<String> classesScanned = scanRoutes(config); //Get the web.xml classes Set<String> classesWebXml = webXmlRoutes(config); //Create the classes Set<String> classes = new HashSet<String>(classesScanned.size() + classesWebXml.size()); //Add the classes classes.addAll(classesScanned); classes.addAll(classesWebXml); //Get the base package //TODO: Remove legacy scan property String basePackage = config.getInitParameter("base-package") != null ? config.getInitParameter("base-package") : config.getInitParameter("scan"); //Set the default base package to empty string basePackage = basePackage != null ? basePackage : ""; //Get the extension that will be added to the end of every path String extension = config.getInitParameter("extension"); //Get the print paths flag boolean printPaths = "true".equals(config.getInitParameter("print-paths")); //Create the route objects for(String clazz : classes) { //Get the routes class Class<?> routeClass = Class.forName(clazz); //Get the package name String routePackage = routeClass.getPackage().getName(); //Check if the package match the base package if(!routePackage.startsWith(basePackage)) continue; //Create an instance of the route Object instance = routeClass.getConstructor(new Class[] {}).newInstance(new Object[]{}); //Create the base path String base = routePackage.substring(basePackage.length()).replace('.', '/') + "/"; //Add the controller methods for(Method method : routeClass.getMethods()) { //Only add public methods if(!"public".equals(Modifier.toString(method.getModifiers()))) continue; //Only add methods that are declared in route class if(method.getDeclaringClass() != routeClass) continue; //Create the parameter type int type = Route.NO_PARAMETER; //If the parameters length is 1 only allow JSON parameters and primitives if(method.getParameterTypes().length == 1) { if(method.getParameterTypes()[0] == JsonObject.class) type = Route.JSON_OBJECT; else if(method.getParameterTypes()[0] == JsonArray.class) type = Route.JSON_ARRAY; else if(method.getParameterTypes()[0] == JsonElement.class) type = Route.JSON_ELEMENT; else if(method.getParameterTypes()[0] == boolean.class || method.getParameterTypes()[0] == Boolean.class) type = Route.PRIMITIVE_BOOLEAN; else if(method.getParameterTypes()[0] == double.class || method.getParameterTypes()[0] == Double.class) type = Route.PRIMITIVE_DOUBLE; else if(method.getParameterTypes()[0] == int.class || method.getParameterTypes()[0] == Integer.class) type = Route.PRIMITIVE_INT; else if(method.getParameterTypes()[0] == long.class || method.getParameterTypes()[0] == Long.class) type = Route.PRIMITIVE_LONG; else if(method.getParameterTypes()[0] == String.class) type = Route.PRIMITIVE_STRING; else continue; } //If the parameter length is 2 only allow HttpServletRequest and HttpServletResponse else if(method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == HttpServletRequest.class && method.getParameterTypes()[1] == HttpServletResponse.class) type = Route.REQUEST_RESPONSE; //Ignore any other method that has parameter else if(method.getParameterTypes().length != 0) continue; //Create the path String path = base + method.getName() + extension; //Check that the path has not already been added unique if(routes.containsKey(path)) throw new Exception("Path " + path + " is not unique"); //Add the path routes.put(path, new Route(instance, method, type)); } } //Create the out put list List<String> list = new ArrayList<>(); //Print the paths setup for(String path : routes.keySet()) list.add(routes.get(path).instance.getClass().getSimpleName() + "(" + (routes.get(path).method.getName() + "): " + path)); //Sort the list Collections.sort(list); //Print the list for(String item : list) if(printPaths) System.out.println(item); } //Failed catch(Exception ex) { throw new ServletException("Failed to init RouterFilter", ex); } } /* * Run the filter. * (non-Javadoc) * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { //Try to run the filter try { //Cast the request and response HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; //Set the thread local fields RouterFilter.request.set(request); RouterFilter.response.set(response); //Invoke the route Object data = invoke(request, response); //Send the data as the response send(request, response, data); } //Failed catch(Exception ex) { throw new ServletException("Failed to route request", ex); } //Clean up finally { RouterFilter.request.set(null); RouterFilter.response.set(null); } } /** * Invoke a route. * @param request * @param response * @return * @throws Exception */ private Object invoke(HttpServletRequest request, HttpServletResponse response) throws Exception { //Create fields that will be used in the exception message String path = null; JsonElement requestData = null; //Try to invoke route try { //Get the path path = request.getServletPath(); //Get the route Route route = routes.get(path); //Check if there is a route for the path if(route == null) throw new Exception("Could not find a route for path " + path); //Create the return data Object returnData = null; //Get the request data requestData = JsonFilter.getJson(); //Invoke the method on the instance with the no parameters if(route.parameterType == Route.NO_PARAMETER) returnData = route.method.invoke(route.instance, NO_PARAMETERS); //Invoke the method on the instance with a JSON object parameter else if(route.parameterType == Route.JSON_OBJECT) returnData = route.method.invoke(route.instance, requestData == null ? requestData : requestData.getAsJsonObject()); //Invoke the method on the instance with a JSON array parameter else if(route.parameterType == Route.JSON_ARRAY) returnData = route.method.invoke(route.instance, requestData == null ? requestData : requestData.getAsJsonArray()); //Invoke the method on the instance with a JSON element parameter else if(route.parameterType == Route.JSON_ELEMENT) returnData = route.method.invoke(route.instance, requestData); //Invoke the method on the instance with a boolean as the parameter else if(route.parameterType == Route.PRIMITIVE_BOOLEAN) returnData = route.method.invoke(route.instance, requestData.getAsBoolean()); //Invoke the method on the instance with a double as the parameter else if(route.parameterType == Route.PRIMITIVE_DOUBLE) returnData = route.method.invoke(route.instance, requestData.getAsDouble()); //Invoke the method on the instance with a integer as the parameter else if(route.parameterType == Route.PRIMITIVE_INT) returnData = route.method.invoke(route.instance, requestData.getAsInt()); //Invoke the method on the instance with a long as the parameter else if(route.parameterType == Route.PRIMITIVE_LONG) returnData = route.method.invoke(route.instance, requestData.getAsLong()); //Invoke the method on the instance with a string as the parameter else if(route.parameterType == Route.PRIMITIVE_STRING) returnData = route.method.invoke(route.instance, requestData.getAsString()); //Invoke the method on the instance with the request and response parameters else if(route.parameterType == Route.REQUEST_RESPONSE) returnData = route.method.invoke(route.instance, new Object[]{request, response}); //The parameter type has not been implemented yet else throw new Exception("The parameter type " + route.parameterType + " has not been implemented"); //Return the return data return returnData; } //Failed catch(Exception ex) { //Create the message String message = "Failed to invoke route for path " + path; //Check if masked if(maskOnError.containsKey(path)) message += "\n\tRequest Data: **MASKED**"; //Check if request data is set else if(requestData == null) message += " (request data not set)"; //Add the request data to the exception else message += "\n\tRequest Data: " + requestData.toString(); //Throw the exception throw new Exception(message, ex); } } /** * Send the return data as the response. * @param request * @param response * @param data * @throws Exception */ private void send(HttpServletRequest request, HttpServletResponse response, Object data) throws Exception { //Try to send the data try { //Don't do anything if the response data is not set if(data == null) ; //Send the response back as JSON data else if(data instanceof JsonElement) { //Set the response type response.setContentType(JSON_CONTENT_TYPE); response.setCharacterEncoding(JSON_CHARACTER_ENCODING); //Print the JSON to the output stream response.getOutputStream().print(data.toString()); } //Send the response back as a JSON string primitive else if(data instanceof String) { //Set the response type response.setContentType(JSON_CONTENT_TYPE); response.setCharacterEncoding(JSON_CHARACTER_ENCODING); //Create the primitive JsonPrimitive primitive = new JsonPrimitive((String) data); //Print the JSON to the output stream response.getOutputStream().print(primitive.toString()); } //Send the response back as a JSON number primitive else if(data instanceof Double || data instanceof Long || data instanceof Integer || data instanceof Number) { //Set the response type response.setContentType(JSON_CONTENT_TYPE); response.setCharacterEncoding(JSON_CHARACTER_ENCODING); //Create the primitive JsonPrimitive primitive = new JsonPrimitive((Number) data); //Print the JSON to the output stream response.getOutputStream().print(primitive.toString()); } //Send the response back as a JSON number primitive that can be cast as a date else if(data instanceof Date) { //Set the response type response.setContentType(JSON_CONTENT_TYPE); response.setCharacterEncoding(JSON_CHARACTER_ENCODING); //Create the primitive JsonPrimitive primitive = new JsonPrimitive(((Date) data).getTime()); //Print the JSON to the output stream response.getOutputStream().print(primitive.toString()); } //Send the response back as a JSON boolean primitive else if(data instanceof Boolean) { //Set the response type response.setContentType(JSON_CONTENT_TYPE); response.setCharacterEncoding(JSON_CHARACTER_ENCODING); //Create the primitive JsonPrimitive primitive = new JsonPrimitive((boolean) data); //Print the JSON to the output stream response.getOutputStream().print(primitive.toString()); } //Send the response back as binary data else if(data instanceof byte[]) { //Set the response type response.setContentType(BINARY_CONTENT_TYPE); //Write the data response.getOutputStream().write((byte[]) data); } //The data type returned by the route is unrecognised else throw new Exception("Unrecognised route return type " + data.getClass().getCanonicalName()); } //Failed catch(Exception ex) { throw new Exception("Failed to send data response", ex); } } /* * Destroy the filter. * (non-Javadoc) * @see javax.servlet.Filter#destroy() */ @Override public void destroy() {} /** * Get the request (for the current request thread). * @return */ public static HttpServletRequest getRequest() { return request.get(); } /** * Get the response (for the current request thread). * @return */ public static HttpServletResponse getResponse() { return response.get(); } /** * Scan for the routes. * @param config * @return * @throws Exception */ private static Set<String> scanRoutes(FilterConfig config) throws Exception { //Try to scan for routes try { //Get the URL URL url = WarUrlFinder.findWebInfClassesPath(config.getServletContext()); //Could not find the URL if(url == null) return new HashSet<String>(); //Create the annotation database AnnotationDB database = new AnnotationDB(); //Scan the URL database.scanArchives(url); //Get the classes marked with the controller annotation Set<String> classes = database.getAnnotationIndex().get(com.katujo.web.utils.Route.class.getCanonicalName()); //Return empty if not set if(classes == null) return new HashSet<String>(); //Return the classes return classes; } //Failed catch(Exception ex) { throw new Exception("Failed to scan for routes", ex); } } /** * Read the routes from the web.xml file. * @param config * @return * @throws Exception */ private static Set<String> webXmlRoutes(FilterConfig config) throws Exception { //Try to read the routes from the web.xml file try { //Get the routes String routes = config.getInitParameter("routes"); //Check if routes is set if(routes == null) return new HashSet<String>(); //Split the routes String[] split = routes.split(";"); //Create the set Set<String> classes = new HashSet<String>(); //Add the classes for(String item : split) if(!item.trim().equals("")) classes.add(item.trim()); //Return the set return classes; } //Failed catch(Exception ex) { throw new Exception("Failed to read web.xml routes", ex); } } /** * Read the routes from the web.xml file. * @param config * @return * @throws Exception */ private static Set<String> maskRequestDataOnError(FilterConfig config) throws Exception { //Try to read the routes from the web.xml file try { //Get the routes String paths = config.getInitParameter("mask-request-data-on-error"); //Check if routes is set if(paths == null) return new HashSet<String>(); //Split the routes String[] split = paths.split(";"); //Create the set of paths Set<String> set = new HashSet<String>(); //Add the classes for(String item : split) if(!item.trim().equals("")) set.add(item.trim()); //Return the set return set; } //Failed catch(Exception ex) { throw new Exception("Failed to read web.xml mask-request-data-on-error", ex); } } /* * Class to hold a route. */ private class Route { //Fields public Object instance; public Method method; public int parameterType; //Parameter types public static final int NO_PARAMETER = 1; public static final int JSON_ELEMENT = 2; public static final int JSON_ARRAY = 3; public static final int JSON_OBJECT = 4; public static final int PRIMITIVE_BOOLEAN = 5; public static final int PRIMITIVE_DOUBLE = 6; public static final int PRIMITIVE_INT = 7; public static final int PRIMITIVE_LONG = 8; public static final int PRIMITIVE_STRING = 9; public static final int REQUEST_RESPONSE = 10; /** * Create the object. * @param instance * @param method */ public Route(Object instance, Method method, int parameterType) { this.instance = instance; this.method = method; this.parameterType = parameterType; } } }
// HttpResponse.java package ed.net.httpserver; import java.io.*; import java.net.*; import java.util.*; import java.text.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; import javax.servlet.*; import javax.servlet.http.*; import ed.io.*; import ed.js.*; import ed.js.func.*; import ed.js.engine.*; import ed.log.*; import ed.util.*; import ed.net.*; import ed.appserver.*; /** * Represents response to an HTTP request. On each request, the 10gen app server defines * the variable 'response' which is of this type. * @expose * @docmodule system.HTTP.response */ public class HttpResponse extends JSObjectBase implements HttpServletResponse { static final boolean USE_POOL = true; static final String DEFAULT_CHARSET = "utf-8"; static final long MIN_GZIP_SIZE = 1000; static final Set<String> GZIP_MIME_TYPES; static { Set<String> s = new HashSet<String>(); s.add( "application/x-javascript" ); s.add( "text/css" ); s.add( "text/html" ); s.add( "text/plain" ); GZIP_MIME_TYPES = Collections.unmodifiableSet( s ); } public static final DateFormat HeaderTimeFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); public static final String SERVER_HEADERS; static { HeaderTimeFormat.setTimeZone( TimeZone.getTimeZone("GMT") ); String hostname = "unknown"; try { hostname = InetAddress.getLocalHost().getHostName(); } catch ( Throwable t ){ t.printStackTrace(); } SERVER_HEADERS = "Server: ED\r\nX-svr: " + hostname + "\r\n"; } /** * Create a response to a given request. */ HttpResponse( HttpRequest request ){ _request = request; _handler = _request._handler; setContentType( "text/html;charset=" + getContentEncoding() ); setDateHeader( "Date" , System.currentTimeMillis() ); set( "prototype" , _prototype ); } public void setResponseCode( int rc ){ if ( _sentHeader ) throw new RuntimeException( "already sent header : " + hashCode() ); _responseCode = rc; } public void setStatus( int rc ){ setResponseCode( rc ); } public void setStatusCode( int rc ){ setResponseCode( rc ); } /** * @deprecated */ public void setStatus( int rc , String name ){ setResponseCode( rc ); } public void sendError( int rc ){ setResponseCode( rc ); } public void sendError( int rc , String msg ){ setResponseCode( rc ); } /** * Get the HTTP response code for this response. * @return this response's HTTP status code */ public int getResponseCode(){ return _responseCode; } /** * Add an additional cookie to be sent in this response. * All cookies will be sent to the browser, but browsers typically only * keep the last cookie with a given name. * @param name cookie name * @param value cookie value * @param maxAge * > 0 = seconds into the future * 0 = remove * < 0 = session */ public void addCookie( String name , String value , int maxAge ){ Cookie c = new Cookie( name , value ); c.setPath( "/" ); c.setMaxAge( maxAge ); _cookies.add( c ); } /** * Add a cookie to be sent in this response. This sends a session cookie * (which is typically deleted when the browser is closed). * @param name cookie name * @param value cookie value */ public void addCookie( String name , String value ){ addCookie( name , value , -1 ); } /** * API copied from appjet * Set a cookie in the response. * @param cookieObject * fields * name (required): The name of the cookie * value (required): The value of the cookie. (Note: this value will be escaped). * expires (optional): If an integer, means number of days until it expires; if a Date object, means exact date on which to expire. * domain (optional): The cookie domain * path (optional): To restrict the cookie to a specific path. * secure (optional): Whether this cookie should only be sent securely. * response.setCookie({ name: "SessionID", value: "25", secure: true, expires: 14 // 14 days }); */ public void setCookie( JSObject o ){ addCookie( objectToCookie( o ) ); } public static Cookie objectToCookie( JSObject o ){ if ( o.get( "name" ) == null ) throw new IllegalArgumentException( "name is required" ); if ( o.get( "value" ) == null ) throw new IllegalArgumentException( "value is required" ); Cookie c = new Cookie( o.get( "name" ).toString() , o.get( "value" ).toString() ); { Object expires = o.get( "expires" ); if ( expires instanceof Number ) c.setMaxAge( (int)( ((Number)expires).doubleValue() * 86400 ) ); else if ( expires instanceof Date ) c.setMaxAge( (int)( ( ((Date)expires).getTime() - System.currentTimeMillis() ) / 1000 ) ); else if ( expires instanceof JSDate ) c.setMaxAge( (int)( ( ((JSDate)expires).getTime() - System.currentTimeMillis() ) / 1000 ) ); } if ( o.get( "domain" ) != null ) c.setDomain( o.get( "domain" ).toString() ); if ( o.get( "path" ) != null ) c.setPath( o.get( "path" ).toString() ); else c.setPath( "/" ); if ( JSInternalFunctions.JS_evalToBool( o.get( "secure" ) ) ) c.setSecure( true ); return c; } /** * Equivalent to "addCookie( name , null , 0 )". Tells the browser * that the cookie with this name is already expired. * @param name cookie name */ public void removeCookie( String name ){ addCookie( name , "none" , 0 ); } public void deleteCookie( String name ){ removeCookie( name ); } public void addCookie( Cookie cookie ){ _cookies.add( cookie ); } /** * Set a cache time for this response. * Sets the Cache-Control and Expires headers * @param seconds the number of seconds that this response should be cached */ public void setCacheTime( int seconds ){ setHeader("Cache-Control" , "max-age=" + seconds ); setDateHeader( "Expires" , System.currentTimeMillis() + ( 1000 * seconds ) ); } public void setCacheable( boolean cacheable ){ if ( cacheable ){ setCacheTime( 3600 ); } else { removeHeader( "Expires" ); setHeader( "Cache-Control" , "no-cache" ); } } public void setCacheable( Object o ){ setCacheable( JSInternalFunctions.JS_evalToBool( o ) ); } /** * Set a header as a date. * * Formats a time, passed as an integer number of milliseconds, as a date, * and sets a header with this date. * * @param n the name of the header * @param t the value of the header, as a number of milliseconds */ public void setDateHeader( String n , long t ){ synchronized( HeaderTimeFormat ) { setHeader( n , HeaderTimeFormat.format( new Date(t) ) ); } } public void addDateHeader( String n , long t ){ synchronized( HeaderTimeFormat ) { addHeader( n , HeaderTimeFormat.format( new Date(t) ) ); } } public Locale getLocale(){ throw new RuntimeException( "getLocal not implemented yet" ); } public void setLocale( Locale l ){ throw new RuntimeException( "setLocale not implemented yet" ); } public void reset(){ throw new RuntimeException( "reset not allowed" ); } public void resetBuffer(){ throw new RuntimeException( "resetBuffer not allowed" ); } public void flushBuffer() throws IOException { flush(); } public int getBufferSize(){ return 0; } public void setBufferSize( int size ){ // we ignore this } public boolean isCommitted(){ return _cleaned || _done || _sentHeader; } public void setContentType( String ct ){ setHeader( "Content-Type" , ct ); } public String getContentType(){ return getHeader( "Content-Type" ); } public String getContentMimeType(){ String ct = getContentType(); if ( ct == null ) return null; int idx = ct.indexOf( ";" ); if ( idx < 0 ) return ct.trim(); return ct.substring( 0 , idx ).trim(); } public void clearHeaders(){ _headers.clear(); _useDefaultHeaders = false; } /** * Set a header in the response. * Overwrites previous headers with the same name * @param n the name of the header to set * @param v the value of the header to set, as a string */ public void setHeader( String n , String v ){ List<String> lst = _getHeaderList( n , true ); lst.clear(); lst.add( v ); } public void addHeader( String n , String v ){ List<String> lst = _getHeaderList( n , true ); if ( isSingleOutputHeader( n ) ) lst.clear(); lst.add( v ); } public void addIntHeader( String n , int v ){ List<String> lst = _getHeaderList( n , true ); lst.add( String.valueOf( v ) ); } public void setContentLength( long length ){ setHeader( "Content-Length" , String.valueOf( length ) ); } public void setContentLength( int length ){ setHeader( "Content-Length" , String.valueOf( length ) ); } public int getContentLength(){ return getIntHeader( "Content-Length" , -1 ); } public void setIntHeader( String n , int v ){ List<String> lst = _getHeaderList( n , true ); lst.clear(); lst.add( String.valueOf( v ) ); } public boolean containsHeader( String n ){ List<String> lst = _getHeaderList( n , false ); return lst != null && lst.size() > 0; } public String getHeader( String n ){ List<String> lst = _getHeaderList( n , false ); if ( lst == null || lst.size() == 0 ) return null; return lst.get( 0 ); } public int getIntHeader( String h , int def ){ return StringParseUtil.parseInt( getHeader( h ) , def ); } private List<String> _getHeaderList( String n , boolean create ){ List<String> lst = _headers.get( n ); if ( lst != null || ! create ) return lst; lst = new LinkedList<String>(); _headers.put( n , lst ); return lst; } public void removeHeader( String name ){ _headers.remove( name ); } /** * @unexpose */ void cleanup(){ if ( _cleaned ) return; if ( _doneHooks != null ){ for ( Pair<Scope,JSFunction> p : _doneHooks ){ try { p.first.makeThreadLocal(); p.second.call( p.first ); } catch ( Throwable t ){ Logger l = Logger.getLogger( "HttpResponse" ); if ( p.first.get( "log" ) instanceof Logger ) l = (Logger)p.first.get( "log" ); l.error( "error running done hook" , t ); } finally { p.first.clearThreadLocal(); } } } if ( _appRequest != null && _appRequest.getScope() != null ) _appRequest.getScope().kill(); _handler._done = ! keepAlive(); _cleaned = true; if ( _myStringContent != null ){ for ( ByteBuffer bb : _myStringContent ){ if ( USE_POOL ) _bbPool.done( bb ); } _myStringContent.clear(); _myStringContent = null; } if ( _writer != null ){ _charBufPool.done( _writer._cur ); _writer._cur = null; _writer = null; } if ( _jsfile != null ){ if ( _jsfile.available() > 0 ) _jsfile.cancelled(); _jsfile = null; } } /** * @unexpose */ public boolean done() throws IOException { if ( _cleaned ) return true; _done = true; if ( _doneTime <= 0 ) _doneTime = System.currentTimeMillis(); if ( ! _sentHeader ) _gzip = useGZIP(); boolean f = flush(); if ( f ) cleanup(); return f; } public String encodeRedirectURL( String loc ){ return loc; } public String encodeRedirectUrl( String loc ){ return loc; } public String encodeUrl( String loc ){ return loc; } public String encodeURL( String loc ){ return loc; } public void redirect( String loc ){ sendRedirectTemporary( loc ); } /** * Send a permanent (301) redirect to the given location. * Equivalent to calling setResponseCode( 301 ) followed by * setHeader( "Location" , loc ). * @param loc the location to redirect to */ public void sendRedirectPermanent(String loc){ setResponseCode( 301 ); setHeader("Location", loc); } /** * Send a temporary (302) redirect to the given location. * Equivalent to calling setResponseCode( 302 ) followed by * setHeader( "Location" , loc ). * @param loc the location to redirect to */ public void sendRedirectTemporary(String loc){ setResponseCode( 302 ); setHeader("Location", loc); } public void sendRedirect( String loc ){ sendRedirectTemporary( loc ); } private boolean flush() throws IOException { return _flush(); } private boolean _flush() throws IOException { if ( _cleaned ) throw new RuntimeException( "already cleaned" ); if ( _numDataThings() > 1 ) throw new RuntimeException( "too much data" ); if ( ! _sentHeader ){ final String header = _genHeader(); final byte[] bytes = header.getBytes(); final ByteBuffer headOut = ByteBuffer.wrap( bytes ); _handler.write( headOut ); _keepAlive = keepAlive(); _sentHeader = true; } if ( _writer != null ){ _writer._push(); _charBufPool.done( _writer._cur ); _writer._cur = null; } if ( ! _request.isHeadRequest() ){ if ( _file != null ){ if ( _fileChannel == null ){ try { _fileChannel = (new FileInputStream(_file)).getChannel(); } catch( IOException ioe ){ throw new RuntimeException( "can't get file : " + _file , ioe ); } } try { //_dataSent += _fileChannel.transferTo( _dataSent , Long.MAX_VALUE , _handler.getChannel() ); _dataSent += _handler.transerFile( _fileChannel , _dataSent , Long.MAX_VALUE ); } catch ( IOException ioe ){ if ( ioe.toString().indexOf( "Resource temporarily unavailable" ) < 0 ) throw ioe; } if ( _dataSent < _file.length() ){ if ( HttpServer.D ) System.out.println( "only sent : " + _dataSent ); _handler._inFork = false; _handler.registerForWrites(); return false; } } if ( _stringContent != null ){ for ( ; _stringContentSent < _stringContent.size() ; _stringContentSent++ ){ ByteBuffer bb = _stringContent.get( _stringContentSent ); int thisTime = _handler.write( bb ); _stringContentPos += thisTime; _dataSent += thisTime; if ( _stringContentPos < bb.limit() ){ if ( HttpServer.D ) System.out.println( "only wrote " + _stringContentPos + " out of " + bb ); _handler._inFork = false; _handler.registerForWrites(); return false; } _stringContentPos = 0; } } if ( _jsfile != null ){ if ( ! _jsfile.write( _handler ) ){ _dataSent = _jsfile.bytesWritten(); _handler._inFork = false; if ( _jsfile.pause() ) _handler.pause(); else _handler.registerForWrites(); return false; } _dataSent = _jsfile.bytesWritten(); } } cleanup(); if ( keepAlive() && ! _handler.hasData() ) _handler.registerForReads(); else _handler.registerForWrites(); return true; } long dataSent(){ return _dataSent; } void socketClosing(){ if ( _cleaned ) return; // uh-oh cleanup(); } private String _genHeader() throws IOException { StringBuilder buf = _headerBufferPool.get(); _genHeader( buf ); String header = buf.toString(); _headerBufferPool.done( buf ); return header; } private Appendable _genHeader( Appendable a ) throws IOException { // first line a.append( "HTTP/1.1 " ); { String rc = String.valueOf( _responseCode ); a.append( rc ).append( " " ); Object msg = _responseMessages.get( rc ); if ( msg == null ) a.append( "OK" ); else a.append( msg.toString() ); a.append( "\n" ); } if ( _useDefaultHeaders ) a.append( SERVER_HEADERS ); // headers if ( _headers != null ){ List<String> headers = new ArrayList<String>( _headers.keySet() ); Collections.sort( headers ); for ( int i=headers.size()-1; i>=0; i final String h = headers.get( i ); List<String> values = _headers.get( h ); for ( int j=0; j<values.size(); j++ ){ a.append( h ); a.append( ": " ); a.append( values.get( j ) ); a.append( "\r\n" ); } } } // cookies for ( Cookie c : _cookies ){ a.append( "Set-Cookie: " ); a.append( c.getName() ).append( "=" ).append( c.getValue() ).append( ";" ); if ( c.getPath() != null ) a.append( " Path=" ).append( c.getPath() ).append( ";" ); if ( c.getDomain() != null ) a.append( " Domain=" ).append( c.getDomain() ).append( ";" ); String expires = CookieUtil.getExpires( c ); if ( expires != null ) a.append( " Expires=" ).append( expires ).append( "; " ); a.append( "\r\n" ); } if ( keepAlive() ) a.append( "Connection: keep-alive\r\n" ); else a.append( "Connection: close\r\n" ); if ( _writer != null ) _writer._push(); if ( _headers.get( "Content-Length") == null ){ long cl = dataSize(); if ( cl >= 0 ){ a.append( "Content-Length: " ).append( String.valueOf( cl ) ).append( "\r\n" ); } } // empty line a.append( "\r\n" ); return a; } /** * @return size or -1 if i don't know */ long dataSize(){ if ( _headers.containsKey( "Content-Length" ) ) return getContentLength(); if ( _stringContent != null ){ int cl = 0; for ( ByteBuffer buf : _stringContent ) cl += buf.limit(); return cl; } if ( _numDataThings() == 0 ) return 0; return -1; } /** * Tries to compute the size of this entire response * Adds the size of the headers plus the content-length know about so far * Slightly expensive. * @return the size of the headers */ public int totalSize(){ final int size[] = new int[]{ 0 }; Appendable a = new Appendable(){ public Appendable append( char c ){ size[0] += 1; return this; } public Appendable append( CharSequence s ){ if ( s == null ) return this; return append( s , 0 , s.length() ); } public Appendable append( CharSequence s , int start , int end ){ size[0] += ( end - start ); if ( _count == 1 ){ int add = StringParseUtil.parseInt( s.toString() , 0 ); size[0] += add; } _count if ( "Content-Length".equalsIgnoreCase( s.toString() ) ) _count = 2; if ( "Content-Length: ".equalsIgnoreCase( s.toString() ) ) _count = 1; return this; } int _count = 0; }; try { _genHeader( a ); } catch ( IOException ioe ){ throw new RuntimeException( "should be impossible" , ioe ); } return size[0]; } /** * Return this response, formatted as a string: HTTP response, headers, * cookies. */ public String toString(){ try { return _genHeader(); } catch ( Exception e ){ throw new RuntimeException( e ); } } public void write( String s ){ getJxpWriter().print( s ); } /** * @unexpose */ public JxpWriter getJxpWriter(){ if ( _writer == null ){ if ( _cleaned ) throw new RuntimeException( "already cleaned" ); _writer = new MyJxpWriter(); } return _writer; } public PrintWriter getWriter(){ if ( _printWriter == null ){ final JxpWriter jxpWriter = getJxpWriter(); _printWriter = new PrintWriter( new Writer(){ public void close(){ } public void flush(){ } public void write(char[] cbuf, int off, int len){ jxpWriter.print( new String( cbuf , off , len ) ); } } , true ); } return _printWriter; } public ServletOutputStream getOutputStream(){ if ( _outputStream == null ){ final JxpWriter jxpWriter = getJxpWriter(); _outputStream = new ServletOutputStream(){ public void write( int b ){ jxpWriter.write( b ); } }; } return _outputStream; } /** * @unexpose */ public void setData( ByteBuffer bb ){ _stringContent = new LinkedList<ByteBuffer>(); _stringContent.add( bb ); } /** * @unexpose */ public boolean keepAlive(){ if ( _sentHeader ){ return _keepAlive; } if ( ! _handler.allowKeepAlive() ) return false; if ( ! _request.keepAlive() ){ return false; } if ( _headers.get( "Content-Length" ) != null ){ return true; } if ( _stringContent != null ){ // TODO: chunkinga return _done; } return false; } /** * @unexpose */ public String getContentEncoding(){ return DEFAULT_CHARSET; } public void setCharacterEncoding( String encoding ){ throw new RuntimeException( "setCharacterEncoding not supported" ); } public String getCharacterEncoding(){ return getContentEncoding(); } /** * Sends a file to the browser. * @param f a file to send */ public void sendFile( File f ){ if ( ! f.exists() ) throw new IllegalArgumentException( "file doesn't exist" ); _file = f; setContentType( MimeTypes.get( f ) ); setContentLength( f.length() ); _stringContent = null; } /** * Sends a file to the browser, including (for database-stored files) * sending a sensible Content-Disposition. * @param f a file to send */ public void sendFile( JSFile f ){ if ( f instanceof JSLocalFile ){ sendFile( ((JSLocalFile)f).getRealFile() ); return; } if ( f.getFileName() != null && getHeader( "Content-Disposition" ) == null ){ setHeader( "Content-Disposition" , f.getContentDisposition() + "; filename=\"" + f.getFileName() + "\"" ); } long length = f.getLength(); sendFile( f.sender() ); long range[] = _request.getRange(); if ( range != null && ( range[0] > 0 || range[1] < length ) ){ if ( range[1] > length ) range[1] = length; try { _jsfile.skip( range[0] ); } catch ( IOException ioe ){ throw new RuntimeException( "can't skip " , ioe ); } _jsfile.maxPosition( range[1] + 1 ); setResponseCode( 206 ); setHeader( "Content-Range" , "bytes " + range[0] + "-" + range[1] + "/" + length ); setContentLength( 1 + range[1] - range[0] ); System.out.println( "got range " + range[0] + " -> " + range[1] ); return; } setContentLength( f.getLength() ); setContentType( f.getContentType() ); } public void sendFile( JSFile.Sender sender ){ _jsfile = sender; _stringContent = null; } private int _numDataThings(){ int num = 0; if ( _stringContent != null ) num++; if ( _file != null ) num++; if ( _jsfile != null ) num++; return num; } private boolean _hasData(){ return _numDataThings() > 0; } private void _checkNoContent(){ if ( _hasData() ) throw new RuntimeException( "already have data set" ); } private void _checkContent(){ if ( ! _hasData() ) throw new RuntimeException( "no data set" ); } /** * Adds a "hook" function to be called after this response has been sent. * @param f a function */ public void addDoneHook( Scope s , JSFunction f ){ if ( _doneHooks == null ) _doneHooks = new ArrayList<Pair<Scope,JSFunction>>(); _doneHooks.add( new Pair<Scope,JSFunction>( s , f ) ); } /** * @unexpose */ public void setAppRequest( AppRequest ar ){ _appRequest = ar; } public long handleTime(){ long end = _doneTime; if ( end <= 0 ) end = System.currentTimeMillis(); return end - _request._startTime; } public int hashCode( IdentitySet seen ){ return System.identityHashCode(this); } boolean useGZIP(){ if ( ! _done ) return false; if ( ! _request.gzip() ) return false; if ( ! GZIP_MIME_TYPES.contains( getContentMimeType() ) ) return false; if ( _stringContent != null && _stringContent.size() > 0 && _stringContentSent == 0 && _stringContentPos == 0 ){ if ( _writer != null ){ _writer._push(); _charBufPool.done( _writer._cur ); _writer = null; } if ( _stringContent.get(0).limit() < MIN_GZIP_SIZE ) return false; setHeader("Content-Encoding" , "gzip" ); setHeader("Vary" , "Accept-Encoding" ); List<ByteBuffer> zipped = ZipUtil.gzip( _stringContent , _bbPool ); for ( ByteBuffer buf : _stringContent ) _bbPool.done( buf ); _stringContent = zipped; _myStringContent = zipped; long length = 0; for ( ByteBuffer buf : _stringContent ){ length += buf.remaining(); } setContentLength( length ); return true; } return false; } final HttpRequest _request; final HttpServer.HttpSocketHandler _handler; // header int _responseCode = 200; Map<String,List<String>> _headers = new StringMap<List<String>>(); boolean _useDefaultHeaders = true; List<Cookie> _cookies = new ArrayList<Cookie>(); boolean _sentHeader = false; private boolean _keepAlive = false; boolean _gzip = false; // data List<ByteBuffer> _stringContent = null; private List<ByteBuffer> _myStringContent = null; // tihs is the real one int _stringContentSent = 0; int _stringContentPos = 0; File _file; FileChannel _fileChannel; long _dataSent = 0; boolean _done = false; long _doneTime = -1; boolean _cleaned = false; MyJxpWriter _writer = null; PrintWriter _printWriter; ServletOutputStream _outputStream; JSFile.Sender _jsfile; private AppRequest _appRequest; private List<Pair<Scope,JSFunction>> _doneHooks; class MyJxpWriter implements JxpWriter { MyJxpWriter(){ _checkNoContent(); _myStringContent = new LinkedList<ByteBuffer>(); _stringContent = _myStringContent; _cur = _charBufPool.get(); _resetBuf(); } public Appendable append(char c){ print( String.valueOf( c ) ); return this; } public Appendable append(CharSequence csq){ print( csq.toString() ); return this; } public Appendable append(CharSequence csq, int start, int end){ print( csq.subSequence( start , end ).toString() ); return this; } public void write( int b ){ if ( _done ) throw new RuntimeException( "already done" ); if ( b < Byte.MIN_VALUE || b > Byte.MAX_VALUE ) throw new RuntimeException( "what?" ); if ( _cur.remaining() == 0 ) _push(); if ( _mode == OutputMode.STRING ){ _push(); _mode = OutputMode.BYTES; _push(); } byte real = (byte)( b & 0xFF ); _raw.put( real ); } public JxpWriter print( int i ){ return print( String.valueOf( i ) ); } public JxpWriter print( double d ){ return print( String.valueOf( d ) ); } public JxpWriter print( long l ){ return print( String.valueOf( l ) ); } public JxpWriter print( boolean b ){ return print( String.valueOf( b ) ); } public boolean closed(){ return _done; } public JxpWriter print( String s ){ if ( _done ) throw new RuntimeException( "already done" ); if ( _mode == OutputMode.BYTES ){ _push(); _mode = OutputMode.STRING; } if ( s == null ) s = "null"; if ( s.length() > MAX_STRING_SIZE ){ for ( int i=0; i<s.length(); ){ String temp = s.substring( i , Math.min( i + MAX_STRING_SIZE , s.length() ) ); print( temp ); i += MAX_STRING_SIZE; } return this; } if ( _cur.position() + ( 3 * s.length() ) > _cur.capacity() ){ if ( _inSpot ) throw new RuntimeException( "can't put that much stuff in spot" ); _push(); } if ( _cur.position() + ( 3 * s.length() ) > _cur.capacity() ) throw new RuntimeException( "still too big" ); _cur.append( s ); return this; } void _push(){ if ( _mode == OutputMode.BYTES ){ if ( _raw != null ){ if ( _raw.position() == 0 ) return; _raw.flip(); _myStringContent.add( _raw ); } _raw = USE_POOL ? _bbPool.get() : ByteBuffer.wrap( new byte[ _cur.limit() * 2 ] ); return; } if ( _cur == null || _cur.position() == 0 ) return; _cur.flip(); ByteBuffer bb = USE_POOL ? _bbPool.get() : ByteBuffer.wrap( new byte[ _cur.limit() * 2 ] ); if ( bb.position() != 0 || bb.limit() != bb.capacity() ) throw new RuntimeException( "something is wrong with _bbPool" ); CharsetEncoder encoder = _defaultCharset.newEncoder(); // TODO: pool try { CoderResult cr = encoder.encode( _cur , bb , true ); if ( cr.isUnmappable() ) throw new RuntimeException( "can't map some character" ); if ( cr.isOverflow() ) throw new RuntimeException( "buffer overflow here is a bad thing. bb after:" + bb ); bb.flip(); if ( _inSpot ) _myStringContent.add( _spot , bb ); else _myStringContent.add( bb ); _resetBuf(); } catch ( Exception e ){ throw new RuntimeException( "no" , e ); } } public void flush() throws IOException { _flush(); } public void reset(){ _myStringContent.clear(); _resetBuf(); } public String getContent(){ throw new RuntimeException( "not implemented" ); } void _resetBuf(){ _cur.position( 0 ); _cur.limit( _cur.capacity() ); } // reset public void mark( int m ){ _mark = m; } public void clearToMark(){ throw new RuntimeException( "not implemented yet" ); } public String fromMark(){ throw new RuntimeException( "not implemented yet" ); } // going back public void saveSpot(){ if ( _spot >= 0 ) throw new RuntimeException( "already have spot saved" ); _push(); _spot = _myStringContent.size(); } public void backToSpot(){ if ( _spot < 0 ) throw new RuntimeException( "don't have spot" ); _push(); _inSpot = true; } public void backToEnd(){ _push(); _inSpot = false; _spot = -1; } public boolean hasSpot(){ return _spot >= 0; } private CharBuffer _cur; private ByteBuffer _raw; private int _mark = 0; private int _spot = -1; private boolean _inSpot = false; private OutputMode _mode = OutputMode.STRING; } enum OutputMode { STRING, BYTES }; static final int CHAR_BUFFER_SIZE = 1024 * 128; static final int MAX_STRING_SIZE = CHAR_BUFFER_SIZE / 4; static SimplePool<CharBuffer> _charBufPool = new WatchedSimplePool<CharBuffer>( "Response.CharBufferPool" , 50 , -1 ){ public CharBuffer createNew(){ return CharBuffer.allocate( CHAR_BUFFER_SIZE ); } protected long memSize( CharBuffer cb ){ return CHAR_BUFFER_SIZE * 2; } public boolean ok( CharBuffer buf ){ if ( buf == null ) return false; buf.position( 0 ); buf.limit( buf.capacity() ); return true; } }; static ByteBufferPool _bbPool = new ByteBufferPool( "HttpResponse" , 50 , CHAR_BUFFER_SIZE * 4 ); static StringBuilderPool _headerBufferPool = new StringBuilderPool( "HttpResponse" , 25 , 1024 ); static Charset _defaultCharset = Charset.forName( DEFAULT_CHARSET ); static final Properties _responseMessages = new Properties(); static { try { _responseMessages.load( ClassLoader.getSystemClassLoader().getResourceAsStream( "ed/net/httpserver/responseCodes.properties" ) ); } catch ( IOException ioe ){ throw new RuntimeException( ioe ); } } static final JSObjectBase _prototype = new JSObjectBase(); static { _prototype.set( "afterSendingCall" , new JSFunctionCalls1(){ public Object call( Scope s , Object func , Object foo[] ){ if ( ! ( func instanceof JSFunction ) ) throw new RuntimeException( "can't call afterSendingCall w/o function" ); HttpResponse res = (HttpResponse)s.getThis(); res.addDoneHook( s , (JSFunction)func ); return null; } } ); } static boolean isSingleOutputHeader( String name ){ return SINGLE_OUTPUT_HEADERS.contains( name.toLowerCase() ); } static final Set<String> SINGLE_OUTPUT_HEADERS; static { Set<String> s = new HashSet<String>(); s.add( "content-type" ); s.add( "content-length" ); s.add( "date" ); SINGLE_OUTPUT_HEADERS = Collections.unmodifiableSet( s ); } }
package org.openhealthtools.mdht.uml.cda.consol.tests; import java.util.Map; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.ecore.EObject; import org.junit.Test; import org.openhealthtools.mdht.uml.cda.CDAFactory; import org.openhealthtools.mdht.uml.cda.StrucDocText; import org.openhealthtools.mdht.uml.cda.consol.AnesthesiaSection; import org.openhealthtools.mdht.uml.cda.consol.ConsolFactory; import org.openhealthtools.mdht.uml.cda.consol.operations.AnesthesiaSectionOperations; import org.openhealthtools.mdht.uml.cda.operations.CDAValidationTest; import org.openhealthtools.mdht.uml.hl7.datatypes.DatatypesFactory; import org.openhealthtools.mdht.uml.hl7.datatypes.ST; /** * <!-- begin-user-doc --> * A static utility class that provides operations related to '<em><b>Anesthesia Section</b></em>' model objects. * <!-- end-user-doc --> * * <p> * The following operations are supported: * <ul> * <li>{@link org.openhealthtools.mdht.uml.cda.consol.AnesthesiaSection#validateAnesthesiaSectionTemplateId(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Anesthesia Section Template Id</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.consol.AnesthesiaSection#validateAnesthesiaSectionCode(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Anesthesia Section Code</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.consol.AnesthesiaSection#validateAnesthesiaSectionText(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Anesthesia Section Text</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.consol.AnesthesiaSection#validateAnesthesiaSectionTitle(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Anesthesia Section Title</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.consol.AnesthesiaSection#validateAnesthesiaSectionProcedureActivityProcedure(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Anesthesia Section Procedure Activity Procedure</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.consol.AnesthesiaSection#validateAnesthesiaSectionMedicationActivity(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Anesthesia Section Medication Activity</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.consol.AnesthesiaSection#getProcedureActivityProcedures() <em>Get Procedure Activity Procedures</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.consol.AnesthesiaSection#getMedicationActivities() <em>Get Medication Activities</em>}</li> * </ul> * </p> * * @generated */ public class AnesthesiaSectionTest extends CDAValidationTest { /** * * @generated */ @Test public void testValidateAnesthesiaSectionTemplateId() { OperationsTestCase<AnesthesiaSection> validateAnesthesiaSectionTemplateIdTestCase = new OperationsTestCase<AnesthesiaSection>( "validateAnesthesiaSectionTemplateId", operationsForOCL.getOCLValue("VALIDATE_ANESTHESIA_SECTION_TEMPLATE_ID__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(AnesthesiaSection target) { } @Override protected void updateToPass(AnesthesiaSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return AnesthesiaSectionOperations.validateAnesthesiaSectionTemplateId( (AnesthesiaSection) objectToTest, diagnostician, map); } }; validateAnesthesiaSectionTemplateIdTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateAnesthesiaSectionCode() { OperationsTestCase<AnesthesiaSection> validateAnesthesiaSectionCodeTestCase = new OperationsTestCase<AnesthesiaSection>( "validateAnesthesiaSectionCode", operationsForOCL.getOCLValue("VALIDATE_ANESTHESIA_SECTION_CODE__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(AnesthesiaSection target) { } @Override protected void updateToPass(AnesthesiaSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return AnesthesiaSectionOperations.validateAnesthesiaSectionCode( (AnesthesiaSection) objectToTest, diagnostician, map); } }; validateAnesthesiaSectionCodeTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateAnesthesiaSectionText() { OperationsTestCase<AnesthesiaSection> validateAnesthesiaSectionTextTestCase = new OperationsTestCase<AnesthesiaSection>( "validateAnesthesiaSectionText", operationsForOCL.getOCLValue("VALIDATE_ANESTHESIA_SECTION_TEXT__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(AnesthesiaSection target) { } @Override protected void updateToPass(AnesthesiaSection target) { target.init(); StrucDocText text = CDAFactory.eINSTANCE.createStrucDocText(); target.setText(text); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return AnesthesiaSectionOperations.validateAnesthesiaSectionText( (AnesthesiaSection) objectToTest, diagnostician, map); } }; validateAnesthesiaSectionTextTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateAnesthesiaSectionTitle() { OperationsTestCase<AnesthesiaSection> validateAnesthesiaSectionTitleTestCase = new OperationsTestCase<AnesthesiaSection>( "validateAnesthesiaSectionTitle", operationsForOCL.getOCLValue("VALIDATE_ANESTHESIA_SECTION_TITLE__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(AnesthesiaSection target) { } @Override protected void updateToPass(AnesthesiaSection target) { target.init(); ST title = DatatypesFactory.eINSTANCE.createST("title"); target.setTitle(title); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return AnesthesiaSectionOperations.validateAnesthesiaSectionTitle( (AnesthesiaSection) objectToTest, diagnostician, map); } }; validateAnesthesiaSectionTitleTestCase.doValidationTest(); } /** * * @generated not */ @Test public void testValidateAnesthesiaSectionProcedureActivityProcedure() { OperationsTestCase<AnesthesiaSection> validateAnesthesiaSectionProcedureActivityProcedureTestCase = new OperationsTestCase<AnesthesiaSection>( "validateAnesthesiaSectionProcedureActivityProcedure", operationsForOCL.getOCLValue("VALIDATE_ANESTHESIA_SECTION_PROCEDURE_ACTIVITY_PROCEDURE__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(AnesthesiaSection target) { target.init(); } @Override protected void updateToPass(AnesthesiaSection target) { target.addProcedure(ConsolFactory.eINSTANCE.createProcedureActivityProcedure().init()); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return AnesthesiaSectionOperations.validateAnesthesiaSectionProcedureActivityProcedure( (AnesthesiaSection) objectToTest, diagnostician, map); } }; validateAnesthesiaSectionProcedureActivityProcedureTestCase.doValidationTest(); } /** * * @generated not */ @Test public void testValidateAnesthesiaSectionMedicationActivity() { OperationsTestCase<AnesthesiaSection> validateAnesthesiaSectionMedicationActivityTestCase = new OperationsTestCase<AnesthesiaSection>( "validateAnesthesiaSectionMedicationActivity", operationsForOCL.getOCLValue("VALIDATE_ANESTHESIA_SECTION_MEDICATION_ACTIVITY__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(AnesthesiaSection target) { target.init(); } @Override protected void updateToPass(AnesthesiaSection target) { target.addSubstanceAdministration(ConsolFactory.eINSTANCE.createMedicationActivity().init()); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return AnesthesiaSectionOperations.validateAnesthesiaSectionMedicationActivity( (AnesthesiaSection) objectToTest, diagnostician, map); } }; validateAnesthesiaSectionMedicationActivityTestCase.doValidationTest(); } /** * * @generated */ @Test public void testGetProcedureActivityProcedures() { AnesthesiaSection target = objectFactory.create(); target.getProcedureActivityProcedures(); } /** * * @generated */ @Test public void testGetMedicationActivities() { AnesthesiaSection target = objectFactory.create(); target.getMedicationActivities(); } /** * * @generated */ private static class OperationsForOCL extends AnesthesiaSectionOperations { public String getOCLValue(String fieldName) { String oclValue = null; try { oclValue = (String) this.getClass().getSuperclass().getDeclaredField(fieldName).get(this); } catch (Exception e) { oclValue = "NO OCL FOUND FOR PROPERTY " + fieldName; } return oclValue; } } /** * * @generated */ private static class ObjectFactory implements TestObjectFactory<AnesthesiaSection> { public AnesthesiaSection create() { return ConsolFactory.eINSTANCE.createAnesthesiaSection(); } } /** * * @generated */ private static OperationsForOCL operationsForOCL = new OperationsForOCL(); /** * * @generated */ private static ObjectFactory objectFactory = new ObjectFactory(); /** * Tests Operations Constructor for 100% coverage * @generated */ private static class ConstructorTestClass extends AnesthesiaSectionOperations { }; /** * Tests Operations Constructor for 100% coverage * @generated */ @Test public void testConstructor() { @SuppressWarnings("unused") ConstructorTestClass constructorTestClass = new ConstructorTestClass(); } // testConstructor /** * * @generated */ @Override protected EObject getObjectToTest() { return null; } } // AnesthesiaSectionOperations
package com.messners.gitlab.api; /** * This class is provides a simplified interface to a GitLab API server, and divides the API up into * a separate API class for each concern. * * @author Greg Messner <greg@messners.com> */ public class GitLabApi { GitLabApiClient apiClient; private CommitsApi commitsApi; private GroupApi groupApi; private MergeRequestApi mergeRequestApi; private ProjectApi projectApi; private RepositoryApi repositoryApi; private SessionApi sessoinApi; private UserApi userApi; private RepositoryFileApi repositoryFileApi; /** * Logs into GitLab using provided {@code username} and {@code password}, and creates a new * {@code GitLabApi} instance using returned private token * @param url GitLab URL * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @return new {@code GitLabApi} instance configured for a user-specific token */ static public GitLabApi create(String url, String username, String password) throws GitLabApiException { String token = new SessionApi(new GitLabApi(url, null)).login(username, null, password).getPrivateToken(); return new GitLabApi(url, token); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server * specified by hostUrl. * * @param hostUrl * @param privateToken */ public GitLabApi (String hostUrl, String privateToken) { apiClient = new GitLabApiClient(hostUrl, privateToken); commitsApi = new CommitsApi(this); groupApi = new GroupApi(this); mergeRequestApi = new MergeRequestApi(this); projectApi = new ProjectApi(this); repositoryApi = new RepositoryApi(this); sessoinApi = new SessionApi(this); userApi = new UserApi(this); repositoryFileApi = new RepositoryFileApi(this); } /** * Return the GitLabApiClient associated with this instance. This is used by all the sub API classes * to communicate with the GitLab API. * * @return the GitLabApiClient associated with this instance */ GitLabApiClient getApiClient () { return (apiClient); } /** * Gets the CommitsApi instance owned by this GitLabApi instance. The CommitsApi is used * to perform all commit related API calls. * * @return the CommitsApi instance owned by this GitLabApi instance */ public CommitsApi getCommitsApi () { return (commitsApi); } /** * Gets the MergeRequestApi instance owned by this GitLabApi instance. The MergeRequestApi is used * to perform all merge request related API calls. * * @return the MergeRequestApi instance owned by this GitLabApi instance */ public MergeRequestApi getMergeRequestApi () { return (mergeRequestApi); } /** * Gets the GroupApi instance owned by this GitLabApi instance. The GroupApi is used * to perform all group related API calls. * * @return the GroupApi instance owned by this GitLabApi instance */ public GroupApi getGroupApi () { return (groupApi); } /** * Gets the ProjectApi instance owned by this GitLabApi instance. The ProjectApi is used * to perform all project related API calls. * * @return the ProjectApi instance owned by this GitLabApi instance */ public ProjectApi getProjectApi () { return (projectApi); } /** * Gets the RepositoryApi instance owned by this GitLabApi instance. The RepositoryApi is used * to perform all repository related API calls. * * @return the RepositoryApi instance owned by this GitLabApi instance */ public RepositoryApi getRepositoryApi () { return (repositoryApi); } /** * Gets the SessionApi instance owned by this GitLabApi instance. The SessionApi is used * to perform a login to the GitLab API. * * @return the SessionApi instance owned by this GitLabApi instance */ public SessionApi getSessionApi () { return (sessoinApi); } /** * Gets the UserApi instance owned by this GitLabApi instance. The UserApi is used * to perform all user related API calls. * * @return the UserApi instance owned by this GitLabApi instance */ public UserApi getUserApi () { return (userApi); } /** * Gets the RepositoryFileApi instance owned by this GitLabApi instance. The RepositoryFileApi is used * to perform all repository files related API calls. * * @return the RepositoryFileApi instance owned by this GitLabApi instance */ public RepositoryFileApi getRepositoryFileApi() { return repositoryFileApi; } /** * Gets the RepositoryFileApi instance owned by this GitLabApi instance. The RepositoryFileApi is used * to perform all repository files related API calls. * * @return the RepositoryFileApi instance owned by this GitLabApi instance */ public void setRepositoryFileApi(RepositoryFileApi repositoryFileApi) { this.repositoryFileApi = repositoryFileApi; } }
package nl.mpi.arbil; import nl.mpi.arbil.data.ArbilDataNode; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.net.HttpURLConnection; import java.util.Vector; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.UIManager; import nl.mpi.arbil.data.ArbilField; import nl.mpi.arbil.util.BugCatcher; public class ArbilIcons { public ImageIcon linorgIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/" + new ArbilVersion().applicationIconName)); // basic icons used in the gui public ImageIcon serverIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/server16x16.png")); public ImageIcon directoryIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/directory16x16.png")); public ImageIcon computerIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/computer16x16.png")); public ImageIcon loadingIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/loading01.png")); // complex icons used for the imdi files // private ImageIcon corpusicon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/corpusnode_color.png")); private ImageIcon localicon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/local.png")); private ImageIcon remoteicon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/remote.png")); private ImageIcon localWithArchiveHandle = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/localarchivehandle.png")); // private ImageIcon blankIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/blank.png")); private ImageIcon writtenresourceIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/writtenresource.png")); private ImageIcon videoIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/video.png")); // private ImageIcon annotationIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/annotation.png")); private ImageIcon audioIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/audio.png")); // private ImageIcon mediafileIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/mediafile.png")); // private ImageIcon corpuslocal16x16cIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/corpuslocal16x16c.png")); // private ImageIcon metadataIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/metadata.png")); public ImageIcon corpusnodeColorIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/corpusnode_color.png")); //private ImageIcon missingRedIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/missing-red.png")); private ImageIcon missingRedIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/notfound.png")); // private ImageIcon corpusnodeIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/corpusnode.png")); // private ImageIcon openerClosedBlackIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/Opener_closed_black.png")); // private ImageIcon corpusIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/corpus.png")); // private ImageIcon openerOpenBlackIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/Opener_open_black.png")); // private ImageIcon corpusserver16x16cIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/corpusserver16x16c.png")); private ImageIcon picturesIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/pictures.png")); // private ImageIcon corpusserverlocal16x16cIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/corpusserverlocal16x16c.png")); private ImageIcon questionRedIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/question-red.png")); public ImageIcon dataIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/data.png")); public ImageIcon fieldIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/field.png")); private ImageIcon dataemptyIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/dataempty.png")); // private ImageIcon server16x16Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/server16x16.png")); // private ImageIcon directory16x16Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/directory16x16.png")); // private ImageIcon sessionColorLocalIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/session_color-local.png")); // private ImageIcon directoryclosed16x16Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/directoryclosed16x16.png")); public ImageIcon sessionColorIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/session_color.png")); public ImageIcon clarinIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/clarinE.png")); public ImageIcon catalogueColorIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/catalogue.png")); private ImageIcon exclamationBlueIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/exclamation-blue.png")); // private ImageIcon sessionColorServerlocalIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/session_color-serverlocal.png")); // private ImageIcon exclamationGreenIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/exclamation-green.png")); // private ImageIcon sessionColorServerIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/session_color-server.png")); private ImageIcon exclamationRedIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/exclamation-red.png")); public ImageIcon languageIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/language.png")); // private ImageIcon sessionIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/session.png")); // private ImageIcon exclamationYellowIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/exclamation-yellow.png")); // private ImageIcon stopIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/stop.png")); // private ImageIcon file16x16Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/file16x16.png")); // private ImageIcon filelocal16x16Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/filelocal16x16.png")); private ImageIcon tickBlueIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/tick-blue.png")); private ImageIcon fileIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/file.png")); private ImageIcon tickGreenIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/tick-green.png")); // private ImageIcon fileserver16x16Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/fileserver16x16.png")); // private ImageIcon tickRedIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/tick-red.png")); // private ImageIcon fileserverlocal16x16Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/fileserverlocal16x16.png")); // private ImageIcon tickYellowIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/tick-yellow.png")); private ImageIcon infofileIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/infofile.png")); // private ImageIcon transcriptIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/transcript.png")); // private ImageIcon lexiconIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/lexicon.png")); // loading icons // private ImageIcon loading01Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/loading01.png")); // private ImageIcon loading02Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/loading02.png")); // private ImageIcon loading03Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/loading03.png")); // private ImageIcon loading04Icon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/loading04.png")); public ImageIcon favouriteIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/favourite.png")); public ImageIcon lockedIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/lock.png")); public ImageIcon unLockedIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/unlock.png")); // private ImageIcon templateIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/template.png")); public ImageIcon vocabularyOpenIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/vocabulary_open.png")); public ImageIcon vocabularyOpenListIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/vocabulary_open_list.png")); public ImageIcon vocabularyClosedIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/vocabulary_closed.png")); public ImageIcon vocabularyClosedListIcon = new ImageIcon(ArbilIcons.class.getResource("/nl/mpi/arbil/resources/icons/vocabulary_closed_list.png")); private static BugCatcher bugCatcher; public static void setBugCatcher(BugCatcher bugCatcherInstance) { bugCatcher = bugCatcherInstance; } static private ArbilIcons singleInstance = null; static synchronized public ArbilIcons getSingleInstance() { if (singleInstance == null) { singleInstance = new ArbilIcons(); } return singleInstance; } private ArbilIcons() { } public ImageIcon getIconForNode(ArbilDataNode[] arbilNodeArray) { int currentIconXPosition = 0; int width = 0; int heightMax = 0; for (ArbilDataNode currentNode : arbilNodeArray) { width += currentNode.getIcon().getIconWidth(); int height = currentNode.getIcon().getIconHeight(); if (heightMax < height) { heightMax = height; } } BufferedImage bufferedImage = new BufferedImage(width, heightMax, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics().create(); for (Object childNode : arbilNodeArray) { ImageIcon currentIcon = ((ArbilDataNode) childNode).getIcon(); currentIcon.paintIcon(null, g2d, currentIconXPosition, 0); currentIconXPosition += currentIcon.getIconWidth(); } g2d.dispose(); return new ImageIcon(bufferedImage); } public ImageIcon compositIcons(Object[] iconArray) { int widthTotal = 0; int heightMax = 0; for (Object currentIcon : iconArray) { int width = ((Icon) currentIcon).getIconWidth(); int height = ((Icon) currentIcon).getIconHeight(); if (currentIcon != missingRedIcon) { widthTotal += width; } if (heightMax < height) { heightMax = height; } } int currentIconXPosition = 0; BufferedImage bufferedImage = new BufferedImage(widthTotal, heightMax, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics().create(); try { for (Object currentIcon : iconArray) { int yPos = (heightMax - ((Icon) currentIcon).getIconHeight()) / 2; if (currentIcon != missingRedIcon) { // the missing icon always overlays the previous icon ((Icon) currentIcon).paintIcon(null, g2d, currentIconXPosition, yPos); currentIconXPosition += ((Icon) currentIcon).getIconWidth(); } else { ((Icon) currentIcon).paintIcon(null, g2d, currentIconXPosition - missingRedIcon.getIconWidth(), yPos); } } g2d.dispose(); } finally { } return new ImageIcon(bufferedImage); } public Icon getIconForVocabulary(ArbilField cellObject) { if (cellObject.hasVocabulary()) { if (((ArbilField) cellObject).isVocabularyOpen()) { // Open vocabulary if (((ArbilField) cellObject).isVocabularyList()) { // Open list return vocabularyOpenListIcon; } else { // Open single return vocabularyOpenIcon; } } else { // Closed vocabulary if (((ArbilField) cellObject).isVocabularyList()) { // Closed list return vocabularyClosedListIcon; } else { // Closed single return vocabularyClosedIcon; } } } else { return null; } } public Icon getIconForField(ArbilField field) { if (field.hasVocabulary()) { return getIconForVocabulary(field); } else if (field.getLanguageId() != null) { return languageIcon; } else { return null; } } public ImageIcon getIconForNode(ArbilDataNode arbilNode) { Vector iconsVector = new Vector(); if (arbilNode.isLoading() || (arbilNode.getParentDomNode().isMetaDataNode() && !arbilNode.getParentDomNode().isDataLoaded())) { iconsVector.add(loadingIcon); } if (arbilNode.isLocal()) { if (arbilNode.isMetaDataNode()) { if (arbilNode.matchesRemote == 0) { if (arbilNode.archiveHandle == null) { iconsVector.add(localicon); } else { iconsVector.add(localWithArchiveHandle); } } else { iconsVector.add(remoteicon); } } } else { iconsVector.add(remoteicon); // don't show the corpuslocalservericon until the serverside is done, otherwise the icon will show only after copying a branch but not after a restart // if (matchesLocal == 0) { // } else { // icon = corpuslocalservericon; } if (arbilNode.resourceFileServerResponse == HttpURLConnection.HTTP_OK) { iconsVector.add(unLockedIcon); } else if (arbilNode.resourceFileServerResponse == HttpURLConnection.HTTP_MOVED_TEMP) { iconsVector.add(lockedIcon); } String mimeTypeForNode = arbilNode.getAnyMimeType(); if (mimeTypeForNode != null) { mimeTypeForNode = mimeTypeForNode.toLowerCase(); if (mimeTypeForNode.contains("audio")) { iconsVector.add(audioIcon); } else if (mimeTypeForNode.contains("video")) { iconsVector.add(videoIcon); } else if (mimeTypeForNode.contains("image")) { iconsVector.add(picturesIcon); } else if (mimeTypeForNode.contains("text")) { iconsVector.add(writtenresourceIcon); } else if (mimeTypeForNode.contains("xml")) { iconsVector.add(writtenresourceIcon); } else if (mimeTypeForNode.contains("chat")) { iconsVector.add(writtenresourceIcon); } else if (mimeTypeForNode.contains("pdf")) { iconsVector.add(writtenresourceIcon); } else if (mimeTypeForNode.contains("kml")) { iconsVector.add(writtenresourceIcon); } else if (mimeTypeForNode.contains("manual/mediafile")) { iconsVector.add(picturesIcon); } else if (mimeTypeForNode.contains("manual/writtenresource")) { iconsVector.add(writtenresourceIcon); } else if (mimeTypeForNode.contains("unspecified") || mimeTypeForNode.length() == 0) { // no icon for this iconsVector.add(fileIcon); } else if(mimeTypeForNode.contains("unknown")){ iconsVector.add(questionRedIcon); } else if (mimeTypeForNode.length() > 0) { iconsVector.add(questionRedIcon); bugCatcher.logError(mimeTypeForNode, new Exception("Icon not found for file type: " + mimeTypeForNode)); } } else if (arbilNode.isInfoLink) { iconsVector.add(infofileIcon); } else if (arbilNode.hasResource()) { // the resource is not found so show a unknow resource icon iconsVector.add(fileIcon); } else if (arbilNode.isMetaDataNode()) { if (arbilNode.isChildNode()) { if (arbilNode.isEmptyMetaNode()) { iconsVector.add(dataemptyIcon); } else { iconsVector.add(dataIcon); } } else if (arbilNode.isSession()) { iconsVector.add(sessionColorIcon); } else if (arbilNode.isCatalogue()) { iconsVector.add(catalogueColorIcon); } else if (arbilNode.isCorpus()) { iconsVector.add(corpusnodeColorIcon); } else if (arbilNode.isCmdiMetaDataNode()) { iconsVector.add(clarinIcon); } else { // this icon might not be the best one to show in this case if (arbilNode.isDataLoaded()) { iconsVector.add(fileIcon); } //iconsVector.add(blankIcon); } } else if (arbilNode.isDirectory()) { iconsVector.add(UIManager.getIcon("FileView.directoryIcon")); } else { iconsVector.add(fileIcon); } // add missing file icon if ((arbilNode.fileNotFound || arbilNode.resourceFileNotFound())) { if (arbilNode.isResourceSet()) { iconsVector.add(missingRedIcon); } else { iconsVector.add(questionRedIcon); } } // add a file attached to a session icon if (!arbilNode.isMetaDataNode() && arbilNode.matchesInCache + arbilNode.matchesRemote > 0) { if (arbilNode.matchesRemote > 0) { iconsVector.add(tickGreenIcon); } else { iconsVector.add(tickBlueIcon); } } // add icons for favourites if (arbilNode.isFavorite()) { iconsVector.add(favouriteIcon); } // add icons for save state // if (arbilNode.hasHistory()) { // iconsVector.add(exclamationBlueIcon); // if (arbilNode.getNeedsSaveToDisk()) { // iconsVector.add(exclamationRedIcon); return compositIcons(iconsVector.toArray());// TODO: here we could construct a string describing the icon and only create if it does not alread exist in a hashtable } }
package Server; import team17.sheet06.common.IComputationService; import team17.sheet06.common.IJob; import team17.sheet06.common.IJobDoneCallback; import team17.sheet06.common.Job; import java.rmi.RemoteException; import java.util.concurrent.*; public class ComputationService implements IComputationService { private ExecutorService executor; private volatile int currentJobs; private final int MAX_JOBS = 1; public ComputationService(){ executor = Executors.newCachedThreadPool(); } @Override public <T> IJob<T> submit(Callable<T> task, IJobDoneCallback<T> callback) throws RemoteException { if (currentJobs >= MAX_JOBS) return null; incrementJobCount(); Job<T> job = new Job<>(); Runnable taskRunner = new Runnable() { @Override public void run() { try { final T x = task.call(); callback.setResult(x); decrementJobCount(); } catch (Exception e) { e.printStackTrace(); } } }; executor.execute(taskRunner); return job; } private synchronized void incrementJobCount(){ this.currentJobs++; } private synchronized void decrementJobCount(){ this.currentJobs } }
package com.minimajack.v8.project; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.minimajack.v8.io.Strategy; import com.minimajack.v8.parser.impl.FileParserTask; import com.minimajack.v8.parser.result.Result; public class Project { final Logger logger = LoggerFactory.getLogger( Project.class ); public static final String BASE_NAME = "project.xml"; public static final String BASE_SRC_NAME = "src"; private File packedFile; private File location; private Strategy strategy; public void loadProject() { } public void saveProject() { } public boolean unpackProject() throws JAXBException { FileParserTask reader = new FileParserTask( packedFile.getPath(), location.getPath() + File.separator + BASE_SRC_NAME + File.separator, strategy ); Result result = reader.compute(); String projectFile = location.getPath() + File.separator + BASE_NAME; logger.debug( "Project path {}", projectFile ); result.relativize( location.toPath().toAbsolutePath() ); JAXBContext jaxbContext = JAXBContext.newInstance( Result.class ); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true ); jaxbMarshaller.marshal( result, new File( projectFile ) ); return true; } public File getPackedFile() { return packedFile; } public void setPackedFile( File packedFile ) { this.packedFile = packedFile; } public File getLocation() { return location; } public void setLocation( File location ) { this.location = location; } public Strategy getStrategy() { return strategy; } public void setStrategy( Strategy strategy ) { this.strategy = strategy; } }
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class OPM_Sample extends OPMSuper implements Comparator<String> { public void testNormalMethodCouldBePrivate() { someNormalMethod(); } @Override public int compare(String s1, String s2) { return s2.compareTo(s1); } public int testFPGenericDerivation() { return compare("Hello", "World"); } public void someNormalMethod() { List<String> l = getFoo(new ArrayList<String>()); } @Override public List<String> getFoo(List<String> l) { return l; } public void fpUncalledDontReport() { fpHasRTAnnotation(); } @RT public void fpHasRTAnnotation() { } public void setFPFoo(int x) { } public int getFPFoo() { return 0; } } abstract class OPMSuper { public abstract List<String> getFoo(List<String> l); } @Retention(RetentionPolicy.RUNTIME) @interface RT { } enum FPEnumValueOf { What, Where; public static void fpWithValueOf() { FPEnumValueOf f = FPEnumValueOf.valueOf(String.valueOf("What")); } } class OPMParent { public OPMParent(int i) { } class FPOPMChild extends OPMParent{ public FPOPMChild() { super(1); } } }
package com.nerodesk.om.aws; import com.amazonaws.services.s3.Headers; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.util.DateUtils; import com.nerodesk.om.Attributes; import java.io.IOException; import java.util.Date; import lombok.EqualsAndHashCode; /** * Aws based document attributes. * * @author Krzysztof Krason (Krzysztof.Krason@gmail.com) * @version $Id$ * @since 0.4 */ @EqualsAndHashCode public final class AwsAttributes implements Attributes { /** * Visible attribute name. */ private static final String VISIBLE_ATTR = "visible"; /** * AWS document metadata. */ private final transient ObjectMetadata meta; /** * Ctor. * @param metadata AWS document metadata. */ public AwsAttributes(final ObjectMetadata metadata) { this.meta = metadata; } @Override public long size() throws IOException { return this.meta.getContentLength(); } @Override public String type() throws IOException { return this.meta.getContentType(); } @Override public Date created() throws IOException { final Date date; if (this.meta.getRawMetadataValue(Headers.DATE) == null) { date = this.meta.getLastModified(); } else { date = DateUtils.cloneDate( (Date) this.meta.getRawMetadataValue(Headers.DATE) ); } return date; } @Override public boolean visible() throws IOException { return Boolean.parseBoolean( this.meta.getUserMetaDataOf(AwsAttributes.VISIBLE_ATTR) ); } @Override public void show(final boolean shown) { this.meta.addUserMetadata( AwsAttributes.VISIBLE_ATTR, String.valueOf(shown) ); } }
package com.bitso.helpers; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Helpers { private static final List<Field> getAllFields(List<Field> fields, Class<?> type) { fields.addAll(Arrays.asList(type.getDeclaredFields())); if (type.getSuperclass() != null) { fields = getAllFields(fields, type.getSuperclass()); } return fields; } public static final String fieldPrinter(Object obj) { StringBuilder sb = new StringBuilder(); sb.append("=============="); List<Field> fields = getAllFields(new ArrayList<Field>(), obj.getClass()); for (Field f : fields) { try { Object o = f.get(obj); sb.append('\n'); sb.append(f.getName()); sb.append(": "); sb.append(o); } catch (Exception e) { e.printStackTrace(); } } sb.append("\n==============\n"); return sb.toString(); } }
package com.nx.util.jme3.base; import com.jme3.animation.AnimControl; import com.jme3.animation.Bone; import com.jme3.animation.SkeletonControl; import com.jme3.asset.AssetManager; import com.jme3.bounding.BoundingBox; import com.jme3.bounding.BoundingVolume; import com.jme3.collision.Collidable; import com.jme3.collision.CollisionResults; import com.jme3.font.BitmapFont; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.scene.*; import com.jme3.scene.control.AbstractControl; import com.jme3.scene.control.Control; import com.jme3.scene.debug.Arrow; import com.jme3.scene.shape.Box; import com.jme3.scene.shape.Sphere; import com.jme3.util.SafeArrayList; import jme3tools.optimize.GeometryBatchFactory; import org.slf4j.LoggerFactory; import java.nio.*; import java.util.*; import static com.nx.util.jme3.base.DebugUtil.assetManager; /** * TODO: merge all duplicated methods (they can be handled in a single one without any performance impact. Doubling them is just useless... I think.) * @author NemesisMate */ public final class SpatialUtil { private SpatialUtil() { } public interface Operation { /** * Must stop that rama * @return */ public boolean operate(Spatial spatial); } public interface ReturnOperation<T extends Object> extends Operation { public T getReturnObject(); } // TODO improve visit first to cut on the for if returnedObject on returnoperation == null. public static <T extends Operation> T visitNodeWith(Spatial spatial, T operation) { if(!operation.operate(spatial)) { if(spatial instanceof Node) { for(Spatial s : ((Node)spatial).getChildren()) { visitNodeWith(s, operation); } } } return operation; } // public void generateTangents(Spatial task) { // if(task == null) { // return; // task.depthFirstTraversal(new SceneGraphVisitor() { // @Override // public void visit(Spatial task) { // if(task instanceof Geometry) { // Mesh mesh = ((Geometry) task).getMesh(); // if(mesh.getBuffer(VertexBuffer.Type.Normal) != null && mesh.getBuffer(VertexBuffer.Type.Tangent) == null) { // TangentBinormalGenerator.generate(mesh); /** * Prints the scenegraph on the debug console. * * @param spatial to print recursively. */ public static void drawGraph(Spatial spatial) { System.out.println(spatial); if(!(spatial instanceof Node)) return; List<Spatial> spatials = new ArrayList<>(); //Map<Spatial, Integer> repeated = new HashMap<>(); List<String> lines = sceneGraphLoop(((Node)spatial).getChildren(), spatials, "", new ArrayList<String>()); for(String line : lines) { System.out.println(line); } for(Spatial spat : spatials) { int count = 0; //System.out.println(task.getName()); for(Spatial spat2 : spatials) if(spat == spat2) count++; if(count > 1){ System.out.println(spat.getName() + "(REPEATED - IMPOSSIBLE): " + count); //repeated.put(task, count); } } System.out.println("Total: " + spatials.size() + "\n\n\n\n"); } //TODO public static List<String> getDrawGraph(final Spatial spatial) { return sceneGraphLoop(new ArrayList<Spatial>(1) {{ add(spatial); }}, new ArrayList<Spatial>(), "", new ArrayList<String>()); } private static List<String> sceneGraphLoop(List<Spatial> spatials, List<Spatial> all, String dashes, List<String> lines) { dashes += "-"; for(Spatial spatial : spatials) { all.add(spatial); String data = dashes + spatial; if(spatial instanceof Geometry) { data += "(" + ((Geometry)spatial).getMaterial().getName() + " <>" + ((Geometry) spatial).getMaterial().getKey() + ")"; } int numControls = spatial.getNumControls(); data += " - (" + spatial.getTriangleCount() + "t, " + spatial.getVertexCount() + "v) LOC[L:" + spatial.getLocalTranslation() + ", W:" + spatial.getWorldTranslation() + "] SCALE[L:" + spatial.getLocalScale() + ", W:" + spatial.getWorldScale() + "] ROT[L:" + spatial.getLocalRotation() + ", W:" + spatial.getWorldRotation() + "]" + " - Controls: " + numControls; if(numControls > 0) { data += " ("; for(int i = 0; i < numControls; i++) { Control control = spatial.getControl(i); data += control.getClass().getSimpleName() + ", "; } data = data.substring(0, data.length() - 2); data += ")"; } // System.out.println(data); // stringBuilder.append('\n' + data); lines.add(data); if(spatial instanceof Node) { sceneGraphLoop(((Node)spatial).getChildren(), all, dashes, lines); } } return lines; } public static Geometry gatherFirstGeom(Spatial spatial) { if (spatial instanceof Node) { for (Spatial child : ((SafeArrayList<Spatial>)((Node)spatial).getChildren()).getArray()) { return gatherFirstGeom(child); } } else if (spatial instanceof Geometry) { return (Geometry) spatial; } return null; } public static List<Mesh> gatherMeshes(Spatial spatial, List<Mesh> meshStore) { if (spatial instanceof Node) { Node node = (Node) spatial; for (Spatial child : ((SafeArrayList<Spatial>)node.getChildren()).getArray()) { gatherMeshes(child, meshStore); } } else if (spatial instanceof Geometry) { meshStore.add(((Geometry) spatial).getMesh()); } return meshStore; } public static void gatherGeoms(Spatial spatial, Mesh.Mode mode, List<Geometry> geomStore) { if (spatial instanceof Node) { Node node = (Node) spatial; for (Spatial child : ((SafeArrayList<Spatial>)node.getChildren()).getArray()) { gatherGeoms(child, mode, geomStore); } } else if (spatial instanceof Geometry && ((Geometry) spatial).getMesh().getMode() == mode) { geomStore.add((Geometry) spatial); } } public static Node getAllBounds(Spatial spatial) { final Node bounds = new Node(spatial.getName() + "_BOUNDS"); spatial.depthFirstTraversal(new SceneGraphVisitor() { @Override public void visit(Spatial spatial) { if(spatial instanceof Geometry) { BoundingBox bb = (BoundingBox) spatial.getWorldBound(); Box b = new Box(bb.getXExtent(), bb.getYExtent(), bb.getZExtent()); Geometry geom = new Geometry(null, b); bounds.attachChild(geom); } else { if(((Node)spatial).getQuantity() == 0) { Sphere b = new Sphere(10, 10, 0.25f * spatial.getWorldScale().length()); Geometry geom = new Geometry(null, b); bounds.attachChild(geom); } } } }); return bounds; } public static Map<Spatial, Geometry> getBounds(Spatial spatial, Map<Spatial, Geometry> bounds) { if(bounds == null) { bounds = new HashMap<>(); } final Map<Spatial, Geometry> finalBounds = bounds; spatial.depthFirstTraversal(new SceneGraphVisitor() { @Override public void visit(Spatial spatial) { if(spatial instanceof Geometry) { BoundingBox bb = (BoundingBox) spatial.getWorldBound(); Box b = new Box(bb.getXExtent(), bb.getYExtent(), bb.getZExtent()); Geometry geom = new Geometry(null, b); finalBounds.put(spatial, geom); } else { if(((Node)spatial).getQuantity() == 0) { Sphere b = new Sphere(10, 10, 0.25f * spatial.getWorldScale().length()); Geometry geom = new Geometry(null, b); finalBounds.put(spatial, geom); } } } }); return finalBounds; } public static boolean isChild(Spatial child, Spatial parent) { if(child == parent) { return true; } if(parent instanceof Node) { for (Spatial c : (((SafeArrayList<Spatial>)((Node)parent).getChildren()).getArray())) { if(isChild(child, c)) { return true; } } } return false; }; /** * Finds a task on the given task (usually, a node). * * @param spatial * @param name * @return */ public static Spatial find(Spatial spatial, final String name) { if(spatial != null) { String spatName = spatial.getName(); if(spatName != null && spatName.equals(name)) return spatial; // if(task instanceof Node) return nodeFind((Node)task, name); if(spatial instanceof Node) return ((Node)spatial).getChild(name); } return null; } public static Geometry findGeometry(Spatial spatial, final String name) { if(spatial != null) { String spatName = spatial.getName(); // if(task instanceof Node) return nodeFind((Node)task, name); if(spatial instanceof Node) { return findGeometry((Node)spatial, name); } else { if(spatName != null && spatName.equals(name)) return (Geometry) spatial; } } return null; } public static Geometry findGeometry(Node node, String name) { for (Spatial child : ((SafeArrayList<Spatial>)node.getChildren()).getArray()) { String spatName = child.getName(); if(child instanceof Node) { Geometry out = findGeometryStartsWith((Node)child, name); if(out != null) { return out; } } else { if (spatName != null && spatName.equals(name)) { return (Geometry) child; } } } return null; } public static List<Spatial> findAllStartsWith(Spatial spatial, final String name, List<Spatial> storeList, boolean nested) { if(spatial != null) { String spatName = spatial.getName(); if(spatName != null && spatName.startsWith(name)) { storeList.add(spatial); if(nested) { if(spatial instanceof Node) { findAllStartsWith((Node)spatial, name, storeList, nested); } } } else if(spatial instanceof Node) { return findAllStartsWith((Node)spatial, name, storeList, nested); } } return storeList; } public static List<Spatial> findAllStartsWith(Node node, final String name, List<Spatial> storeList, boolean nested) { for (Spatial child : ((SafeArrayList<Spatial>)node.getChildren()).getArray()) { String spatName = child.getName(); if (spatName != null && spatName.startsWith(name)) { storeList.add(child); if(nested) { if(child instanceof Node) { findAllStartsWith((Node)child, name, storeList, nested); } } } else if(child instanceof Node) { findAllStartsWith((Node)child, name, storeList, nested); } } return storeList; } public static Spatial findStartsWith(Spatial spatial, final String name) { if(spatial != null) { String spatName = spatial.getName(); if(spatName != null && spatName.startsWith(name)) return spatial; // if(task instanceof Node) return nodeFind((Node)task, name); if(spatial instanceof Node) { return findStartsWith((Node)spatial, name); } } return null; } public static Spatial findStartsWith(Node node, String name) { for (Spatial child : ((SafeArrayList<Spatial>)node.getChildren()).getArray()) { String spatName = child.getName(); if (spatName != null && spatName.startsWith(name)) { return child; } else if(child instanceof Node) { Spatial out = findStartsWith((Node)child, name); if(out != null) { return out; } } } return null; } public static String getUserDataKeyStartsWith(Spatial spatial, final String name) { Collection<String> keys = spatial.getUserDataKeys(); if(keys != null && !keys.isEmpty()) { for (String key : keys) { if(key.startsWith(name)) { return key; } } } return null; } public static <T> Collection<T> getAllUserDataStartsWith(Spatial spatial, final String name) { Collection<String> keys = spatial.getUserDataKeys(); if(keys != null && !keys.isEmpty()) { Collection<T> userDatas = new ArrayList<T>(keys.size()); for (String key : keys) { if(key.startsWith(name)) { userDatas.add((T) spatial.getUserData(key)); } } return userDatas; } return null; } public static <T> T getUserDataStartsWith(Spatial spatial, final String name) { Collection<String> keys = spatial.getUserDataKeys(); if(keys != null && !keys.isEmpty()) { for (String key : keys) { if(key.startsWith(name)) { return spatial.getUserData(key); } } } return null; } public static List<Spatial> findAllWithDataStartsWith(Spatial spatial, final String name, List<Spatial> storeList, boolean nested) { if(spatial != null) { Collection<String> keys = spatial.getUserDataKeys(); if(keys != null && !keys.isEmpty()) { for(String key : keys) { if(key.startsWith(name)) { storeList.add(spatial); if(!nested) { return storeList; } else { break; } } } } if(spatial instanceof Node) { return findAllWithDataStartsWith((Node) spatial, name, storeList, nested); } } return storeList; } public static List<Spatial> findAllWithDataStartsWith(Node node, final String name, List<Spatial> storeList, boolean nested) { for (Spatial child : ((SafeArrayList<Spatial>)node.getChildren()).getArray()) { findAllWithDataStartsWith(child, name, storeList, nested); } return storeList; } public static Geometry findGeometryStartsWith(Spatial spatial, final String name) { if(spatial != null) { String spatName = spatial.getName(); // if(task instanceof Node) return nodeFind((Node)task, name); if(spatial instanceof Node) { return findGeometryStartsWith((Node)spatial, name); } else { if(spatName != null && spatName.startsWith(name)) return (Geometry) spatial; } } return null; } public static Geometry findGeometryStartsWith(Node node, String name) { for (Spatial child : ((SafeArrayList<Spatial>)node.getChildren()).getArray()) { String spatName = child.getName(); if(child instanceof Node) { Geometry out = findGeometryStartsWith((Node)child, name); if(out != null) { return out; } } else { if (spatName != null && spatName.startsWith(name)) { return (Geometry) child; } } } return null; } public static Spatial findHasUserData(Node node, final String key) { if(node != null) { for(Spatial spatial : node.getChildren()) { Spatial found = findHasUserData(spatial, key); if(found != null) { return found; } } } return null; } public static Spatial findHasUserData(Spatial spatial, final String key) { if(spatial != null) { if(spatial.getUserData(key) != null) { return spatial; } // if(task instanceof Node) return nodeFind((Node)task, name); if(spatial instanceof Node) { return findHasUserData((Node)spatial, key); } } return null; } // NOT NEEDED, getChild(name) does the same thing // private static Spatial nodeFind(Node node, final String name) { // Spatial ret = null; // for(Spatial spat : node.getChildren()) { // String spatName = spat.getName(); // if(spatName != null && spat.getName().equals(name)) return spat; // if(spat instanceof Node) { // ret = nodeFind((Node)spat, name); // if(ret != null) return ret; // return ret; /** * Not safe (not enough tested). * * Resizes a task without altering it scale. * TODO: make sure the animations still fine. * * @param spatial * @param scale */ public static void resize(Spatial spatial, final float scale) { SceneGraphVisitor visitor = new SceneGraphVisitor() { @Override public void visit(Spatial spat) { if(spat instanceof Geometry) { VertexBuffer pb = ((Geometry)spat).getMesh().getBuffer(VertexBuffer.Type.Position); FloatBuffer positions = (FloatBuffer) pb.getData(); for(int i = 0; i < positions.capacity(); i++) { positions.put(i, positions.get(i) * scale); } } } }; spatial.depthFirstTraversal(visitor); // task.updateGeometricState(); // task.updateModelBound(); SkeletonControl control = spatial.getControl(SkeletonControl.class); if(control == null) return; for(Bone bone : control.getSkeleton().getRoots()) { // If don't want to change the whole model (only the instance on the task) uncomment // the following two lines (bone.setUser..., and comment bone.setBindTransforms(...) bone.setUserControl(true); bone.setUserTransforms(new Vector3f(Vector3f.ZERO), Quaternion.IDENTITY, new Vector3f(scale, scale, scale)); //bone.setBindTransforms(Vector3f.ZERO, Quaternion.IDENTITY, new Vector3f(scale, scale, scale)); } // AnimControl animControl = task.getControl(AnimControl.class); // if(animControl == null) return; // animControl.getAnim("").getTracks()[0] } /** * Translates the internal geometries of this task without altering the task local translation. * @param spatial * @param translation */ public static void translateGeom(final Spatial spatial, final Vector3f translation) { SceneGraphVisitor visitor = new SceneGraphVisitor() { @Override public void visit(Spatial spat) { if(spat instanceof Geometry) { // VertexBuffer pb = ((Geometry)spat).getMesh().getBuffer(VertexBuffer.Type.Position); // FloatBuffer positions = (FloatBuffer) pb.getData(); // for(int i = 0; i < positions.capacity(); i++) // positions.put(i, positions.get(i) + (1f/task.getLocalScale().y)); //spat.setLocalTranslation(new Vector3f(0f, 1f, 0f).multLocal(Vector3f.UNIT_XYZ.divide(task.getLocalScale()))); spat.setLocalTranslation(translation.divide(spatial.getLocalScale())); } } }; spatial.depthFirstTraversal(visitor); } /** * Rotates the internal geometries of this task without altering the task local Rotates. * * @param spatial * @param angle * @param axis */ public static void rotateGeom(final Spatial spatial, final float angle, final Vector3f axis) { SceneGraphVisitor visitor = new SceneGraphVisitor() { @Override public void visit(Spatial spat) { if(spat instanceof Geometry) spat.getLocalRotation().fromAngleAxis(angle, axis); //spat.setLocalRotation(rotation); } }; spatial.depthFirstTraversal(visitor); } /** * Optimizes Geometries and Nodes for the given task. * Basically, performs a {@link #optimizeGeoms(Spatial)} followed by a {@link #optimizeNodes(Spatial)} * * @param spatial to optimize. */ public static void optimizeAll(Spatial spatial) { optimizeGeoms(spatial); optimizeNodes(spatial); } /** * Optimizes Geometries for the given task. * * @param spatial to optimize. */ public static void optimizeGeoms(Spatial spatial) { if(spatial instanceof Node) { GeometryBatchFactory.optimize((Node)spatial); // System.gc(); } } /** * Optimizes Nodes for the given task. * * @param spatial to optimize. */ public static void optimizeNodes(Spatial spatial) { SceneGraphVisitor visitor = new SceneGraphVisitor() { // public int i = 0; // Node compareNode = new Node("node"); @Override public void visit(Spatial spat) { // SceneGraphVisitor visitor = new SceneGraphVisitor() { // @Override // public void visit(Spatial spat) { if(spat instanceof Node) { if(((Node)spat).getChildren().isEmpty()) spat.removeFromParent(); else for(Spatial spat2 : ((Node)spat).getChildren()) { if(spat2 instanceof Node) { if(spat2.getLocalScale().equals(Vector3f.UNIT_XYZ) && spat2.getLocalTranslation().equals(Vector3f.ZERO) && spat2.getLocalRotation().equals(Quaternion.IDENTITY) && spat2.getLocalLightList().size() == 0) { // spat2.setName("node"); // if(spat2.equals(compareNode)) { // System.out.println("Nodo sobrante"); for(Spatial spat3 :((Node)spat2).getChildren()) ((Node)spat).attachChild(spat3); spat.removeFromParent(); // igual a ((Node)spat).detachChild(spat2); } } } //spat.depthFirstTraversal(visitor); } // System.out.println("Total: " + i); } }; spatial.depthFirstTraversal(visitor); // System.gc(); } public static boolean hasControl(Spatial spat, Control control) { int numControl = spat.getNumControls(); for(int i = 0; i < numControl; i++) { if(spat.getControl(i) == control) { return true; } } return false; } public static Collection<AnimControl> getAnimControlsFor(Spatial spat) { return getControlsFor(spat, AnimControl.class); } public static AnimControl getFirstAnimControlFor(Spatial spat) { return getFirstControlFor(spat, AnimControl.class); } public static void removeControlsFor(Spatial spat, final Class<? extends Control> controlClass) { // List<T> controls = new ArrayList<>(3); spat.depthFirstTraversal(new SceneGraphVisitor() { @Override public void visit(Spatial spatial) { Control control = spatial.getControl(controlClass); if(control != null) { spatial.removeControl(control); // controls.add(control); } } }); // return controls; } public static <T extends Control> Collection<T> getControlsNoRecursive(Spatial spat, Class<T> controlClass) { ArrayList<T> controls = new ArrayList<>(3); int numControls = spat.getNumControls(); for(int i = 0; i < numControls; i++) { Control control = spat.getControl(i); if(controlClass.isAssignableFrom(control.getClass())) { controls.add((T) control); } } controls.trimToSize(); return controls; } public static <T extends Control> Collection<T> getControlsFor(Spatial spat, final Class<T> controlClass) { final List<T> controls = new ArrayList<>(3); spat.depthFirstTraversal(new SceneGraphVisitor() { @Override public void visit(Spatial spatial) { T control = spatial.getControl(controlClass); if(control != null) { controls.add(control); } } }); return controls; } public static <T extends Control> T getFirstControlFor(Spatial spat, final Class<T> controlClass) { return visitNodeWith(spat, new Operation() { T firstControl; @Override public boolean operate(Spatial spatial) { if(firstControl != null) { return true; } T control = spatial.getControl(controlClass); if(control != null) { this.firstControl = control; return true; } return false; } }).firstControl; } public static <T extends AbstractControl> T getFirstEnabledControlFor(Spatial spat, final Class<T> controlClass) { return visitNodeWith(spat, new Operation() { T firstControl; @Override public boolean operate(Spatial spatial) { if(firstControl != null) { return true; } T control = spatial.getControl(controlClass); if(control != null && control.isEnabled()) { this.firstControl = control; return true; } return false; } }).firstControl; } public static Geometry createArrow(Vector3f direction) { Geometry geometry = new Geometry("SU Created Arrow", new Arrow(direction)); if(geometry.getMesh().getBuffer(VertexBuffer.Type.Normal) == null) { int vCount = geometry.getMesh().getVertexCount(); float[] buff = new float[vCount * 3]; for(int i = 0; i < vCount; i++) { buff[i] = 0; } geometry.getMesh().setBuffer(VertexBuffer.Type.Normal, 3, buff); } else { LoggerFactory.getLogger(SpatialUtil.class).error("I know, this is not an error, but all this normal buffers stuff is not more needed."); } return geometry; } /** * Use the DebugUtil getDebugArrow instead. * @param direction * @param color * @return */ @Deprecated public static Geometry createArrow(Vector3f direction, ColorRGBA color) { Arrow arrow = new Arrow(direction); Geometry geometry = new Geometry("SU Created Arrow", arrow); Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); if(color == null) { color = ColorRGBA.randomColor(); } material.setColor("Color", color); geometry.setMaterial(material); return geometry; } public static Geometry createBox(float size) { return createBox(size, size, size); } public static Geometry createBox(Vector3f extents) { return createBox(extents.x, extents.y, extents.z); } public static Geometry createBox(float halfX, float halfY, float halfZ) { return new Geometry("SU Created Box", new Box(halfX, halfY, halfZ)); // create cube geometry from the shape } public static Geometry createSphere(float size) { return new Geometry("SU Created Sphere", new Sphere(10, 10, size)); } public static Geometry createSphere(Vector3f extents) { return createSphere(extents.x, extents.y, extents.z); } public static Geometry createSphere(float halfX, float halfY, float halfZ) { if(halfY > halfX) { if(halfZ > halfY) { return createSphere(halfZ); } return createSphere(halfY); } return createSphere(halfX); } public static Material createMaterial(AssetManager assetManager, ColorRGBA color) { Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", color != null ? color : ColorRGBA.randomColor()); return mat; } //TODO: redo the full split method having in mind it optimization for usages with substring (avoiding it intensive current new allocation) public static List<String> splitTextIntoLines(BitmapFont font, float maxChatWidth, String text, List<String> finalMessage) { if(finalMessage == null) { finalMessage = new ArrayList<>(); } else { if(!(finalMessage instanceof ArrayList)) { // LoggerFactory.getLogger(SpatialUtil.class).error("The current implementation only supports ArrayList"); throw new UnsupportedOperationException("The current implementation only supports ArrayList"); } } finalMessage = splitTextIntoLines(font, maxChatWidth, finalMessage, text.split(" "), 0); ((ArrayList)finalMessage).trimToSize(); return finalMessage; } private static List<String> splitTextIntoLines(BitmapFont font, float maxChatWidth, List<String> finalMessage, String[] words, int index) { String current; String substring; float accumulated = 0; float whiteSpaceSize = font.getLineWidth(" "); float dashSpaceSize = font.getLineWidth("-"); if(finalMessage.isEmpty()) finalMessage.add(""); else accumulated = font.getLineWidth(finalMessage.get(finalMessage.size() - 1)) + whiteSpaceSize; for(;index < words.length; ++index) { accumulated += font.getLineWidth(words[index]) + whiteSpaceSize; if(accumulated > maxChatWidth) { // If the word itself is too big if(font.getLineWidth(words[index]) > maxChatWidth) { if(words[index].length() <= 1) { // LoggerFactory.getLogger(SpatialUtil.class).error("Given max width too small: {}", maxChatWidth); throw new UnsupportedOperationException("Given max width too small: " + maxChatWidth); } int wordIndex = 0; while(wordIndex < words[index].length()) { substring = words[index].substring(wordIndex, words[index].length()); float size = font.getLineWidth(substring) + dashSpaceSize; while(size > maxChatWidth) { substring = substring.substring(0, substring.length()/2); size = font.getLineWidth(substring) + dashSpaceSize; } // < because we have to add the "-" character at the end of that word int wordEnd = wordIndex + substring.length(); while(size < maxChatWidth && wordEnd < words[index].length()) { substring = words[index].substring(wordIndex, wordEnd++); size = font.getLineWidth(substring) + dashSpaceSize; } wordIndex += substring.length(); int currentIndex = finalMessage.size() - 1; current = finalMessage.get(currentIndex); if(current.length() != 0) { current = substring; //new StringBuilder(substring); finalMessage.add(current); currentIndex++; } else current += substring; if(wordIndex < words[index].length()) current += "-"; else current += " "; finalMessage.set(currentIndex, current); } return splitTextIntoLines(font, maxChatWidth, finalMessage, words, index + 1); } else { accumulated = font.getLineWidth(words[index]) + whiteSpaceSize; finalMessage.add(""); } } int currentIndex = finalMessage.size() - 1; current = finalMessage.get(currentIndex) + words[index]; if(index < words.length - 1) current += " "; finalMessage.set(currentIndex, current); } return finalMessage; } public static List<StringBuilder> splitTextIntoLines2(BitmapFont font, float maxChatWidth, String text, List<StringBuilder> finalMessage) { if(finalMessage == null) { finalMessage = new ArrayList<>(); } else { if(!(finalMessage instanceof ArrayList)) { // LoggerFactory.getLogger(SpatialUtil.class).error("The current implementation only supports ArrayList"); throw new UnsupportedOperationException("The current implementation only supports ArrayList"); } } finalMessage = splitTextIntoLines2(font, maxChatWidth, finalMessage, text.split(" "), 0); ((ArrayList)finalMessage).trimToSize(); return finalMessage; } private static List<StringBuilder> splitTextIntoLines2(BitmapFont font, float maxChatWidth, List<StringBuilder> finalMessage, String[] words, int index) { StringBuilder current; String substring; float accumulated = 0; float whiteSpaceSize = font.getLineWidth(" "); float dashSpaceSize = font.getLineWidth("-"); if(finalMessage.isEmpty()) finalMessage.add(new StringBuilder("")); else accumulated = font.getLineWidth(finalMessage.get(finalMessage.size() - 1).toString()) + whiteSpaceSize; for(;index < words.length; ++index) { accumulated += font.getLineWidth(words[index]) + whiteSpaceSize; if(accumulated > maxChatWidth) { // If the word itself is too big if(font.getLineWidth(words[index]) > maxChatWidth) { int wordIndex = 0; while(wordIndex < words[index].length()) { substring = words[index].substring(wordIndex, words[index].length()); float size = font.getLineWidth(substring) + dashSpaceSize; while(size > maxChatWidth) { substring = substring.substring(0, substring.length()/2); size = font.getLineWidth(substring) + dashSpaceSize; } // < because we have to add the "-" character at the end of that word int wordEnd = wordIndex + substring.length(); while(size < maxChatWidth && wordEnd < words[index].length()) { substring = words[index].substring(wordIndex, wordEnd++); size = font.getLineWidth(substring) + dashSpaceSize; } wordIndex += substring.length(); current = finalMessage.get(finalMessage.size() - 1); if(current.length() != 0) { current = new StringBuilder(substring); finalMessage.add(current); } else current.append(substring); if(wordIndex < words[index].length()) current.append("-"); else current.append(" "); } return splitTextIntoLines2(font, maxChatWidth, finalMessage, words, index+1); } else { accumulated = font.getLineWidth(words[index]) + whiteSpaceSize; finalMessage.add(new StringBuilder("")); } } current = finalMessage.get(finalMessage.size() - 1).append(words[index]); if(index < words.length - 1) current.append(" "); } return finalMessage; } // public static void enablePhysicsFor(Spatial spatial) { // spatial.depthFirstTraversal(new SceneGraphVisitor() { // @Override // public void visit(Spatial spatial) { // RigidBodyControl rigid = spatial.getControl(RigidBodyControl.class); // if(rigid != null) { // // rigid.setPhysicsLocation(new Vector3f(0, 2, 0)); // rigid.setEnabled(true); // rigid.activate(); // public static void disablePhysicsFor(Spatial spatial) { // spatial.depthFirstTraversal(new SceneGraphVisitor() { // @Override // public void visit(Spatial spatial) { // RigidBodyControl rigid = spatial.getControl(RigidBodyControl.class); // if(rigid != null) { //// rigid.clearForces(); //// rigid.setApplyPhysicsLocal(true); // rigid.setEnabled(false); public static boolean hasGeometry(Spatial spatial) { if(spatial instanceof Node) { for(Spatial s : ((Node) spatial).getChildren()) { if(hasGeometry(s)) { return true; } } } else { return true; } return false; } public static Spatial getDirectChild(Node node, String childName) { for(Spatial child : ((SafeArrayList<Spatial>)node.getChildren()).getArray()) { if(childName.equals(child.getName())) { return child; } } return null; } public static void offsetMesh(Mesh mesh, Vector3f offset) { FloatBuffer buffer = mesh.getFloatBuffer(VertexBuffer.Type.Position); for(int i = 0; i < buffer.capacity(); i+=3) { buffer.put(i, buffer.get(i) + offset.x); buffer.put(i+1, buffer.get(i+1) + offset.y); buffer.put(i+2, buffer.get(i+2) + offset.z); } mesh.updateBound(); } public static int collidesWithBounds(Collidable other, CollisionResults results, Spatial spatial) { BoundingVolume bv = spatial.getWorldBound(); if(bv == null) { return 0; } int total = bv.collideWith(other, results); if(total != 0) { return total; } if(spatial instanceof Node) { for(Spatial child : ((SafeArrayList<Spatial>)((Node) spatial).getChildren()).getArray()) { total += collidesWithBounds(other, results, child); } } return total; } public static boolean meshEquals(Mesh mesh1, Mesh mesh2) { if(mesh1 == mesh2) { return true; } if(mesh1 == null || mesh2 == null) { return false; } if(mesh1.getVertexCount() != mesh2.getVertexCount()) { return false; } if(mesh1.getTriangleCount() != mesh2.getTriangleCount()) { return false; } if(mesh1.getMode() != mesh2.getMode()) { return false; } Collection<VertexBuffer> buffers1 = mesh1.getBufferList(); Collection<VertexBuffer> buffers2 = mesh2.getBufferList(); if(buffers1.size() != buffers2.size()) { return false; } outer: for(VertexBuffer vertexBuffer1 : buffers1) { for(VertexBuffer vertexBuffer2 : buffers2) { if(vertexBuffer1.getBufferType() == vertexBuffer2.getBufferType()) { if(vertexBuffer1.getFormat() != vertexBuffer2.getFormat()) { return false; } if(vertexBuffer1.getUsage() != vertexBuffer2.getUsage()) { return false; } if(vertexBuffer1.getNumElements() != vertexBuffer2.getNumElements()) { return false; } if(vertexBuffer1.getNumComponents() != vertexBuffer2.getNumComponents()) { return false; } Buffer data1 = vertexBuffer1.getData(); Buffer data2 = vertexBuffer2.getData(); if (data1 instanceof FloatBuffer) { FloatBuffer buf1 = (FloatBuffer) data1; FloatBuffer buf2 = (FloatBuffer) data2; int capacity = buf1.capacity(); for(int i = 0; i < capacity; i++) { if(buf1.get(i) != buf2.get(i)) { return false; } } } else if (data1 instanceof ShortBuffer) { ShortBuffer buf1 = (ShortBuffer) data1; ShortBuffer buf2 = (ShortBuffer) data2; int capacity = buf1.capacity(); for(int i = 0; i < capacity; i++) { if(buf1.get(i) != buf2.get(i)) { return false; } } } else if (data1 instanceof ByteBuffer) { ByteBuffer buf1 = (ByteBuffer) data1; ByteBuffer buf2 = (ByteBuffer) data2; int capacity = buf1.capacity(); for(int i = 0; i < capacity; i++) { if(buf1.get(i) != buf2.get(i)) { return false; } } } else if (data1 instanceof IntBuffer) { IntBuffer buf1 = (IntBuffer) data1; IntBuffer buf2 = (IntBuffer) data2; int capacity = buf1.capacity(); for(int i = 0; i < capacity; i++) { if(buf1.get(i) != buf2.get(i)) { return false; } } } else if (data1 instanceof DoubleBuffer) { DoubleBuffer buf1 = (DoubleBuffer) data1; DoubleBuffer buf2 = (DoubleBuffer) data2; int capacity = buf1.capacity(); for(int i = 0; i < capacity; i++) { if(buf1.get(i) != buf2.get(i)) { return false; } } } else { throw new UnsupportedOperationException(); } continue outer; } } return false; } return true; } }
package com.okta.tools.helpers; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; import com.amazonaws.services.securitytoken.model.AssumeRoleWithSAMLRequest; import com.amazonaws.services.securitytoken.model.AssumeRoleWithSAMLResult; import com.okta.tools.OktaAwsCliEnvironment; import com.okta.tools.models.AccountOption; import com.okta.tools.models.RoleOption; import com.okta.tools.saml.AwsSamlRoleUtils; import com.okta.tools.saml.AwsSamlSigninParser; import org.jsoup.nodes.Document; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class RoleHelper { private OktaAwsCliEnvironment environment; public RoleHelper(OktaAwsCliEnvironment environment) { this.environment = environment; } public AssumeRoleWithSAMLResult assumeChosenAwsRole(AssumeRoleWithSAMLRequest assumeRequest) { BasicAWSCredentials nullCredentials = new BasicAWSCredentials("", ""); AWSCredentialsProvider nullCredentialsProvider = new AWSStaticCredentialsProvider(nullCredentials); AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder .standard() .withRegion(Regions.US_EAST_1) .withCredentials(nullCredentialsProvider) .build(); return sts.assumeRoleWithSAML(assumeRequest); } public AssumeRoleWithSAMLRequest chooseAwsRoleToAssume(String samlResponse) throws IOException { Map<String, String> roleIdpPairs = AwsSamlRoleUtils.getRoles(samlResponse); List<String> roleArns = new ArrayList<>(); String principalArn; String roleArn; if (roleIdpPairs.containsKey(environment.awsRoleToAssume)) { principalArn = roleIdpPairs.get(environment.awsRoleToAssume); roleArn = environment.awsRoleToAssume; } else if (roleIdpPairs.size() > 1) { List<AccountOption> accountOptions = getAvailableRoles(samlResponse); System.out.println("\nPlease choose the role you would like to assume: "); //Gather list of applicable AWS roles int i = 0; int j = -1; for (AccountOption accountOption : accountOptions) { System.out.println(accountOption.accountName); for (RoleOption roleOption : accountOption.roleOptions) { roleArns.add(roleOption.roleArn); System.out.println("\t[ " + (i + 1) + " ]: " + roleOption.roleName); if (roleOption.roleArn.equals(environment.awsRoleToAssume)) { j = i; } i++; } } if ((environment.awsRoleToAssume != null && !environment.awsRoleToAssume.isEmpty()) && j == -1) { System.out.println("No match for role " + environment.awsRoleToAssume); } // Default to no selection final int selection; // If config.properties has matching role, use it and don't prompt user to select if (j >= 0) { selection = j; System.out.println("Selected option " + (j + 1) + " based on OKTA_AWS_ROLE_TO_ASSUME value"); } else { //Prompt user for role selection selection = MenuHelper.promptForMenuSelection(roleArns.size()); } roleArn = roleArns.get(selection); principalArn = roleIdpPairs.get(roleArn); } else { Map.Entry<String, String> role = roleIdpPairs.entrySet().iterator().next(); System.out.println("Auto select role as only one is available : " + role.getKey()); roleArn = role.getKey(); principalArn = role.getValue(); } return new AssumeRoleWithSAMLRequest() .withPrincipalArn(principalArn) .withRoleArn(roleArn) .withSAMLAssertion(samlResponse) .withDurationSeconds(3600); } private List<AccountOption> getAvailableRoles(String samlResponse) throws IOException { Document document = AwsSamlRoleUtils.getSigninPageDocument(samlResponse); return AwsSamlSigninParser.parseAccountOptions(document); } }
package com.frankhpe.gittest; public class Main { public static void main(String [] args) { System.out.println("Hello 777"); System.out.println("Hello 666"); } }
package com.gildedrose; import static java.lang.Math.max; import static java.lang.Math.min; import java.util.HashMap; import java.util.Map; class GildedRose { private static final int DEFAULT_QUALITY_INCREASE_AMOUNT = 1; private static final int DEFAULT_QUALITY_DECAY_AMOUNT = -1; private static final int QUALITY_FLOOR = 0; private static final int QUALITY_CEILING = 50; private static final ItemModifier AGELESS_ITEM_MODIFIER = new ItemModifier(0, 0); private static final ItemModifier BACKSTAGE_PASS_ITEM_MODIFIER = new ItemModifier(DEFAULT_QUALITY_INCREASE_AMOUNT, -1) { public void step(Item item) { adjustQuality(item); if (item.sellIn < 11) { adjustQuality(item); } if (item.sellIn < 6) { adjustQuality(item); } adjustSellIn(item); if (pastSellBy(item)) { item.quality = 0; } } }; private static final ItemModifier ACCRUING_ITEM_MODIFIER = new ItemModifier(DEFAULT_QUALITY_INCREASE_AMOUNT, -1); private static final ItemModifier DECAYING_ITEM_MODIFIER = new ItemModifier(DEFAULT_QUALITY_DECAY_AMOUNT, -1); private static final ItemModifier DOUBLE_DECAYING_ITEM_MODIFIER = new ItemModifier(2 * DEFAULT_QUALITY_DECAY_AMOUNT, -1); private static final String AGED_BRIE = "Aged Brie"; private static final String BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT = "Backstage passes to a TAFKAL80ETC concert"; private static final String SULFURAS_HAND_OF_RAGNAROS = "Sulfuras, Hand of Ragnaros"; private static final String CONJURED_MANA_CAKE = "Conjured Mana Cake"; Item[] items; private static final Map<String, ItemModifier> MODIFIER_MAP = new HashMap<String, ItemModifier>() { private static final long serialVersionUID = -8102026157041850052L; @Override public ItemModifier get(Object key) { return (containsKey(key)) ? super.get(key) : DECAYING_ITEM_MODIFIER; } }; public GildedRose(Item[] items) { this.items = items; MODIFIER_MAP.put(AGED_BRIE, ACCRUING_ITEM_MODIFIER); MODIFIER_MAP.put(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT, BACKSTAGE_PASS_ITEM_MODIFIER); MODIFIER_MAP.put(SULFURAS_HAND_OF_RAGNAROS, AGELESS_ITEM_MODIFIER); MODIFIER_MAP.put(CONJURED_MANA_CAKE, DOUBLE_DECAYING_ITEM_MODIFIER); for (Item item : items) { item.quality = (item.quality < QUALITY_FLOOR) ? QUALITY_FLOOR : item.quality; } } public void updateItems() { for (Item item : items) { ItemModifier modifier = MODIFIER_MAP.get(item.name); modifier.step(item); } } static class ItemModifier { private Integer qualityAdjustment = DEFAULT_QUALITY_DECAY_AMOUNT; private Integer sellInAdjustment = -1; public ItemModifier(Integer qualityAdjustment, Integer sellInAdjustment) { this.qualityAdjustment = qualityAdjustment; this.sellInAdjustment = sellInAdjustment; } protected boolean pastSellBy(Item item) { return item.sellIn < 0; } protected void adjustQuality(Item item) { int newQuality = item.quality + qualityAdjustment; if (isDecaying()) { item.quality = max(QUALITY_FLOOR, newQuality); } else { item.quality = min(QUALITY_CEILING, newQuality); } } private boolean isDecaying() { return qualityAdjustment < 0; } protected void adjustSellIn(Item item) { item.sellIn = item.sellIn + sellInAdjustment; } public void step(Item item) { adjustQuality(item); adjustSellIn(item); if (pastSellBy(item)) { adjustQuality(item); } } } }
package org.hisp.dhis.analytics.table; import static org.hamcrest.CoreMatchers.containsString; import static org.hisp.dhis.DhisConvenienceTest.createProgram; import static org.hisp.dhis.DhisConvenienceTest.createProgramTrackedEntityAttribute; import static org.hisp.dhis.DhisConvenienceTest.createTrackedEntityAttribute; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.hisp.dhis.analytics.AnalyticsTableUpdateParams; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.common.ValueType; import org.hisp.dhis.jdbc.StatementBuilder; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramTrackedEntityAttribute; import org.hisp.dhis.system.database.DatabaseInfo; import org.hisp.dhis.trackedentity.TrackedEntityAttribute; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.util.ReflectionTestUtils; import com.google.common.collect.Lists; /** * @author Luciano Fiandesio */ public class JdbcEnrollmentAnalyticsTableManagerTest { @Mock private IdentifiableObjectManager idObjectManager; @Mock private StatementBuilder statementBuilder; @Mock private DatabaseInfo databaseInfo; @Mock private JdbcTemplate jdbcTemplate; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @InjectMocks private JdbcEnrollmentAnalyticsTableManager subject; @Before public void setUp() { ReflectionTestUtils.setField( subject, "statementBuilder", statementBuilder ); when( jdbcTemplate.queryForList( "select distinct(extract(year from psi.executiondate)) from programstageinstance psi inner join programinstance pi on psi.programinstanceid = pi.programinstanceid where pi.programid = 0 and psi.executiondate is not null and psi.deleted is false and psi.executiondate >= '2018-01-01'", Integer.class ) ).thenReturn( Lists.newArrayList( 2018, 2019 ) ); } @Test public void verifyTeiTypeOrgUnitFetchesOuNameWhenPopulatingEventAnalyticsTable() { ArgumentCaptor<String> sql = ArgumentCaptor.forClass( String.class ); when( databaseInfo.isSpatialSupport() ).thenReturn( true ); Program p1 = createProgram( 'A' ); TrackedEntityAttribute tea = createTrackedEntityAttribute( 'a', ValueType.ORGANISATION_UNIT ); tea.setId( 9999 ); ProgramTrackedEntityAttribute programTrackedEntityAttribute = createProgramTrackedEntityAttribute( p1, tea ); p1.setProgramAttributes( Lists.newArrayList( programTrackedEntityAttribute ) ); when( idObjectManager.getAllNoAcl( Program.class ) ).thenReturn( Lists.newArrayList( p1 ) ); AnalyticsTableUpdateParams params = AnalyticsTableUpdateParams.newBuilder().withLastYears( 2 ).build(); subject.populateTable( params, PartitionUtils.getTablePartitions( subject.getAnalyticsTables( params ) ).get( 0 ) ); verify( jdbcTemplate ).execute( sql.capture() ); String ouQuery = "(select ou.name from organisationunit ou where ou.uid = " + "(select value from trackedentityattributevalue where trackedentityinstanceid=pi.trackedentityinstanceid and " + "trackedentityattributeid=9999)) as \"" + tea.getUid() + "\""; assertThat( sql.getValue(), containsString( ouQuery ) ); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-07-18"); this.setApiVersion("16.7.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package ma.glasnost.orika.test.favorsextension; import ma.glasnost.orika.MapperFacade; import ma.glasnost.orika.MapperFactory; import ma.glasnost.orika.impl.DefaultMapperFactory; import ma.glasnost.orika.test.MappingUtil; import org.junit.Assert; import org.junit.Test; public class FavorsExtensionTestCase { @Test public void favorsExtension() throws Throwable { MapperFactory factory = MappingUtil.getMapperFactory(); factory.classMap(Animal.class, AnimalDto.class) .field("category", "type") .field("name", "qualifier") .favorExtension(true) .register(); MapperFacade mapper = factory.getMapperFacade(); Bird src = new Bird(); src.category = "falcon"; src.name = "Falcor"; src.wingSpanInCm = 120; BirdDto dest = mapper.map(src, BirdDto.class); Assert.assertEquals(src.category, dest.type); Assert.assertEquals(src.name, dest.qualifier); Assert.assertEquals(src.wingSpanInCm, dest.wingSpanInCm); Cat cat = new Cat(); cat.category = "tiger"; cat.name = "Tigger"; cat.striped = true; CatDto dest2 = mapper.map(cat, CatDto.class); Assert.assertEquals(cat.category, dest2.type); Assert.assertEquals(cat.name, dest2.qualifier); Assert.assertEquals(cat.striped, dest2.striped); } @Test public void favorsExtensionGlobally() throws Throwable { MapperFactory factory = new DefaultMapperFactory.Builder().favorExtension(true).build(); factory.classMap(Animal.class, AnimalDto.class) .field("category", "type") .field("name", "qualifier") .register(); MapperFacade mapper = factory.getMapperFacade(); Bird src = new Bird(); src.category = "falcon"; src.name = "Falcor"; src.wingSpanInCm = 120; BirdDto dest = mapper.map(src, BirdDto.class); Assert.assertEquals(src.category, dest.type); Assert.assertEquals(src.name, dest.qualifier); Assert.assertEquals(src.wingSpanInCm, dest.wingSpanInCm); Cat cat = new Cat(); cat.category = "tiger"; cat.name = "Tigger"; cat.striped = true; CatDto dest2 = mapper.map(cat, CatDto.class); Assert.assertEquals(cat.category, dest2.type); Assert.assertEquals(cat.name, dest2.qualifier); Assert.assertEquals(cat.striped, dest2.striped); } @Test public void favorsExtensionMultiLevel() throws Throwable { MapperFactory factory = new DefaultMapperFactory.Builder().favorExtension(true).build(); factory.classMap(Animal.class, AnimalDto.class) .field("category", "type") .field("name", "qualifier") .register(); factory.classMap(Reptile.class, ReptileDto.class) .field("weightInKg", "weightKg") .register(); MapperFacade mapper = factory.getMapperFacade(); Salamander src = new Salamander(); src.category = "falcon"; src.name = "Falcor"; src.tailLengthInCm = 23.0f; src.weightInKg = 12.5f; SalamanderDto dest = mapper.map(src, SalamanderDto.class); Assert.assertEquals(src.category, dest.type); Assert.assertEquals(src.name, dest.qualifier); Assert.assertEquals(src.weightInKg, dest.weightKg, 0.1); Assert.assertEquals(src.tailLengthInCm, dest.tailLengthInCm, 0.1); } @Test public void withoutFavorsExtension() throws Throwable { /* * Note: without using 'favorsExtension', the result is that Orika * uses the Animal <-> AnimalDto mapping that was registered without * generating a dynamic mapping for the downstream classes */ MapperFactory factory = MappingUtil.getMapperFactory(); factory.classMap(Animal.class, AnimalDto.class) .field("category", "type") .field("name", "qualifier") .register(); MapperFacade mapper = factory.getMapperFacade(); Bird src = new Bird(); src.category = "falcon"; src.name = "Falcor"; src.wingSpanInCm = 120; BirdDto dest = mapper.map(src, BirdDto.class); Assert.assertEquals(src.category, dest.type); Assert.assertEquals(src.name, dest.qualifier); Assert.assertNotEquals(src.wingSpanInCm, dest.wingSpanInCm); Cat cat = new Cat(); cat.category = "tiger"; cat.name = "Tigger"; cat.striped = true; CatDto dest2 = mapper.map(cat, CatDto.class); Assert.assertEquals(cat.category, dest2.type); Assert.assertEquals(cat.name, dest2.qualifier); Assert.assertNotEquals(cat.striped, dest2.striped); /* * But after we explicitly register the mapping, and * declare that it should 'use' the Animal to AnimalDto * mapper, it works as expected */ factory.classMap(Bird.class, BirdDto.class) .byDefault() .use(Animal.class, AnimalDto.class) .register(); dest = mapper.map(src, BirdDto.class); Assert.assertEquals(src.category, dest.type); Assert.assertEquals(src.name, dest.qualifier); Assert.assertEquals(src.wingSpanInCm, dest.wingSpanInCm); } public static class Animal { public String category; public String name; } public static class Bird extends Animal { public int wingSpanInCm; } public static class Cat extends Animal { public boolean striped; } public static class Reptile extends Animal { public float weightInKg; } public static class Salamander extends Reptile { public float tailLengthInCm; } public static class AnimalDto { public String type; public String qualifier; } public static class BirdDto extends AnimalDto { public int wingSpanInCm; } public static class CatDto extends AnimalDto { public boolean striped; } public static class ReptileDto extends AnimalDto { public float weightKg; } public static class SalamanderDto extends ReptileDto { public float tailLengthInCm; } }
package org.safehaus.subutai.api.templateregistry; import java.util.ArrayList; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.gson.annotations.Expose; /** * Template represents template entry in registry */ public class Template { public static final String MASTER_TEMPLATE_NAME = "master"; private static Template masterTemplate = new Template(); //name of template @Expose private String templateName; //name of parent template @Expose private String parentTemplateName; //lxc architecture e.g. amd64, i386 @Expose private String lxcArch; //lxc container name @Expose private String lxcUtsname; //path to cfg files tracked by subutai @Expose private String subutaiConfigPath; //path to app data files tracked by subutai @Expose private String subutaiAppdataPath; //name of parent template @Expose private String subutaiParent; //name of git branch where template cfg files are versioned @Expose private String subutaiGitBranch; //id of git commit which pushed template cfg files to git @Expose private String subutaiGitUuid; //contents of packages manifest file private String packagesManifest; @Expose private List<Template> children; public Template( final String lxcArch, final String lxcUtsname, final String subutaiConfigPath, final String subutaiAppdataPath, final String subutaiParent, final String subutaiGitBranch, final String subutaiGitUuid, final String packagesManifest ) { Preconditions.checkArgument( !Strings.isNullOrEmpty( lxcUtsname ), "Missing lxc.utsname parameter" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( lxcArch ), "Missing lxc.arch parameter" ); Preconditions .checkArgument( !Strings.isNullOrEmpty( subutaiConfigPath ), "Missing subutai.config.path parameter" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( subutaiAppdataPath ), "Missing subutai.app.data.path parameter" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( subutaiParent ), "Missing subutai.parent parameter" ); Preconditions .checkArgument( !Strings.isNullOrEmpty( subutaiGitBranch ), "Missing subutai.git.branch parameter" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( subutaiGitUuid ), "Missing subutai.git.uuid parameter" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( packagesManifest ), "Missing packages manifest" ); this.lxcArch = lxcArch; this.lxcUtsname = lxcUtsname; this.subutaiConfigPath = subutaiConfigPath; this.subutaiAppdataPath = subutaiAppdataPath; this.subutaiParent = subutaiParent; this.subutaiGitBranch = subutaiGitBranch; this.subutaiGitUuid = subutaiGitUuid; this.packagesManifest = packagesManifest; this.templateName = lxcUtsname; this.parentTemplateName = subutaiParent; } private Template() { templateName = MASTER_TEMPLATE_NAME; } public static Template getMasterTemplate() { return masterTemplate; } public void addChildren( List<Template> children ) { if ( this.children == null ) { this.children = new ArrayList<>(); } this.children.addAll( children ); } public String getLxcArch() { return lxcArch; } public String getLxcUtsname() { return lxcUtsname; } public String getSubutaiConfigPath() { return subutaiConfigPath; } public String getSubutaiAppdataPath() { return subutaiAppdataPath; } public String getSubutaiParent() { return subutaiParent; } public String getSubutaiGitBranch() { return subutaiGitBranch; } public String getSubutaiGitUuid() { return subutaiGitUuid; } public String getPackagesManifest() { return packagesManifest; } public String getTemplateName() { return templateName; } public String getParentTemplateName() { return parentTemplateName; } @Override public String toString() { return "Template{" + "templateName='" + templateName + '\'' + ", parentTemplateName='" + parentTemplateName + '\'' + ", lxcArch='" + lxcArch + '\'' + ", lxcUtsname='" + lxcUtsname + '\'' + ", subutaiConfigPath='" + subutaiConfigPath + '\'' + ", subutaiAppdataPath='" + subutaiAppdataPath + '\'' + ", subutaiParent='" + subutaiParent + '\'' + ", subutaiGitBranch='" + subutaiGitBranch + '\'' + ", subutaiGitUuid='" + subutaiGitUuid + '\'' + '}'; } }
package org.a11y.brlapi; public abstract class Client extends Program { private final ConnectionSettings connectionSettings = new ConnectionSettings(); public final Client setServerHost (String host) { connectionSettings.setServerHost(host); return this; } public final Client setAuthorizationSchemes (String schemes) { connectionSettings.setAuthorizationSchemes(schemes); return this; } protected Client (String... arguments) { super(arguments); addOption("server", (operands) -> { setServerHost(operands[0]); }, "host specification" ); addOption("authorization", (operands) -> { setAuthorizationSchemes(operands[0]); }, "authorization scheme(s)" ); } protected interface ClientTask { public void run (Connection connection); } private final void connect (ClientTask task) { try { Connection connection = new Connection(connectionSettings); try { task.run(connection); } finally { connection.close(); connection = null; } } catch (ConnectionError error) { internalError(("connection error: " + error)); } } protected abstract void runClient (Connection connection); @Override protected final void runProgram () { connect( (connection) -> { runClient(connection); } ); } protected final void ttyMode (Connection connection, String driver, int[] path, ClientTask task) { try { connection.enterTtyModeWithPath(driver, path); try { task.run(connection); } finally { connection.leaveTtyMode(); } } catch (ConnectionError error) { internalError(("tty mode error: " + error)); } } protected final void ttyMode (Connection connection, boolean keys, int[] path, ClientTask task) { ttyMode(connection, (keys? connection.getDriverName(): null), path, task); } protected final void rawMode (Connection connection, String driver, ClientTask task) { try { connection.enterRawMode(driver); try { task.run(connection); } finally { connection.leaveRawMode(); } } catch (ConnectionError error) { internalError(("raw mode error: " + error)); } } protected final void rawMode (Connection connection, ClientTask task) { rawMode(connection, connection.getDriverName(), task); } protected final Parameter getParameter (Connection connection, String name) { Parameter parameter = connection.getParameters().get(name); if (parameter == null) { semanticError("unknown parameter: %s", name); } return parameter; } }
package com.rarchives.ripme.ui; import java.awt.Color; import java.awt.Container; import java.awt.Desktop; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.Observable; import java.util.Observer; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import org.apache.log4j.Logger; import com.rarchives.ripme.ripper.AbstractRipper; import com.rarchives.ripme.utils.Utils; /** * Everything UI-related starts and ends here. */ public class MainWindow implements Runnable, RipStatusHandler { private static final Logger logger = Logger.getLogger(MainWindow.class); private static final String WINDOW_TITLE = "RipMe"; private static final String HISTORY_FILE = ".history"; private static JFrame mainFrame; private static JTextField ripTextfield; private static JButton ripButton; private static JLabel statusLabel; private static JButton openButton; private static JProgressBar statusProgress; // Log private static JButton optionLog; private static JPanel logPanel; private static JTextPane logText; private static JScrollPane logTextScroll; // History private static JButton optionHistory; private static JPanel historyPanel; private static JList historyList; private static DefaultListModel historyListModel; private static JScrollPane historyListScroll; private static JPanel historyButtonPanel; private static JButton historyButtonRemove, historyButtonClear, historyButtonRerip; // Configuration private static JButton optionConfiguration; private static JPanel configurationPanel; // TODO Configuration components public MainWindow() { mainFrame = new JFrame(WINDOW_TITLE); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //mainFrame.setPreferredSize(new Dimension(400, 180)); //mainFrame.setResizable(false); mainFrame.setLayout(new GridBagLayout()); createUI(mainFrame.getContentPane()); loadHistory(); setupHandlers(); } public void run() { mainFrame.pack(); mainFrame.setLocationRelativeTo(null); mainFrame.setVisible(true); } private void status(String text) { statusLabel.setText(text); mainFrame.pack(); } private void createUI(Container pane) { EmptyBorder emptyBorder = new EmptyBorder(5, 5, 5, 5); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 2; gbc.ipadx = 2; gbc.gridx = 0; gbc.weighty = 2; gbc.ipady = 2; gbc.gridy = 0; ripTextfield = new JTextField("", 20); ripButton = new JButton("Rip"); JPanel ripPanel = new JPanel(new GridBagLayout()); ripPanel.setBorder(emptyBorder); gbc.gridx = 0; ripPanel.add(new JLabel("URL:", JLabel.RIGHT), gbc); gbc.gridx = 1; ripPanel.add(ripTextfield, gbc); gbc.gridx = 2; ripPanel.add(ripButton, gbc); statusLabel = new JLabel("Inactive"); statusLabel.setHorizontalAlignment(JLabel.CENTER); openButton = new JButton(); openButton.setVisible(false); JPanel statusPanel = new JPanel(new GridBagLayout()); statusPanel.setBorder(emptyBorder); gbc.gridx = 0; statusPanel.add(statusLabel, gbc); statusPanel.add(openButton, gbc); JPanel progressPanel = new JPanel(new GridBagLayout()); progressPanel.setBorder(emptyBorder); statusProgress = new JProgressBar(0, 100); progressPanel.add(statusProgress, gbc); JPanel optionsPanel = new JPanel(new GridBagLayout()); optionsPanel.setBorder(emptyBorder); optionLog = new JButton("Log"); optionHistory = new JButton("History"); optionConfiguration = new JButton("Configuration"); gbc.gridx = 0; optionsPanel.add(optionLog, gbc); gbc.gridx = 1; optionsPanel.add(optionHistory, gbc); gbc.gridx = 2; optionsPanel.add(optionConfiguration, gbc); logPanel = new JPanel(new GridBagLayout()); logPanel.setBorder(emptyBorder); logText = new JTextPaneNoWrap(); logTextScroll = new JScrollPane(logText); logPanel.setVisible(false); logPanel.setPreferredSize(new Dimension(300, 250)); logPanel.add(logTextScroll, gbc); historyPanel = new JPanel(new GridBagLayout()); historyPanel.setBorder(emptyBorder); historyPanel.setVisible(false); historyPanel.setPreferredSize(new Dimension(300, 250)); historyListModel = new DefaultListModel(); historyList = new JList(historyListModel); historyList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); historyListScroll = new JScrollPane(historyList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); historyButtonRemove = new JButton("Remove"); historyButtonClear = new JButton("Clear"); historyButtonRerip = new JButton("Re-rip All"); gbc.gridx = 0; JPanel historyListPanel = new JPanel(new GridBagLayout()); historyListPanel.add(historyListScroll, gbc); historyPanel.add(historyListPanel, gbc); historyButtonPanel = new JPanel(new GridBagLayout()); historyButtonPanel.setPreferredSize(new Dimension(300, 10)); historyButtonPanel.setBorder(emptyBorder); gbc.gridx = 0; historyButtonPanel.add(historyButtonRemove, gbc); gbc.gridx = 1; historyButtonPanel.add(historyButtonClear, gbc); gbc.gridx = 2; historyButtonPanel.add(historyButtonRerip, gbc); gbc.gridy = 1; gbc.gridx = 0; historyPanel.add(historyButtonPanel, gbc); configurationPanel = new JPanel(new GridBagLayout()); configurationPanel.setBorder(emptyBorder); configurationPanel.setVisible(false); configurationPanel.setPreferredSize(new Dimension(300, 250)); // TODO Configuration components gbc.gridy = 0; pane.add(ripPanel, gbc); gbc.gridy = 1; pane.add(statusPanel, gbc); gbc.gridy = 2; pane.add(progressPanel, gbc); gbc.gridy = 3; pane.add(optionsPanel, gbc); gbc.gridy = 4; pane.add(logPanel, gbc); gbc.gridy = 5; pane.add(historyPanel, gbc); gbc.gridy = 5; pane.add(configurationPanel, gbc); } private void setupHandlers() { ripButton.addActionListener(new RipButtonHandler()); optionLog.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { logPanel.setVisible(!logPanel.isVisible()); historyPanel.setVisible(false); configurationPanel.setVisible(false); mainFrame.pack(); } }); optionHistory.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { logPanel.setVisible(false); historyPanel.setVisible(!historyPanel.isVisible()); configurationPanel.setVisible(false); mainFrame.pack(); } }); optionConfiguration.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { logPanel.setVisible(false); historyPanel.setVisible(false); configurationPanel.setVisible(!configurationPanel.isVisible()); mainFrame.pack(); } }); historyButtonRemove.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int[] indices = historyList.getSelectedIndices(); for (int i = indices.length - 1; i >= 0; i historyListModel.remove(indices[i]); } saveHistory(); } }); historyButtonClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { historyListModel.clear(); saveHistory(); } }); // Re-rip all history historyButtonRerip.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Runnable ripAllThread = new Runnable() { @Override public void run() { historyButtonPanel.setEnabled(false); historyList.setEnabled(false); for (int i = 0; i < historyListModel.size(); i++) { historyList.clearSelection(); historyList.setSelectedIndex(i); Thread t = ripAlbum( (String) historyListModel.get(i) ); try { synchronized (t) { t.wait(); } t.join(); } catch (InterruptedException e) { logger.error("[!] Exception while waiting for ripper to finish:", e); } } historyList.setEnabled(true); historyButtonPanel.setEnabled(true); } }; new Thread(ripAllThread).start(); } }); } private void appendLog(final String text, final Color color) { SimpleAttributeSet sas = new SimpleAttributeSet(); StyleConstants.setForeground(sas, color); StyledDocument sd = logText.getStyledDocument(); try { sd.insertString(sd.getLength(), text + "\n", sas); } catch (BadLocationException e) { } logText.setCaretPosition(sd.getLength()); } private void loadHistory() { File f; FileReader fr = null; BufferedReader br; try { f = new File(HISTORY_FILE); fr = new FileReader(f); br = new BufferedReader(fr); String line; while ( (line = br.readLine()) != null ) { if (!line.trim().equals("")) { historyListModel.addElement(line.trim()); } } } catch (FileNotFoundException e) { // Do nothing } catch (IOException e) { logger.error("[!] Error while loading history file " + HISTORY_FILE, e); } finally { try { if (fr != null) { fr.close(); } } catch (IOException e) { } } } private void saveHistory() { FileWriter fw = null; try { fw = new FileWriter(HISTORY_FILE, false); for (int i = 0; i < historyListModel.size(); i++) { fw.write( (String) historyListModel.get(i) ); fw.write("\n"); fw.flush(); } } catch (IOException e) { logger.error("[!] Error while saving history file " + HISTORY_FILE, e); } finally { try { if (fw != null) { fw.close(); } } catch (IOException e) { } } } private Thread ripAlbum(String urlString) { URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { logger.error("[!] Could not generate URL for '" + urlString + "'", e); status("Error: " + e.getMessage()); return null; } ripButton.setEnabled(false); ripTextfield.setEnabled(false); statusProgress.setValue(100); openButton.setVisible(false); statusLabel.setVisible(true); mainFrame.pack(); try { AbstractRipper ripper = AbstractRipper.getRipper(url); ripTextfield.setText(ripper.getURL().toExternalForm()); ripper.setObserver((RipStatusHandler) this); Thread t = new Thread(ripper); t.start(); return t; } catch (Exception e) { logger.error("[!] Error while ripping: " + e.getMessage(), e); status("Error: " + e.getMessage()); return null; } } class RipButtonHandler implements ActionListener { public void actionPerformed(ActionEvent event) { ripAlbum(ripTextfield.getText()); } } private class StatusEvent implements Runnable { private final AbstractRipper ripper; private final RipStatusMessage msg; public StatusEvent(AbstractRipper ripper, RipStatusMessage msg) { this.ripper = ripper; this.msg = msg; } public void run() { handleEvent(this); } } private void handleEvent(StatusEvent evt) { RipStatusMessage msg = evt.msg; int completedPercent = evt.ripper.getCompletionPercentage(); statusProgress.setValue(completedPercent); status( evt.ripper.getStatusText() ); switch(msg.getStatus()) { case LOADING_RESOURCE: case DOWNLOAD_STARTED: appendLog( "Downloading: " + (String) msg.getObject(), Color.BLACK); break; case DOWNLOAD_COMPLETE: appendLog( "Completed: " + (String) msg.getObject(), Color.GREEN); break; case DOWNLOAD_ERRORED: appendLog( "Error: " + (String) msg.getObject(), Color.RED); break; case DOWNLOAD_WARN: appendLog( "Warn: " + (String) msg.getObject(), Color.ORANGE); break; case RIP_COMPLETE: if (!historyListModel.contains(ripTextfield.getText())) { historyListModel.addElement(ripTextfield.getText()); } saveHistory(); ripButton.setEnabled(true); ripTextfield.setEnabled(true); statusProgress.setValue(100); statusLabel.setVisible(false); openButton.setVisible(true); File f = (File) msg.getObject(); String prettyFile = Utils.removeCWD(f); openButton.setText("Open " + prettyFile); appendLog( "Rip complete, saved to " + prettyFile, Color.GREEN); openButton.setActionCommand(f.toString()); openButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { try { Desktop.getDesktop().open(new File(event.getActionCommand())); } catch (Exception e) { logger.error(e); } } }); mainFrame.pack(); } } public void update(AbstractRipper ripper, RipStatusMessage message) { StatusEvent event = new StatusEvent(ripper, message); SwingUtilities.invokeLater(event); } /** Simple TextPane that allows horizontal scrolling. */ class JTextPaneNoWrap extends JTextPane { private static final long serialVersionUID = 1L; @Override public boolean getScrollableTracksViewportWidth() { return false; } } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-03-24"); this.setApiVersion("15.19.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package de.thingweb.repository; import java.util.List; import java.lang.String; import java.lang.Boolean; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.HashMap; import java.net.URI; import java.io.ByteArrayInputStream; import de.thingweb.repository.rest.RESTServerInstance; import de.thingweb.repository.ThingDescriptionCollectionHandler; import org.eclipse.californium.core.CoapClient; import org.eclipse.californium.core.CoapHandler; import org.eclipse.californium.core.CoapObserveRelation; import org.eclipse.californium.core.CoapResponse; //import org.eclipse.californium.coap.MediaTypeRegistry; /** @brief Observe the ResourceDirectory Server to import Thing Descriptions. * * This class sets a CoAP client that will observe the specified * ResourceDirectory URI in order to import Thing Descriptions of those things * that register to it. When a thing is registered in the Resource Directory, * an observation event occurs that sends the URI of that new thing to the * observers. This class uses that URI to GET the thing description. * * In the same way, when a thing is no longer registered in the Resource * Directory, an observation event occurs and the thing description is * deleted from the database. A deregistered thing is identified because its * URI would not be found in the ResourceDirectory response. * */ public class ResourceDirectoryObserver { private String rd_uri; private String td_uri; private CoapObserveRelation relation; private CoapClient client; private HashMap<String, Boolean> things_map; // keeps track of the updates in the RD private HashMap<String, String> things_uris; // keeps track of the registered things private final String url_re = "(coap?|http)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; private List<RESTServerInstance> servers; public ResourceDirectoryObserver(String uri, List<RESTServerInstance> srvs) { rd_uri = uri; //td_uri = "coap://localhost:5683/"; td_uri = "http: servers = srvs; client = new CoapClient(rd_uri + "/rd"); things_map = new HashMap<String, Boolean>(); things_uris = new HashMap<String, String>(); // load thing_uris with the URIs stored in the repository's database for (String td_uri: ThingDescriptionUtils.listThingDescriptionsUri()) { System.out.println(td_uri); this.things_uris.put(td_uri, td_uri); } // observing relation = client.observe( new CoapHandler() { @Override public void onLoad(CoapResponse response) { String content = response.getResponseText(); System.out.println(content); // Extract the url's Matcher m = Pattern.compile(url_re).matcher(content); things_map.clear(); while (m.find()) { String thing_url = m.group(); things_map.put(thing_url, true); // Check if a new resource registers if (!things_uris.containsKey(thing_url)) { // Get TD System.out.println(thing_url); CoapClient cli = new CoapClient(thing_url); cli.get(new CoapHandler() { @Override public void onLoad(CoapResponse response) { String content = response.getResponseText(); System.out.println(content); // Add TD ThingDescriptionCollectionHandler tdch = new ThingDescriptionCollectionHandler(servers); try { tdch.post(new URI(td_uri + "/td"), null, new ByteArrayInputStream(response.getPayload())); } catch (Exception e) { System.err.println(e.getMessage()); } } @Override public void onError() { System.err.println("Failed"); } }); } } // Check if a known resource has deregistered, if so remove TD removeDeregisteredThingDescriptions(); } @Override public void onError() { System.err.println("Failed"); } }); //relation.proactiveCancel(); } /** * @brief Removes deregistered thing descriptions from the repository's database. * * First, checks if a resource has deregistered from the Resource Directory. * If deregistered, then deletes it from the database. */ private void removeDeregisteredThingDescriptions() { for (String uri : this.things_uris.keySet()) { if (!this.things_map.containsKey(uri)) { String source_id = ""; try { source_id = ThingDescriptionUtils.getThingDescriptionIdFromUri(uri); System.out.println("Removing description with id " + source_id); // delete the thing description ThingDescriptionHandler tdh = new ThingDescriptionHandler(source_id, servers); try { tdh.delete(new URI(source_id), null, null); this.things_uris.remove(uri); System.out.println("Successfully removed description of URI " + uri); } catch (Exception e) { System.err.println(e.getMessage()); } } catch (Exception e) { System.err.println(e.getMessage()); } } } } }
package com.rultor.maven.plugin; import com.jcabi.aspects.Loggable; import com.jcabi.log.Logger; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.maven.execution.ExecutionListener; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.InstantiationStrategy; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; /** * Steps Mojo. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 0.1 */ @ToString @Mojo( name = "steps", defaultPhase = LifecyclePhase.INITIALIZE, requiresProject = true, threadSafe = true, instantiationStrategy = InstantiationStrategy.SINGLETON ) @EqualsAndHashCode(callSuper = false) @Loggable(Loggable.DEBUG) public final class StepsMojo extends AbstractMojo { /** * Maven session, to be injected by Maven itself. */ @Component private transient MavenSession session; /** * Maven project, to be injected by Maven itself. * @since 0.3 */ @Component private transient MavenProject project; /** * Skip execution. * @since 0.3 */ @Parameter(property = "rultor.skip", defaultValue = "true") private transient boolean skip; /** * Listener already injected. * @since 0.3 */ private transient boolean injected; @Override public void execute() { if (this.injected) { Logger.info(this, "Xembly listener already injected"); } else if (this.skip) { Logger.info(this, "Execution skipped, use -Drultor.skip=false"); } else { this.inject(); Logger.info(this, "Xembly execution listener injected"); } } /** * Set session. * @param ssn Session to set. */ public void setSession(final MavenSession ssn) { this.session = ssn; } /** * Set project. * @param prj Project to inject * @since 0.3 */ public void setProject(final MavenProject prj) { this.project = prj; } /** * Inject listener. * @since 0.3 */ private void inject() { final MavenExecutionRequest request = this.session.getRequest(); ExecutionListener listener = request.getExecutionListener(); if (this.project.getModules().isEmpty()) { listener = new XemblyMojos(listener); } else { listener = new XemblyProjects(listener); } request.setExecutionListener(listener); this.injected = true; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-10-03"); this.setApiVersion("18.15.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param language language */ public void setLanguage(String language){ this.requestConfiguration.put("language", language); } /** * language * * @return String */ public String getLanguage(){ if(this.requestConfiguration.containsKey("language")){ return(String) this.requestConfiguration.get("language"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package com.senac.petshop.rnval; import com.senac.petshop.bean.Dono; import com.senac.petshop.infra.ValidacaoRN; import com.senac.petshop.infra.ValidacaoRNException; /** * * @author lossurdo */ public class DonoRNVal implements ValidacaoRN<Dono> { @Override public void validarSalvar(Dono bean) { if (bean.getCpf() == null) { throw new ValidacaoRNException("Campo CPF não informado"); } if (bean.getNome() == null) { throw new ValidacaoRNException("Campo Nome não informado"); } if (bean.getTelefoneCelular() == null) { throw new ValidacaoRNException("Campo Telefone Celular não informado"); } } @Override public void validarExcluir(Dono bean) { validarConsultar(bean); } @Override public void validarConsultar(Dono bean) { if (bean.getCodigo() == null) { throw new ValidacaoRNException("Campo Código não informado"); } } @Override public void validarAlterar(Dono bean) { validarConsultar(bean); } }
public class Game { private int rolls[] = new int[21]; private int currentRoll = 0; public void roll(int pins) { rolls[currentRoll++] = pins; } public int score() { int score = 0; int frameIndex = 0; for (int frame = 0; frame < 10; frame++) { if (rolls[frameIndex] + rolls[frameIndex + 1] == 10) { //spare score += 10 + rolls[frameIndex + 2]; } else { score += rolls[frameIndex] + rolls[frameIndex + 1]; } frameIndex += 2; } return score; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:17-11-27"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package com.sentenial.ws.service; import com.sentenial.ws.client.AuthHandler; import javax.xml.ws.BindingProvider; import javax.xml.ws.Service; import javax.xml.ws.handler.Handler; import javax.xml.ws.handler.HandlerResolver; import javax.xml.ws.handler.PortInfo; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; /** * * @param <T> */ public final class WsHelper<T extends Service> { public <I> I buildWsClient(T wsServiceImplementation, Class<I> ifaceImplementationClass){ return buildWsClient(wsServiceImplementation, ifaceImplementationClass,new ArrayList<Handler>(), new HashMap<String,Object>()); } public <I> I buildWsClient(T wsServiceImplementation, Class<I> ifaceImplementationClass, final List<Handler>extraHandlers, Map<String,Object> ctxSettings){ final WsSettings settings = WsSettingsLoader.loadSettings(); wsServiceImplementation.setHandlerResolver(new HandlerResolver() { @Override public List<Handler> getHandlerChain(PortInfo portInfo) { final List<Handler> handlerList = new ArrayList<Handler>(); handlerList.add(new AuthHandler(settings.getUsername(), settings.getPassword())); handlerList.addAll(extraHandlers); return handlerList; } }); final I serviceIface = wsServiceImplementation.getPort(ifaceImplementationClass); final BindingProvider bindingProvider = (BindingProvider) serviceIface; final Map<String, Object> req_ctx = bindingProvider.getRequestContext(); req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, settings.getWsUrl()); req_ctx.putAll(ctxSettings); bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, settings.getWsUrl()); return serviceIface; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-05-13"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package me.zombieranke.Schatttenwanderer; import java.io.IOException; import java.util.ArrayList; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.Music; import org.newdawn.slick.SavedState; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.state.transition.FadeInTransition; import org.newdawn.slick.state.transition.FadeOutTransition; import org.newdawn.slick.util.pathfinding.AStarPathFinder; /**The basic game Logic that every Level must extend*/ public abstract class LevelHandler extends BasicGameState { /**The index where the levels start(allows virtual IDs of level)*/ protected static final int levelOffset = 5; /**Indicates the number of the level (levelOffset + levelCount = levelID)*/ protected int levelNumber; public static int levelCount; /**The Player*/ protected Player player; /**The target that the player has to kill*/ protected Target target; /**The exit that the player has to escape through*/ protected Exit exit; protected int watchSpeed; protected boolean sneaking; /**A boolean indicating whether the alarm is currently active*/ protected boolean alarm; /**The remaining alarm time*/ protected int alarmTime; /**The default time that an alarm lasts*/ protected static final int alarmTimeDefault = 600; /**A variable to track how long the player stood in the WatchSightArea*/ protected int gracePeriod; /**Keeps track when the player last get out of stealth*/ protected int stealthCooldown; /**Default time it takes for a lever to reset in alarm situations*/ protected static final int leverResetTimeDefault = 150; /**The remaining time until all levers reset*/ protected int leverResetTime = 0; protected ArrayList<Watch> watches; /**Everything that cannot be trespassed*/ protected ArrayList<SolidObject> solids = new ArrayList<SolidObject>(); /**All lasers in the level * @see Laser */ protected ArrayList<Laser> laser; /**All levers in the level * @see Lever */ protected ArrayList<Lever> lever; /**Indicates if we are in debug view(shows all hitboxes)*/ private boolean debug; /**Indicates which direction the player looks(use with caution)*/ private int state; /**Indicates whether the player has succeeded in his mission(killed the target)*/ private boolean mission; /**The music to play when there is an alarm*/ protected Music alarmMusic; /**The music to play when there is no alarm*/ protected Music gameMusic; protected Music endMusic; /**The sound to play when the exit opens*/ protected Sound exitSound; /**The sound to play when the player flicks a lever*/ protected Sound leverSound; /** Background Image */ protected Image game_background; /** Background for the "outer layer"/UI Elements outside of boundaries as a tile */ protected Image UI_Background; protected LevelMap levelMap; protected AStarPathFinder aPath; protected void renderSpecific(GameContainer container, StateBasedGame game, Graphics g){} protected void updateSpecific(GameContainer container, StateBasedGame game, int delta){} /**Reset everything that is the same between levels*/ public void reset() { alarm = false; laser = new ArrayList<Laser>(); lever = new ArrayList<Lever>(); watches = new ArrayList<Watch>(); debug = false; state = 1; mission = false; exit.setOpen(false); exit.animation.setCurrentFrame(0); } /**Function to reload stuff on level leave * * @param container The container holding the game */ public abstract void onLeave(GameContainer container) throws SlickException; /**Initialize all game objects to be able to use them later * * @param container The container holding the game * @throws SlickException */ public void initObjects(GameContainer container) throws SlickException { for(Laser l : laser) { l.init(container.getWidth(),container.getHeight(),solids); } for(Lever l : lever) { l.init(); } for(Watch w: watches) { w.init(solids); w.setRotation(w.getDirection()+180); w.setMoving(false); w.setNoise(w.getNoiseDefault()); } player.setHealth(); player.setEnergy(); player.setRotation(0); target.animation.setCurrentFrame(2); target.animation.stop(); exit.animation.setCurrentFrame(0); exit.animation.stop(); player.setMoving(false); } /** Used to reset the Level when exiting * * @param container The container holding the game * @param game The game holding this state * @throws SlickException */ public void resetOnLeave(GameContainer container, StateBasedGame game) throws SlickException { if(levelCount<levelNumber) { levelCount = levelNumber; } reset(); onLeave(container); } @Override public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { renderSpecific(container,game,g); UI_Background.draw(0, 0); game_background.draw(100, 100); g.setColor(Color.black); g.drawString("Bewegung: Pfeiltasten\nSchalter betätigen: F\nStealth: C\nSprint: V", 40, 20); g.drawString("Schleichen: Shift", 300, 20); g.drawString("Wachenbewegung: WASD\nWachendrehung: Q,E", 300, 60); for(SolidObject w : solids) { w.render(g); } for(Laser l: laser) { l.render(g); } for(Lever l: lever) { l.render(g); } for(Watch w: watches) { w.render(g); } target.render(g); player.render(g); exit.render(g); if(debug) { for(SolidObject w : solids) { w.renderCollisionArea(g); } player.renderCollisionArea(g); for(Watch w : watches) { w.renderCollisionArea(g); } target.renderCollisionArea(g); for(Laser l: laser) { l.renderCollisionArea(g); } for(Lever l: lever) { l.renderCollisionArea(g); } } if(alarm) //Alarmbalken und Info oben { g.setColor(Color.red); g.drawString("ALARM", container.getWidth()/2, 50); g.fillRect(container.getWidth()/2-125, 70, alarmTime/2, 10); if(leverResetTime>0) { g.drawString("Lever Reset in "+ Math.ceil(leverResetTime/50.0)+"!", container.getWidth()/2 +100, 60); } } //Lebensbar anzeigen g.setColor(new Color(0.2f,0.2f,0.2f)); g.fillRect(755, 789, 310, 30); g.setColor(Color.green); g.fillRect(760, 794, player.getHealth(), 20); //300px Healthbar if (mission){ g.drawString("Target successfully killed",40, 850); } //Energiebalken g.setColor(new Color(0.2f,0.2f,0.2f)); g.fillRect(215, 789, 310, 30); g.setColor(Color.yellow); g.fillRect(220, 794, player.getEnergy(), 20); //300px Energybar g.setColor(Color.red); } @Override public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { updateSpecific(container,game,delta); Input input = container.getInput(); state = 0; player.animation.update(delta); for(Watch w : watches) { w.animation.update(delta); } exit.animation.update(delta); checkAlarm(); if(!alarm && (player.getHealth()<(player.getHealthDefault()/2))) { player.setHealth(player.getHealth() + 0.5f); } //Debug Toggle if(input.isKeyPressed(Input.KEY_F3)) { debug = !debug; } if(input.isKeyPressed(Input.KEY_H)) { deactivateAlarm(); player.setHealth(); player.setEnergy(); } if(input.isKeyPressed(Input.KEY_ESCAPE)) { gameMusic.stop(); alarmMusic.stop(); resetOnLeave(container, game); game.enterState(1); } if(input.isKeyPressed(Input.KEY_F)) { player.setStealth(false); for(Lever l : lever){ if(player.checkCollision(l)){ l.flipLever(); leverSound.play(1,0.3f); } } } //Player Movement Start player.setMoving(false); sneaking = false; if((input.isKeyDown(Input.KEY_LSHIFT) || input.isKeyDown(Input.KEY_RSHIFT)) && !player.isSprint()) { sneaking = true; } if(input.isKeyDown(Input.KEY_LEFT)) { player.setStealth(false); player.setMoving(true); state += 8; if(player.isSprint()) { if(player.canMove(-player.getSpeedSprint(), 0, solids, exit)) { player.move(-player.getSpeedSprint(), 0); } } else if(sneaking) { if(player.canMove(-player.getSpeedSneak(), 0, solids, exit)) { player.move(-player.getSpeedSneak(), 0); } } else { if(player.canMove(-player.getSpeedWalk(), 0, solids, exit)) { player.move(-player.getSpeedWalk(), 0); } } } if(input.isKeyDown(Input.KEY_RIGHT)) { player.setStealth(false); player.setMoving(true); state += 2; if(player.isSprint()) { if(player.canMove(player.getSpeedSprint(), 0, solids, exit)) { player.move(player.getSpeedSprint(), 0); } } else if(sneaking) { if(player.canMove(player.getSpeedSneak(), 0, solids, exit)) { player.move(player.getSpeedSneak(), 0); } } else { if(player.canMove(player.getSpeedWalk(), 0, solids, exit)) { player.move(player.getSpeedWalk(), 0); } } } if(input.isKeyDown(Input.KEY_UP)) { player.setStealth(false); player.setMoving(true); state += 1; if(player.isSprint()) { if(player.canMove(0, -player.getSpeedSprint(), solids, exit)) { player.move(0, -player.getSpeedSprint()); } } else if(sneaking) { if(player.canMove(0, -player.getSpeedSneak(), solids, exit)) { player.move(0, -player.getSpeedSneak()); } } else { if(player.canMove(0, -player.getSpeedWalk(), solids, exit)) { player.move(0, -player.getSpeedWalk()); } } } if(input.isKeyDown(Input.KEY_DOWN)) { player.setStealth(false); player.setMoving(true); state += 4; if(player.isSprint()) { if(player.canMove(0, player.getSpeedSprint(), solids, exit)) { player.move(0, player.getSpeedSprint()); } } else if(sneaking) { if(player.canMove(0, player.getSpeedSneak(), solids, exit)) { player.move(0, player.getSpeedSneak()); } } else { if(player.canMove(0, player.getSpeedWalk(), solids, exit)) { player.move(0, player.getSpeedWalk()); } } } //Player Movement Ende //Stealth und Sprint skill if(input.isKeyPressed(Input.KEY_V)) { player.switchSprint(); } if(input.isKeyPressed(Input.KEY_C) && stealthCooldown<=0) { if(player.isStealth()) { stealthCooldown = 50; } player.switchStealth(); } if(!player.isStealth()) { stealthCooldown } if(player.isStealth()) { player.setEnergy(player.getEnergy() - 1.2f); } if(player.isSprint()) { player.setEnergy(player.getEnergy() - 2.5f); } if(!(player.isStealth() || player.isSprint()) && player.getEnergy()<player.getEnergyDefault()) { player.setEnergy(player.getEnergy() + 0.5f); } if(player.getEnergy()<=0) { player.setStealth(false); player.setSprint(false); } //Skills Ende switch(state) { case 1: player.setRotation(90); break; case 2: player.setRotation(180); break; case 3: player.setRotation(135); break; case 4: player.setRotation(270); break; case 6: player.setRotation(225); break; case 12: player.setRotation(315); break; case 8: player.setRotation(360); break; case 9: player.setRotation(45); break; } if(!player.isMoving()) { player.animation.setCurrentFrame(2); player.animation.stop(); } else { player.animation.start(); } //Funktion des Ausgangs Anfang(old) //Funktion des Ausgangs Ende //Miracle of Sound Anfang if(alarm && !alarmMusic.playing()) { gameMusic.stop(); alarmMusic.loop(1,1); } if(!alarm && !gameMusic.playing()) { alarmMusic.stop(); gameMusic.loop(1,0.4f); } //Miracle of Sound Ende //Spielende if(player.getHealth()<=0) { Fail fail = (Fail) game.getState(3); fail.setLast(this.getID()); gameMusic.stop(); alarmMusic.stop(); resetOnLeave(container, game); game.enterState(3, new FadeOutTransition(), new FadeInTransition()); } if(player.checkCollision(exit) && exit.isOpen()) { Success success = (Success) game.getState(2); success.setLast(this.getID()); SavedState st = new SavedState("/Schattenwanderer_State"); try { st.load(); } catch (IOException e) { e.printStackTrace(); } if(st.getNumber("lastSuccessful") < this.getID() - levelOffset) { st.setNumber("lastSuccesful", this.getID() - levelOffset); } try { st.save(); } catch (IOException e) { e.printStackTrace(); } gameMusic.stop(); alarmMusic.stop(); endMusic.loop(1,1); resetOnLeave(container, game); game.enterState(2, new FadeOutTransition(), new FadeInTransition()); } //Hear Circle Logic float hearMax = player.isSprint() ? 75 : 50; float incrementPerUpdate = player.isSprint() ? 2 : 1; float alarmMultiplier = alarm ? 1.3f : 1; hearMax *= alarmMultiplier; float calmDown = 1.7f - alarmMultiplier; for(Watch w : watches) { if(player.isMoving() && (w.getNoise() < hearMax) && !sneaking) { if( w.getNoise() < hearMax - incrementPerUpdate) { w.addNoise(incrementPerUpdate); } } else if(w.getNoise()>w.getNoiseDefault()*alarmMultiplier) { w.addNoise(-calmDown); } } //Updates player.update(delta); for(Watch w : watches) { w.move(solids,exit); w.update(delta); w.updateSight(solids); } //Kill target if(target.checkCollision(player) && !mission){ mission = true; target.setDead(true); target.animation2.setCurrentFrame(0); target.animation2.start(); target.animation2.stopAt(9); openExit(); } //Death Animation target.animation2.update(delta); } /**Checks if the alarm should be activated, ticks it down if it is, deactivates it if alarmTime has reached 0 and * deals damage to the player if he stands in front of a watch*/ private void checkAlarm() { for(Laser l: laser) { if(l.isOn()) { if(player.checkCollision(l.getBeam())&& !player.isStealth()) { activateAlarm(); } } } boolean inSight = false; for(Watch w : watches) { if((player.checkCollision(w.getSightCone()) || player.checkCollision(w.getHearCircle())) && !player.isStealth()) { inSight = true; activateAlarm(); w.setPLayerLastKnown(new Vector2f(player.getX(),player.getY())); } if(target.checkCollision(w.getSightCone()) && !target.isDiscovered()) { activateAlarm(); target.setDiscovered(true); } } if(inSight) { gracePeriod++; if(gracePeriod>=10) { player.setHealth(player.getHealth() - 3); } } else { gracePeriod = 0; } if(alarm) { alarmTime if(alarmTime<0) { deactivateAlarm(); } } leverResetTime if(leverResetTime==0) { for(Lever l: lever) { if(l.isFlipped()) { l.flipLever(); } } } } /**Activates the alarm * * @param alarmTime How long the alarm should last */ private void activateAlarm() { alarm = true; this.alarmTime = alarmTimeDefault; onAlarmActivate(); } @SuppressWarnings("unused") private void activateAlarm(int alarmTime) { alarm = true; this.alarmTime = alarmTime; onAlarmActivate(); } /**Deactivates the alarm*/ private void deactivateAlarm() { alarm = false; onAlarmDeactivate(); } /**Event that is fired when the alarm gets activated. Extends watch sight radius and closes the door*/ public void onAlarmActivate() { for(Watch w : watches) { w.setSightRadius(150); w.setAlarmed(alarm); w.setPath(null); } //leverResetTime = leverResetTimeDefault; closeExit(); } /**Event that gets fired when the alarm gets deactivated. Resets watch sights radius and reopens the door(if mission has already been accomplished)*/ public void onAlarmDeactivate() { for(Watch w : watches) { w.setSightRadius(100); w.setAlarmed(alarm); } openExit(); } /**Function to open the exit*/ public void openExit() { if(mission && !alarm) { exit.animation.start(); exit.animation.stopAt(7); exitSound.play(1,0.5f); exit.setOpen(true); } } /**Function to close the exit*/ public void closeExit() { exit.animation.start(); exit.animation.stopAt(0); exit.setOpen(false); } @Override public int getID() { return levelOffset + levelNumber; } }
package org.nd4j.parameterserver.distributed.messages; import org.agrona.concurrent.UnsafeBuffer; import org.apache.commons.io.input.ClassLoaderObjectInputStream; import org.apache.commons.lang3.SerializationUtils; import org.nd4j.parameterserver.distributed.conf.VoidConfiguration; import org.nd4j.parameterserver.distributed.enums.NodeRole; import org.nd4j.parameterserver.distributed.logic.completion.Clipboard; import org.nd4j.parameterserver.distributed.logic.Storage; import org.nd4j.parameterserver.distributed.training.TrainingDriver; import org.nd4j.parameterserver.distributed.transport.Transport; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; import java.io.Serializable; /** * @author raver119@gmail.com */ public interface VoidMessage extends Serializable { void setTargetId(short id); short getTargetId(); long getTaskId(); int getMessageType(); long getOriginatorId(); void setOriginatorId(long id); byte[] asBytes(); UnsafeBuffer asUnsafeBuffer(); static <T extends VoidMessage> T fromBytes(byte[] array) { try { ObjectInputStream in = new ClassLoaderObjectInputStream(Thread.currentThread().getContextClassLoader(), new ByteArrayInputStream(array)); T result = (T) in.readObject(); return result; } catch (Exception e) { throw new RuntimeException(e); } //return SerializationUtils.deserialize(array); } /** * This method initializes message for further processing */ void attachContext(VoidConfiguration voidConfiguration, TrainingDriver<? extends TrainingMessage> trainer, Clipboard clipboard, Transport transport, Storage storage, NodeRole role, short shardIndex); void extractContext(BaseVoidMessage message); /** * This method will be started in context of executor, either Shard, Client or Backup node */ void processMessage(); boolean isJoinSupported(); boolean isBlockingMessage(); void joinMessage(VoidMessage message); int getRetransmitCount(); void incrementRetransmitCount(); }
package com.sixtyfour.parser; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import com.sixtyfour.elements.commands.Command; import com.sixtyfour.elements.commands.Gosub; import com.sixtyfour.elements.commands.Goto; import com.sixtyfour.elements.commands.If; import com.sixtyfour.elements.commands.On; /** * This class can be used to convert a BASIC program that uses labels and no * line numbers to proper BASIC V2 style with line numbers only. For example: * * <pre> * a=3 * output: * print"hallo":a=a+1 * if a<100 then output * goto terminate * print "should not see this!" * terminate:end * </pre> * * will be converted to this: * * <pre> * 100 a=3 * 110 rem jump target * 120 print"hallo":a=a+1 * 130 if a<100 then 110 * 140 goto 160 * 150 print "should not see this!" * 160 end * </pre> * * This doesn't happen automatically. If one wants to use labels instead of line * numbers, he/she has to trigger this conversion in Java code. * * @author EgonOlsen * */ public class Preprocessor { private final static int INC = 10; private final static int START = 100; /** * Converts a BASIC program with labels and without line numbers into one * with line numbers only. If the code can't be converted properly, this * method will throw an exception. * * @param code * the code with labels * @return the code with line numbers */ public static String[] convertToLineNumbers(String[] code) { List<String> res = new ArrayList<String>(); List<String> tmp = new ArrayList<String>(); Map<String, Integer> label2line = new HashMap<String, Integer>(); int ln = START; for (String line : code) { if (!line.isEmpty()) { char c = line.charAt(0); if (Character.isDigit(c)) { throw new RuntimeException("Code already contains line numbers: " + Arrays.toString(code)); } int pos = line.indexOf(":"); if (pos != -1) { String label = line.substring(0, pos).trim(); Command com = Parser.getCommand(label); if (com == null) { label2line.put(label, ln); line = line.substring(pos + 1).trim(); if (line.isEmpty()) { line = "rem jump target"; } } } tmp.add(line); ln += INC; } } ln = START; for (String line : tmp) { String[] parts = line.split(":"); StringBuilder sb = new StringBuilder(); if (parts.length > 0) { for (String part : parts) { if (sb.length() > 0) { sb.append(":"); } Command com = Parser.getCommand(part.trim()); if (com instanceof If) { String lp = Parser.replaceStrings(part, '_').toLowerCase(Locale.ENGLISH); int pos = lp.indexOf("then"); int pos2 = lp.indexOf("goto"); boolean got = true; if (pos2 == -1) { pos2 = lp.indexOf("gosub"); if (pos2 != -1) { got = false; } } if (pos == -1) { pos = pos2; } if (pos2 > pos) { pos = pos2; } if (pos != -1) { sb.append(part.substring(0, pos + (got ? 4 : 5))).append(" "); String op = part.substring(pos + (got ? 4 : 5)); Integer lineNum = label2line.get(op.trim()); if (lineNum != null) { sb.append(lineNum); } else { sb.append(op); } } else { sb.append(part); } } else { if (com instanceof Goto || com instanceof Gosub || com instanceof On) { String pl = part.toLowerCase(Locale.ENGLISH); int pos = pl.indexOf("goto"); boolean got = true; if (pos == -1) { pos = pl.indexOf("gosub"); got = false; } if (pos != -1) { sb.append(part.substring(0, pos + (got ? 4 : 5))).append(" "); String op = part.substring(pos + (got ? 4 : 5)); String[] targets = op.split(","); int cnt = 0; for (String target : targets) { Integer lineNum = label2line.get(target.trim()); if (lineNum == null) { throw new RuntimeException("Label '" + target + "' not found: " + line); } sb.append((cnt++) == 0 ? "" : ","); sb.append(lineNum); } } } else { sb.append(part); } } } res.add(ln + " " + sb.toString()); } else { res.add(ln + " " + line); } ln += INC; } return res.toArray(new String[res.size()]); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:17-12-15"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package org.opencb.opencga.storage.core.alignment.adaptors; import ga4gh.Reads; import org.apache.commons.lang3.time.StopWatch; import org.ga4gh.models.ReadAlignment; import org.opencb.biodata.models.core.Region; import org.opencb.biodata.tools.alignment.AlignmentFilters; import org.opencb.biodata.tools.alignment.AlignmentManager; import org.opencb.biodata.tools.alignment.AlignmentOptions; import org.opencb.commons.datastore.core.Query; import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.datastore.core.QueryResult; import org.opencb.opencga.storage.core.alignment.iterators.ProtoAlignmentIterator; import java.io.IOException; import java.nio.file.Path; import java.util.List; public class DefaultAlignmentDBAdaptor implements AlignmentDBAdaptor { private AlignmentManager alignmentManager; public DefaultAlignmentDBAdaptor(Path input) throws IOException { alignmentManager = new AlignmentManager(input); } @Override public QueryResult getAllAlignmentsByRegion(List<Region> regions, QueryOptions options) { throw new UnsupportedOperationException(); } @Override public QueryResult getAllAlignmentsByGene(String gene, QueryOptions options) { throw new UnsupportedOperationException(); } @Override public QueryResult getCoverageByRegion(Region region, QueryOptions options) { throw new UnsupportedOperationException(); } @Override public QueryResult getAlignmentsHistogramByRegion(Region region, boolean histogramLogarithm, int histogramMax) { throw new UnsupportedOperationException(); } @Override public QueryResult getAllIntervalFrequencies(Region region, QueryOptions options) { throw new UnsupportedOperationException(); } @Override public QueryResult getAlignmentRegionInfo(Region region, QueryOptions options) { throw new UnsupportedOperationException(); } @Override public QueryResult get(Query query, QueryOptions options) { try { StopWatch watch = new StopWatch(); watch.start(); AlignmentOptions alignmentOptions = parseQueryOptions(options); AlignmentFilters alignmentFilters = parseQuery(query); Region region = parseRegion(query); List<ReadAlignment> readAlignmentList; if (region != null) { readAlignmentList = alignmentManager.query(region, alignmentOptions, alignmentFilters, ReadAlignment.class); } else { readAlignmentList = alignmentManager.query(alignmentOptions, alignmentFilters, ReadAlignment.class); } // List<String> stringFormatList = new ArrayList<>(readAlignmentList.size()); // for (Reads.ReadAlignment readAlignment : readAlignmentList) { // stringFormatList.add(readAlignment()); // List<JsonFormat> list = alignmentManager.query(region, alignmentOptions, alignmentFilters, Reads.ReadAlignment.class); watch.stop(); return new QueryResult("Get alignments", ((int) watch.getTime()), readAlignmentList.size(), readAlignmentList.size(), null, null, readAlignmentList); } catch (Exception e) { e.printStackTrace(); return new QueryResult<>(); } } @Override public ProtoAlignmentIterator iterator() { return iterator(new Query(), new QueryOptions()); } @Override public ProtoAlignmentIterator iterator(Query query, QueryOptions options) { try { if (options == null) { options = new QueryOptions(); } if (query == null) { query = new Query(); } AlignmentOptions alignmentOptions = parseQueryOptions(options); AlignmentFilters alignmentFilters = parseQuery(query); Region region = parseRegion(query); if (region != null) { return new ProtoAlignmentIterator( alignmentManager.iterator(region, alignmentOptions, alignmentFilters, Reads.ReadAlignment.class)); } else { return new ProtoAlignmentIterator(alignmentManager.iterator(alignmentOptions, alignmentFilters, Reads.ReadAlignment.class)); } } catch (Exception e) { e.printStackTrace(); } return null; } private Region parseRegion(Query query) { Region region = null; String regionString = query.getString(QueryParams.REGION.key()); if (regionString != null && !regionString.isEmpty()) { region = new Region(regionString); } return region; } private AlignmentFilters parseQuery(Query query) { AlignmentFilters alignmentFilters = AlignmentFilters.create(); int minMapQ = query.getInt(QueryParams.MIN_MAPQ.key()); if (minMapQ > 0) { alignmentFilters.addMappingQualityFilter(minMapQ); } return alignmentFilters; } private AlignmentOptions parseQueryOptions(QueryOptions options) { AlignmentOptions alignmentOptions = new AlignmentOptions() .setContained(options.getBoolean(QueryParams.CONTAINED.key())); int limit = options.getInt(QueryParams.LIMIT.key()); if (limit > 0) { alignmentOptions.setLimit(limit); } return alignmentOptions; } @Override public long count(Query query, QueryOptions options) { ProtoAlignmentIterator iterator = iterator(query, options); long cont = 0; while (iterator.hasNext()) { iterator.next(); cont++; } return cont; } }
package com.softartisans.timberwolf; import java.util.Date; public interface Email { String getBody(); String getSender(); String[] getRecipients(); String[] getCcRecipients(); String[] getBccRecipients(); String getSubject(); Date getTimeSent(); // TODO: What other common headers do we want? String[] getHeaderKeys(); String getHeader(String header); }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-02-09"); this.setApiVersion("15.17.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// SwingDisplayPanel.java package imagej.ui.swing.display; import imagej.data.Data; import imagej.data.Dataset; import imagej.data.display.DataView; import imagej.data.display.DisplayWindow; import imagej.data.display.ImageDisplay; import imagej.data.display.ImageDisplayPanel; import imagej.data.roi.Overlay; import imagej.ext.display.EventDispatcher; import imagej.ui.common.awt.AWTKeyEventDispatcher; import imagej.ui.common.awt.AWTMouseEventDispatcher; import imagej.ui.swing.StaticSwingUtils; import java.awt.Adjustable; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Rectangle; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import net.imglib2.img.Axes; import net.imglib2.img.Axis; import net.imglib2.roi.RegionOfInterest; import net.miginfocom.swing.MigLayout; /** * Swing implementation of image display panel. Contains a label, a graphics * pane containing an ImageCanvas, and panel containing dimensional controllers * (sliders). This panel is added to a top-level display container * (DisplayWindow). * * @author Curtis Rueden * @author Grant Harris * @author Barry DeZonia */ public class SwingDisplayPanel extends JPanel implements ImageDisplayPanel { private final ImageDisplay display; private final JLabel imageLabel; private final JPanel sliders; private final DisplayWindow window; protected final Map<Axis, Long> axisPositions = new HashMap<Axis, Long>(); // TODO - HACK - to avoid concurrent modification exceptions I need to make // axisSliders a ConcurrentHashMap instead of a regular HashMap. See bug // #672. The weird part is tracing with print statements you can show that // nobody but the single call to createSliders() is accessing the // axisSliders instance variable. I can find no evidence of a concurrent // access let alone modification. Making hashmap concurrent makes issue go // away. private final Map<Axis, JScrollBar> axisSliders = new ConcurrentHashMap<Axis, JScrollBar>(); private final Map<Axis, JLabel> axisLabels = new HashMap<Axis, JLabel>(); public SwingDisplayPanel(final ImageDisplay display, final DisplayWindow window) { this.display = display; this.window = window; imageLabel = new JLabel(" "); final int prefHeight = imageLabel.getPreferredSize().height; imageLabel.setPreferredSize(new Dimension(0, prefHeight)); final JPanel graphicPane = new JPanel(); graphicPane.setLayout(new MigLayout("ins 0", "fill,grow", "fill,grow")); graphicPane.add((JHotDrawImageCanvas) display.getCanvas()); sliders = new JPanel(); sliders.setLayout(new MigLayout("fillx,wrap 2", "[right|fill,grow]")); setLayout(new BorderLayout()); setBorder(new EmptyBorder(3, 3, 3, 3)); add(imageLabel, BorderLayout.NORTH); add(graphicPane, BorderLayout.CENTER); add(sliders, BorderLayout.SOUTH); window.setContent(this); } // -- ImageDisplayPanel methods -- /** * Get the position of some axis other than X and Y * * @param axis - the axis * @return the position of that axis on the sliders */ @Override public long getAxisPosition(final Axis axis) { if (axisPositions.containsKey(axis)) { return axisPositions.get(axis); } return 0; } @Override public void setAxisPosition(final Axis axis, final long position) { axisPositions.put(axis, position); final JScrollBar scrollBar = axisSliders.get(axis); if (scrollBar != null) scrollBar.setValue((int) position); } @Override public DisplayWindow getWindow() { return window; } // -- DisplayPanel methods -- @Override public ImageDisplay getDisplay() { return display; } @Override public void makeActive() { window.requestFocus(); } @Override public void redoLayout() { EventQueue.invokeLater(new Runnable() { @SuppressWarnings("synthetic-access") @Override public void run() { createSliders(); sliders.setVisible(sliders.getComponentCount() > 0); sizeAppropriately(); window.setTitle(getDisplay().getName()); window.showDisplay(true); } }); } private boolean initial = true; void sizeAppropriately() { final JHotDrawImageCanvas canvas = (JHotDrawImageCanvas) display.getCanvas(); final Rectangle deskBounds = StaticSwingUtils.getWorkSpaceBounds(); Dimension canvasSize = canvas.getPreferredSize(); // width determined by scaled image canvas width final int labelPlusSliderHeight = imageLabel.getPreferredSize().height + sliders.getPreferredSize().height; // graphicPane.getPreferredSize(); int scaling = 1; while (canvasSize.height + labelPlusSliderHeight > deskBounds.height - 32 || canvasSize.width > deskBounds.width - 32) { canvas.setZoom(1.0 / scaling++); canvasSize = canvas.getPreferredSize(); } if (initial) { canvas.setInitialScale(canvas.getZoomFactor()); initial = false; } } @Override public void setLabel(final String s) { imageLabel.setText(s); } @Override public void addEventDispatcher(final EventDispatcher dispatcher) { if (dispatcher instanceof AWTKeyEventDispatcher) { addKeyListener((AWTKeyEventDispatcher) dispatcher); } if (dispatcher instanceof AWTMouseEventDispatcher) { addMouseListener((AWTMouseEventDispatcher) dispatcher); addMouseMotionListener((AWTMouseEventDispatcher) dispatcher); addMouseWheelListener((AWTMouseEventDispatcher) dispatcher); } } // -- Helper methods -- private/*synchronized*/void createSliders() { final long[] min = new long[display.numDimensions()]; Arrays.fill(min, Long.MAX_VALUE); final long[] max = new long[display.numDimensions()]; Arrays.fill(max, Long.MIN_VALUE); // final Axis[] axes = new Axis[display.numDimensions()]; // display.axes(axes); final Axis[] dispAxes = display.getAxes(); /* * Run through all of the views and determine the extents of each. * * NB: Images can have minimum spatial extents less than zero, * for instance, some sort of bounded function that somehow * became an image in a dataset. So the dataset should have * something more than dimensions. * * For something like time or Z, this could be kind of cool: * my thing's time dimension goes from last Tuesday to Friday. */ for (final DataView v : display) { final Data o = v.getData(); if (o instanceof Dataset) { final Dataset ds = (Dataset) o; final long[] dims = ds.getDims(); for (int i = 0; i < dispAxes.length; i++) { final int index = ds.getAxisIndex(dispAxes[i]); if (index >= 0) { min[i] = Math.min(min[i], 0); max[i] = Math.max(max[i], dims[index]); } } } else if (o instanceof Overlay) { final Overlay overlay = (Overlay) o; final RegionOfInterest roi = overlay.getRegionOfInterest(); if (roi != null) { for (int i = 0; i < dispAxes.length; i++) { final int index = overlay.getAxisIndex(dispAxes[i]); if ((index >= 0) && (index < roi.numDimensions())) { min[i] = Math.min(min[i], (long) Math.ceil(roi.realMin(index))); max[i] = Math.max(max[i], (long) Math.floor(roi.realMax(index))); } } } } } for (final Axis axis : axisSliders.keySet()) { if (display.getAxisIndex(axis) < 0) { sliders.remove(axisSliders.get(axis)); sliders.remove(axisLabels.get(axis)); axisSliders.remove(axis); axisLabels.remove(axis); axisPositions.remove(axis); } // if a Dataset had planes deleted this will eventually get called. // if thats the case the slider might exist but its allowable range // has changed. check that we have correct range. final JScrollBar slider = axisSliders.get(axis); if (slider != null) { for (int i = 0; i < dispAxes.length; i++) { if (axis == dispAxes[i]) { if ((slider.getMinimum() != min[i]) || (slider.getMaximum() != max[i])) { if (slider.getValue() > max[i]) slider.setValue((int) max[i]); slider.setMinimum((int) min[i]); slider.setMaximum((int) max[i]); } } } } } for (int i = 0; i < dispAxes.length; i++) { final Axis axis = dispAxes[i]; if (axisSliders.containsKey(axis)) continue; if (Axes.isXY(axis)) continue; if (min[i] >= max[i] - 1) continue; setAxisPosition(axis, (int) min[i]); final JLabel label = new JLabel(axis.getLabel()); axisLabels.put(axis, label); label.setHorizontalAlignment(SwingConstants.RIGHT); final JScrollBar slider = new JScrollBar(Adjustable.HORIZONTAL, (int) min[i], 1, (int) min[i], (int) max[i]); axisSliders.put(axis, slider); slider.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(final AdjustmentEvent e) { final long position = slider.getValue(); axisPositions.put(axis, position); getDisplay().update(); } }); sliders.add(label); sliders.add(slider); } } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-03-11"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package org.duracloud.services.amazonmapreduce.postprocessing; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.AutoCloseInputStream; import org.duracloud.client.ContentStore; import org.duracloud.common.error.DuraCloudRuntimeException; import org.duracloud.services.amazonmapreduce.AmazonMapReduceJobWorker; import org.duracloud.services.amazonmapreduce.BaseAmazonMapReducePostJobWorker; import org.duracloud.services.amazonmapreduce.util.ContentStoreUtil; import org.duracloud.services.amazonmapreduce.util.ContentStreamUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.io.OutputStream; public class HeaderPostJobWorker extends BaseAmazonMapReducePostJobWorker { private final Logger log = LoggerFactory.getLogger(HeaderPostJobWorker.class); private ContentStoreUtil storeUtil; private ContentStreamUtil streamUtil; private String serviceWorkDir; private String spaceId; private String contentId; private String newContentId; private String header; public HeaderPostJobWorker(AmazonMapReduceJobWorker predecessor, ContentStore contentStore, String serviceWorkDir, String spaceId, String contentId, String newContentId, String header) { super(predecessor); init(contentStore, serviceWorkDir, spaceId, contentId, newContentId, header); } public HeaderPostJobWorker(AmazonMapReduceJobWorker predecessor, ContentStore contentStore, String serviceWorkDir, String spaceId, String contentId, String newContentId, String header, long sleepMillis) { super(predecessor, sleepMillis); init(contentStore, serviceWorkDir, spaceId, contentId, newContentId, header); } private void init(ContentStore contentStore, String serviceWorkDir, String spaceId, String contentId, String newContentId, String header) { this.storeUtil = new ContentStoreUtil(contentStore); this.streamUtil = new ContentStreamUtil(); this.serviceWorkDir = serviceWorkDir; this.spaceId = spaceId; this.contentId = contentId; this.newContentId = newContentId; this.header = header; } @Override protected void doWork() { InputStream originalStream = getContentStream(); File fileWithHeader = new File(serviceWorkDir, contentId); OutputStream outputStream = createOutputStream(fileWithHeader); writeToOutputStream(header, outputStream); writeToOutputStream(System.getProperty("line.separator"), outputStream); writeToOutputStream(originalStream, outputStream); IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(originalStream); storeContentStream(fileWithHeader); deleteOldContent(); } private InputStream getContentStream() { try { return storeUtil.getContentStream(spaceId, contentId); } catch (DuraCloudRuntimeException e) { String msg = e.getMessage(); InputStream stream = new ByteArrayInputStream(msg.getBytes()); return new AutoCloseInputStream(stream); } } private void writeToOutputStream(String text, OutputStream outputStream) { streamUtil.writeToOutputStream(text, outputStream); } private void writeToOutputStream(InputStream inputStream, OutputStream outputStream) { streamUtil.writeToOutputStream(inputStream, outputStream); } private OutputStream createOutputStream(File file) { return streamUtil.createOutputStream(file); } private void deleteOldContent() { storeUtil.deleteOldContent(spaceId, contentId); } private void storeContentStream(File file) { storeUtil.storeContentStream(file, spaceId, newContentId); } }
package com.vzome.core.editor; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.vzome.core.commands.Command; import com.vzome.core.commands.XmlSaveFormat; import com.vzome.core.commands.Command.Failure; import com.vzome.core.editor.UndoableEdit.Context; import com.vzome.core.math.DomUtils; import com.vzome.core.model.Manifestation; public class EditHistory implements Iterable<UndoableEdit> { private List<UndoableEdit> mEdits = new ArrayList<>(); // mEditNumber is the number of "redone" UndoableEdits in mEdits private int mEditNumber = 0; private boolean breakpointHit = false; private static final Logger logger = Logger .getLogger( "com.vzome.core.EditHistory" ); private static final Logger breakpointLogger = Logger .getLogger( "com.vzome.core.editor.Breakpoint" ); public interface Listener { void showCommand( Element xml, int editNumber ); } public Listener listener; public void setListener( Listener listener ) { this .listener = listener; } public void addEdit( UndoableEdit edit, Context context ) { if ( ! edit .isDestructive() ) { // just insert at the current point, don't invalidate the redoable edits mEdits .add( mEditNumber, edit ); ++ mEditNumber; return; } if ( mEditNumber < mEdits .size() ) { boolean makeBranch = false; // first, find the last isSticky() edit in the dead edits being removed. int lastStickyEdit = mEditNumber - 1; int deadEditIndex = mEditNumber; for ( Iterator<UndoableEdit> deadEdits = mEdits .listIterator( mEditNumber ); deadEdits .hasNext(); ) { UndoableEdit dead = deadEdits .next(); if ( dead .isSticky() ) { makeBranch = true; lastStickyEdit = deadEditIndex; } ++deadEditIndex; } Branch branch = makeBranch? new Branch( context ) : null; deadEditIndex = mEditNumber; for ( Iterator<UndoableEdit> deadEdits = mEdits .listIterator( mEditNumber ); deadEdits .hasNext(); ) { UndoableEdit removed = deadEdits .next(); deadEdits .remove(); if ( deadEditIndex <= lastStickyEdit ) { // note that lastStickyEdit is initialized with the last edit not discarded, // so this can only be true if a sticky edit had been found, and the loop // has not reached it yet branch .addEdit( removed ); } ++deadEditIndex; } if ( makeBranch ) { mEdits .add( branch ); ++ mEditNumber; } } mEdits .add( edit ); ++ mEditNumber; } public UndoableEdit undoAll() { UndoableEdit last = null; do { UndoableEdit edit = undo(); if ( edit == null ) break; last = edit; } while ( true ); return last; } public UndoableEdit undoToManifestation( Manifestation man ) { UndoableEdit edit = null; do { edit = undo(); if ( edit == null ) break; if ( ( edit instanceof ChangeManifestations ) && ((ChangeManifestations) edit) .showsManifestation( man ) ) { break; } } while ( true ); return edit; } public UndoableEdit undoToBreakpoint() { // always try once, to skip over a breakpoint we might be sitting on UndoableEdit edit = undo(); if ( edit == null ) return edit; do { edit = undo(); if ( edit == null ) break; if ( edit instanceof Breakpoint ) { break; } } while ( true ); return edit; } public UndoableEdit redoToBreakpoint() throws Command.Failure { // always try once, to skip over a breakpoint we might be sitting on UndoableEdit edit = redo(); if ( edit == null ) return edit; do { edit = redo(); if ( edit == null ) break; if ( edit instanceof Breakpoint ) { break; } } while ( true ); return edit; } public void setBreakpoint() { mEdits .add( mEditNumber++, new Breakpoint() ); } public UndoableEdit redoAll( int breakpoint ) throws Command.Failure { UndoableEdit last = null; breakpointHit = false; // different mechanism than the int parameter do { UndoableEdit edit = redo(); if ( edit == null ) break; last = edit; if ( breakpointHit ) { breakpointHit = false; break; } } while ( breakpoint == -1 || mEditNumber < breakpoint ); return last; } public void goToEdit( int editNum ) throws Command.Failure { if ( editNum == -1 ) // -1 means redoAll editNum = mEdits .size(); if ( editNum == mEditNumber ) return; // undo() and redo() inlined here to avoid isVisible() and block limitations while ( mEditNumber < editNum ) { if ( mEditNumber == mEdits .size() ) break; UndoableEdit undoable = mEdits .get( mEditNumber++ ); undoable .redo(); } while ( mEditNumber > editNum ) { if ( mEditNumber == 0 ) break; UndoableEdit undoable = mEdits .get( --mEditNumber ); undoable .undo(); } } public UndoableEdit undo() { if ( mEditNumber == 0 ) return null; UndoableEdit undoable = mEdits .get( --mEditNumber ); if ( undoable instanceof EndBlock ) return undoBlock(); undoable .undo(); logger .fine( "undo: " + undoable .toString() ); if ( undoable instanceof BeginBlock ) return undoable; if ( ! undoable .isVisible() ) return undo(); // undo another one, until we find one we want to return return undoable; } private UndoableEdit undoBlock() { UndoableEdit undone; do { undone = undo(); } while ( ! (undone instanceof BeginBlock) ); return undone; } public UndoableEdit redo() throws Command.Failure { if ( mEditNumber == mEdits .size() ) return null; UndoableEdit undoable = mEdits .get( mEditNumber++ ); if ( undoable instanceof BeginBlock ) return redoBlock(); try { if ( logger .isLoggable( Level .FINE ) ) logger .fine( "redo: " + undoable .toString() ); undoable .redo(); } catch ( RuntimeException e ) { if ( logger .isLoggable( Level .WARNING ) ) logger .warning( "edit number that failed is " + (mEditNumber-1) ); throw e; } if ( undoable instanceof EndBlock ) return undoable; if ( ! undoable .isVisible() ) return redo(); // redo another one, until we find one we want to return return undoable; } private UndoableEdit redoBlock() throws Command.Failure { UndoableEdit redone; do { redone = redo(); } while ( ! (redone instanceof EndBlock) ); return redone; } public Element getDetailXml( Document doc ) { Element result = doc .createElement( "EditHistoryDetails" ); DomUtils .addAttribute( result, "editNumber", Integer.toString( this .mEditNumber ) ); int edits = 0, lastStickyEdit=-1; for (UndoableEdit undoable : this) { Element edit = undoable .getDetailXml( doc ); ++ edits; DomUtils .addAttribute( edit, "editNumber", Integer.toString( edits ) ); if ( logger .isLoggable( Level.FINEST ) ) logger .finest( "side-effect: " + DomUtils .getXmlString( edit ) ); result .appendChild( edit ); if ( undoable .isSticky() ) lastStickyEdit = edits; } result .setAttribute( "lastStickyEdit", Integer .toString( lastStickyEdit ) ); return result; } public Element getXml( Document doc ) { Element result = doc .createElement( "EditHistory" ); DomUtils .addAttribute( result, "editNumber", Integer.toString( this .mEditNumber ) ); return result; // edits are now serialized in calling EditorController // for ( Iterator<UndoableEdit> it = mEdits .iterator(); it .hasNext(); ) // UndoableEdit undoable = it .next(); // Context newContext = undoable .getContext(); // if ( context != undoable .getContext() ) // context = newContext; // UndoableEdit switchContext = masterContext .createEdit( type, format ); // Element switchContext = new Element( "switchContext" ); // switchContext .addAttribute( new Attribute( "to", getContextId( context ) ) ); // result .appendChild( switchContext ); // result .appendChild( undoable .getXml() ); } public void mergeSelectionChanges() { // TODO record the state well enough that it can be recovered int cursor = mEditNumber; if ( cursor == 0 ) return; -- cursor; UndoableEdit above = mEdits .get( cursor ); if ( above instanceof ChangeManifestations ) return; if ( ! ( above instanceof ChangeSelection ) ) return; // okay, last edit was a selection change, now look if there's another one before it if ( cursor == 0 ) return; -- cursor; UndoableEdit below = mEdits .get( cursor ); if ( below instanceof ChangeManifestations ) return; if ( below instanceof ChangeSelection ) { // two in a row, wrap with begin/end pair UndoableEdit bracket = new BeginBlock(); mEdits .add( cursor, bracket ); bracket = new EndBlock(); mEdits .add( bracket ); mEditNumber += 2; } else if ( below instanceof EndBlock ) { // match BeginBlock unless you find a real edit int scan = cursor - 1; boolean done = false; while ( ! done ) { UndoableEdit next = mEdits .get( scan ); if ( next instanceof ChangeManifestations ) return; if ( next instanceof ChangeSelection ) --scan; // keep going else if ( next instanceof BeginBlock ) { // merge new selection change into block by swapping with EndBlock mEdits .remove( above ); mEdits .add( cursor, above ); return; } else return; } } } public void replaceEdit( UndoableEdit oldEdit, UndoableEdit newEdit ) { mEdits .set( mEdits .indexOf( oldEdit ), newEdit ); } /** * This is used during DeferredEdit .redo(), possibly to migrate one UndoableEdit into several. * It must maintain the invariant that the next UndoableEdit is the next DeferredEdit to redo. * @param edit */ public void insert( UndoableEdit edit ) { mEdits .add( mEditNumber++, edit ); } public class Breakpoint implements UndoableEdit { @Override public Element getXml( Document doc ) { return doc .createElement( "Breakpoint" ); } @Override public boolean isVisible() { return true; } @Override public void loadAndPerform( Element xml, XmlSaveFormat format, Context context ) throws Failure { context .performAndRecord( this ); } @Override public void perform() throws Failure { breakpointLogger .info( "hit a Breakpoint at " + mEditNumber ); breakpointHit = true; } @Override public void redo() throws Failure { perform(); } @Override public void undo() {} @Override public boolean isSticky() { return false; } @Override public boolean isDestructive() { return false; } @Override public Element getDetailXml( Document doc ) { return getXml( doc ); } } private class DeferredEdit implements UndoableEdit { private final XmlSaveFormat format; private final Element xml; private Context context; public DeferredEdit( XmlSaveFormat format, Element editElem, Context context ) { this.format = format; this.xml = editElem; this.context = context; } @Override public Element getXml( Document doc ) { // Use doc.importNode() instead of returning the xml directly. // This avoids a org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it. // This can occur in DocumentModel.serialize() // when saving a file that includes a DeferredEdit imported from Prototypes\golden.vZome // For example, the following snippet of XML as a valid part of that file can cause the condition described // by simply opening vzome and immediately selecting "Save As..." from the menu and saving the new empty file // which now includes the deferred edits from the prototype file. /* <EditHistory editNumber="0" lastStickyEdit="-1"> <StrutCreation anchor="0 0 0 0 0 0" index="9" len="2 4"/> </EditHistory> */ return (Element) doc.importNode(xml, true); } @Override public boolean isVisible() { return true; } @Override public boolean isDestructive() { return true; } @Override public void redo() throws Command.Failure { /* * The following things need to happen: * * 1. this DeferredEdit will remove itself from the history * * 2. a single UndoableEdit is created based on the xml * * 3. the UndoableEdit may migrate itself, generating */ int num = mEditNumber; mEdits .remove( --mEditNumber ); if ( logger.isLoggable( Level.FINE ) ) // see the logger declaration to enable FINE logger.fine( "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% " + num + ": " + DomUtils .getXmlString( xml ) ); UndoableEdit realized = null; String cmdName = xml.getLocalName(); // if ( format.actionHistory() ) // never happens, yet // realized = design .createActionEdit( cmdName, null, groupInSelection ); // else // opening a file from vZome 2.1 - 4.0 or ...? if ( cmdName .equals( "Breakpoint" ) ) { realized = new Breakpoint(); } else realized = context .createEdit( xml, format .groupingDoneInSelection() ); // System.out.println( "edit: " + num + " " + cmdName ); try { EditHistory .this .listener .showCommand( xml, num ); realized. loadAndPerform(xml, format, new UndoableEdit.Context() { @Override public void performAndRecord( UndoableEdit edit ) { // realized is responsible for inserting itself, or any replacements (migration) try { edit .perform(); if ( logger .isLoggable( Level.FINEST ) ) { Element details = edit .getDetailXml( xml .getOwnerDocument() ); logger .finest( "side-effect: " + DomUtils .getXmlString( details ) ); } } catch (Failure e) { // really hacky tunneling throw new RuntimeException( e ); } EditHistory .this .insert( edit ); } @Override public UndoableEdit createEdit( Element xml, boolean groupInSelection ) { return context .createEdit( xml, groupInSelection ); } } ); // this method needs to have the history, since it may migrate // System.out.println(); // no longer doing redo() and mHistory.replace() here, so each UndoableEdit may // either migrate itself, or determine whether it requires a redo() after deserialization. } catch ( RuntimeException e ) { logger.warning( "failure during initial edit replay:\n" + DomUtils .getXmlString( xml ) ); // errors will be reported by caller! // mErrors .reportError( UNKNOWN_ERROR_CODE, new Object[]{ e } ); throw e; // interrupt the redoing } } @Override public void loadAndPerform( Element xml, XmlSaveFormat format, Context context ) throws Failure { throw new IllegalStateException( "should never be called" ); } @Override public void undo() { // called, but must be a no-op } @Override public void perform() { // never called } @Override public boolean isSticky() { return false; } @Override public Element getDetailXml( Document doc ) { return doc .createElement( "deferredEdit" ); } } /** * Redo to greater of lastStickyEdit and lastDoneEdit, undo back to lastDoneEdit. * If there are explicitSnapshots, this is a migration of an old Article, using edit * numbers, and we have to redo as far as the last one, inserting snapshots as we go. * Note that lastStickyEdit and explicitSnapshots are mutually exclusive, after and before * migration, respectively. * * @param lastDoneEdit * @param lastStickyEdit * @param explicitSnapshots * @throws Failure */ public void synchronize( int lastDoneEdit, int lastStickyEdit, UndoableEdit[] explicitSnapshots ) throws Failure { int redoThreshold = Math .max( lastDoneEdit, lastStickyEdit ); if ( explicitSnapshots != null ) redoThreshold = Math .max( redoThreshold, explicitSnapshots .length - 1 ); mEditNumber = 0; int targetEdit = 0; List<UndoableEdit> toRedo = new ArrayList<>(); // here the edits are all still DeferredEdits for ( int i = 0; i < redoThreshold; i++ ) if ( i < mEdits .size() ) toRedo .add( mEdits .get( i ) ); else break; for ( int oldIndex = 0; oldIndex < toRedo .size(); oldIndex++ ) { DeferredEdit edit = (DeferredEdit) toRedo .get( oldIndex ); try { if ( explicitSnapshots != null && explicitSnapshots .length > oldIndex && explicitSnapshots[ oldIndex ] != null ) { // a snapshot editNum of 3 means a snapshot *before* edit #3 is redone, // so we do this snapshot migration first UndoableEdit snapshot = explicitSnapshots[ oldIndex ]; mEdits .add( mEditNumber, snapshot ); // keep lastDoneEdit in alignment if ( mEditNumber <= lastDoneEdit ) ++ lastDoneEdit; ++ mEditNumber; snapshot .perform(); } ++ mEditNumber; //match the preconditions like this.redo() edit .redo(); // now the edit is realized // lastDoneEdit is in terms of the edits in the file, and we need // to translate it to match the actual edit numbers, after migration // and snapshot creation. We know this condition will succeed once, // since toRedo.size() is at least as big as lastDoneEdit. if ( oldIndex+1 == lastDoneEdit ) targetEdit = mEditNumber; } catch ( RuntimeException e ) { if ( logger.isLoggable( Level.WARNING ) ) logger.warning( "edit number that failed is " + ( this .mEditNumber - 1 ) ); // unwrap Throwable t = e.getCause(); if ( t instanceof Command.Failure ) throw (Command.Failure) t; else throw e; } } if ( explicitSnapshots != null && explicitSnapshots .length > redoThreshold && explicitSnapshots[ redoThreshold ] != null ) { // a snapshot editNum of 3 means a snapshot *before* edit #3 is redone, // so we do this snapshot migration first UndoableEdit snapshot = explicitSnapshots[ redoThreshold ]; mEdits .add( mEditNumber, snapshot ); ++ mEditNumber; snapshot .perform(); } goToEdit( targetEdit ); } public void loadEdit( XmlSaveFormat format, Element editElem, Context context ) { DeferredEdit edit = new DeferredEdit( format, editElem, context ); this .addEdit( edit, context ); } @Override public Iterator<UndoableEdit> iterator() { return this .mEdits .iterator(); } public int getEditNumber() { return this .mEditNumber; } }
package de.mccityville.libmanager.util; import org.eclipse.aether.impl.DefaultServiceLocator; import java.util.logging.Level; import java.util.logging.Logger; public class LoggerServiceLocatorErrorHandler extends DefaultServiceLocator.ErrorHandler { private final Logger logger; public LoggerServiceLocatorErrorHandler(Logger logger) { this.logger = logger; } @Override public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable exception) { logger.log(Level.SEVERE, "Failed to create service fo type " + type.getName() + " with implementation " + impl.getName(), exception); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:19-04-06"); this.setApiVersion("14.17.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package com.johnuckele.vivarium.scripts; import java.io.File; import java.io.IOException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class CreateBlueprintTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); public String path; @Before public void setupPath() throws IOException { path = folder.getRoot().getCanonicalPath() + File.separator; } @Test public void testDefault() throws IOException { { String[] commandArgs = { "-o", path + "b.viv" }; CreateBlueprint.main(commandArgs); } } @Test public void testWithSpecies() throws IOException { { String[] commandArgs = { "-o", path + "s.viv" }; CreateSpecies.main(commandArgs); } { String[] commandArgs = { "-o", path + "b.viv", "-s", path + "s.viv" }; CreateBlueprint.main(commandArgs); } } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-03-11"); this.setApiVersion("18.0.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package de.dhbw.humbuch.guice; import com.google.common.eventbus.EventBus; import com.google.inject.Provides; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.MapBinder; import com.google.inject.persist.jpa.JpaPersistModule; import com.google.inject.servlet.ServletModule; import com.google.inject.servlet.SessionScoped; import com.vaadin.ui.UI; import de.davherrmann.guice.vaadin.UIScoped; import de.davherrmann.mvvm.ViewModelComposer; import de.dhbw.humbuch.model.DAO; import de.dhbw.humbuch.model.DAOImpl; import de.dhbw.humbuch.model.entity.BorrowedMaterial; import de.dhbw.humbuch.model.entity.Category; import de.dhbw.humbuch.model.entity.Dunning; import de.dhbw.humbuch.model.entity.Grade; import de.dhbw.humbuch.model.entity.Parent; import de.dhbw.humbuch.model.entity.SchoolYear; import de.dhbw.humbuch.model.entity.Student; import de.dhbw.humbuch.model.entity.TeachingMaterial; import de.dhbw.humbuch.model.entity.User; import de.dhbw.humbuch.view.MVVMConfig; import de.dhbw.humbuch.view.MainUI; import de.dhbw.humbuch.viewmodel.LoginViewModel; import de.dhbw.humbuch.viewmodel.Properties; public class BasicModule extends ServletModule { @Override protected void configureServlets() { install(new JpaPersistModule("persistModule"));
package com.artemzin.android.wail.ui.fragment.main; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.SwitchCompat; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.afollestad.materialdialogs.Theme; import com.artemzin.android.bytes.ui.DisplayUnitsConverter; import com.artemzin.android.bytes.ui.ViewUtil; import com.artemzin.android.wail.R; import com.artemzin.android.wail.storage.WAILSettings; import com.artemzin.android.wail.storage.db.AppDBManager; import com.artemzin.android.wail.ui.activity.BaseActivity; import com.artemzin.android.wail.ui.activity.MainActivity; import com.artemzin.android.wail.ui.activity.settings.SettingsIgnoredPlayersActivity; import com.artemzin.android.wail.ui.activity.settings.SettingsSelectLanguageActivity; import com.artemzin.android.wail.ui.activity.settings.SettingsSoundNotificationsActivity; import com.artemzin.android.wail.ui.activity.settings.SettingsStatusBarNotificationsActivity; import com.artemzin.android.wail.ui.fragment.BaseFragment; import com.artemzin.android.wail.ui.fragment.dialogs.DialogDecorator; import com.artemzin.android.wail.ui.fragment.dialogs.DialogFragmentWithNumberPicker; import com.artemzin.android.wail.ui.fragment.dialogs.DialogFragmentWithSeekBar; import com.artemzin.android.wail.util.LocaleUtil; import com.artemzin.android.wail.util.WordFormUtil; import com.google.analytics.tracking.android.EasyTracker; import com.google.analytics.tracking.android.MapBuilder; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnCheckedChanged; import butterknife.OnClick; public class SettingsFragment extends BaseFragment implements DialogDecorator.Callback { public static final String GA_EVENT_SETTINGS_FRAGMENT = "SettingsFragment"; @InjectView(R.id.settings_build_version_desc) public TextView buildVersionDescTextView; @InjectView(R.id.settings_select_language_description) public TextView languageMenuItemDescription; @InjectView(R.id.settings_disable_scrobbling_over_mobile_network_switch) public SwitchCompat isScrobblingOverMobileNetworkDisabledSwitch; @InjectView(R.id.settings_lastfm_update_nowplaying_switch) public SwitchCompat isLastfmUpdateNowplayingEnabledSwitch; @InjectView(R.id.settings_container) public View settingContainer; @InjectView(R.id.settings_min_track_duration_in_seconds_desc) public TextView minDurationInSecondsDescription; @InjectView(R.id.settings_min_track_duration_in_percents_desc) public TextView minDurationInPercentsDescription; @InjectView(R.id.settings_theme_switch) public SwitchCompat themeSwitch; @InjectView(R.id.settings_logout_description) public TextView logoutDescription; @OnClick(R.id.settings_ignored_players) public void onIgnoredPlayersClick() { startActivity(new Intent(getActivity(), SettingsIgnoredPlayersActivity.class)); } @OnClick(R.id.settings_select_language_menu_item) public void onSelectLanguageClick() { startActivity(new Intent(getActivity(), SettingsSelectLanguageActivity.class)); } @OnClick(R.id.settings_disable_scrobbling_over_mobile_network) public void onDisableScrobblingOverMobileChanged() { SwitchCompat switchView = (SwitchCompat) getActivity().findViewById(R.id.settings_disable_scrobbling_over_mobile_network_switch); onDisableScrobblingOverMobileChanged(switchView.isChecked()); switchView.setChecked(!switchView.isChecked()); } @OnCheckedChanged(R.id.settings_disable_scrobbling_over_mobile_network_switch) public void onDisableScrobblingOverMobileChanged(boolean isChecked) { if (isChecked == WAILSettings.isEnableScrobblingOverMobileNetwork(getActivity())) { return; } WAILSettings.setDisableScrobblingOverMobileNetwork(getActivity(), isChecked); final String toast = isChecked ? getString(R.string.settings_scrobbling_over_mobile_network_enabled_toast) : getString(R.string.settings_scrobbling_over_mobile_network_disabled_toast); Toast.makeText(getActivity(), toast, Toast.LENGTH_SHORT).show(); EasyTracker.getInstance(getActivity()).send( MapBuilder.createEvent(GA_EVENT_SETTINGS_FRAGMENT, "Scrobbling over mobile network enabled: " + isChecked, null, isChecked ? 1L : 0L ).build() ); } @OnClick(R.id.settings_lastfm_update_nowplaying) public void onLastfmUpdateNowPlayingChanged() { SwitchCompat switchView = (SwitchCompat) getActivity().findViewById(R.id.settings_lastfm_update_nowplaying_switch); onLastfmUpdateNowPlayingChanged(switchView.isChecked()); switchView.setChecked(!switchView.isChecked()); } @OnCheckedChanged(R.id.settings_lastfm_update_nowplaying_switch) public void onLastfmUpdateNowPlayingChanged(boolean isChecked) { if (isChecked == WAILSettings.isLastfmNowplayingUpdateEnabled(getActivity())) { return; } WAILSettings.setLastfmNowplayingUpdateEnabled(getActivity(), isChecked); final String toast = isChecked ? getString(R.string.settings_lastfm_update_nowplaying_enabled_toast) : getString(R.string.settings_lastfm_update_nowplaying_disabled_toast); Toast.makeText(getActivity(), toast, Toast.LENGTH_SHORT).show(); EasyTracker.getInstance(getActivity()).send( MapBuilder.createEvent(GA_EVENT_SETTINGS_FRAGMENT, "lastFmUpdateNowPlaying enabled: " + isChecked, null, isChecked ? 1L : 0L ).build() ); } @OnClick(R.id.settings_theme) public void onThemeChanged() { SwitchCompat switchView = (SwitchCompat) getActivity().findViewById(R.id.settings_theme_switch); onThemeChanged(switchView.isChecked()); switchView.setChecked(!switchView.isChecked()); } @OnCheckedChanged(R.id.settings_theme_switch) public void onThemeChanged(boolean isChecked) { if (isChecked == (WAILSettings.getTheme(getActivity()) == WAILSettings.Theme.DARK)) { return; } WAILSettings.setTheme(getActivity(), isChecked ? WAILSettings.Theme.DARK : WAILSettings.Theme.LIGHT); ((BaseActivity) getActivity()).setTheme(); ((BaseActivity) getActivity()).restart(); } @OnClick(R.id.settings_sound_notifications) public void onSoundNotificationSettingClick() { startActivity(new Intent(getActivity(), SettingsSoundNotificationsActivity.class)); } @OnClick(R.id.settings_status_bar_notifications) public void onStatusBarNotificationSettingClick() { startActivity(new Intent(getActivity(), SettingsStatusBarNotificationsActivity.class)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(R.string.settings_actionbar_title); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main_settings, container, false); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.main_settings, menu); SwitchCompat isWailEnabledSwitch = (SwitchCompat) MenuItemCompat.getActionView(menu .findItem(R.id.main_settings_menu_is_wail_enabled)); isWailEnabledSwitch.setChecked(WAILSettings.isEnabled(getActivity())); isWailEnabledSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { WAILSettings.setEnabled(getActivity(), isChecked); final Toast toast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, (int) DisplayUnitsConverter.dpToPx(getActivity(), 60)); if (isChecked) { setUIStateWailEnabled(); toast.setText(R.string.settings_wail_enabled_toast); } else { setUIStateWailDisabled(); toast.setText(R.string.settings_wail_disabled_toast); } toast.show(); EasyTracker.getInstance(getActivity()).send(MapBuilder .createEvent( GA_EVENT_SETTINGS_FRAGMENT, "isWailEnabled changed, enabled: " + isChecked, null, isChecked ? 1L : 0L).build() ); } }); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.inject(this, view); if (WAILSettings.isEnabled(getActivity())) { setUIStateWailEnabled(); } else { setUIStateWailDisabled(); } String lang = WAILSettings.getLanguage(getActivity()); if (lang == null) { lang = getResources().getStringArray(R.array.settings_select_language_languages)[0]; } languageMenuItemDescription.setText(lang); refreshMinTrackDurationInPercents(); refreshMinTrackDurationInSeconds(); isScrobblingOverMobileNetworkDisabledSwitch.setChecked(WAILSettings.isEnableScrobblingOverMobileNetwork(getActivity())); isLastfmUpdateNowplayingEnabledSwitch.setChecked(WAILSettings.isLastfmNowplayingUpdateEnabled(getActivity())); logoutDescription.setText(WAILSettings.getLastfmUserName(getActivity())); themeSwitch.setChecked(WAILSettings.getTheme(getActivity()) == WAILSettings.Theme.DARK); try { buildVersionDescTextView.setText(getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName); } catch (Exception e) { buildVersionDescTextView.setText("unknown"); EasyTracker.getInstance(getActivity()).send(MapBuilder.createException("Can not set build version in settings: " + e.getMessage(), false).build()); } } @Override public void onStart() { super.onStart(); EasyTracker.getInstance(getActivity()).send(MapBuilder.createEvent(GA_EVENT_SETTINGS_FRAGMENT, "started", null, 1L).build()); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance(getActivity()).send(MapBuilder.createEvent(GA_EVENT_SETTINGS_FRAGMENT, "stopped", null, 0L).build()); } void setUIStateWailEnabled() { ViewUtil.setEnabledForAllChildrenRecursively((ViewGroup) settingContainer, true); } void setUIStateWailDisabled() { ViewUtil.setEnabledForAllChildrenRecursively((ViewGroup) settingContainer, false); } @OnClick(R.id.settings_min_track_duration_in_percents) void showMinTrackDurationInPercentsEditDialog() { final DialogFragmentWithSeekBar dialogFragmentWithSeekBar = DialogFragmentWithSeekBar.newInstance( getString(R.string.settings_min_track_elapsed_time_in_percent_dialog_title), getString(R.string.settings_min_track_elapsed_time_in_percent_dialog_description), WAILSettings.getMinTrackDurationInPercents(getActivity()) ); dialogFragmentWithSeekBar.setListener(this); dialogFragmentWithSeekBar.show(getFragmentManager(), "minTrackDurationInPercentsDialog"); } @OnClick(R.id.settings_min_track_duration_in_seconds) void showMinTrackDurationInSecondsEditDialog() { final DialogFragmentWithNumberPicker minTrackDurationInSecondsDialog = DialogFragmentWithNumberPicker.newInstance( getString(R.string.settings_min_track_elapsed_time_in_seconds_dialog_title), 30, 600, WAILSettings.getMinTrackDurationInSeconds(getActivity())); minTrackDurationInSecondsDialog.setListener(this); minTrackDurationInSecondsDialog.show(getFragmentManager(), "minTrackDurationInSecondsDialog"); } private void refreshMinTrackDurationInSeconds() { final int minTrackDurationInSeconds = WAILSettings.getMinTrackDurationInSeconds(getActivity()); minDurationInSecondsDescription.setText( getString( R.string.settings_min_track_elapsed_time_in_seconds_desc, minTrackDurationInSeconds + " " + WordFormUtil.getWordForm(minTrackDurationInSeconds, getResources().getStringArray(R.array.word_forms_second)) ) ); } private void refreshMinTrackDurationInPercents() { minDurationInPercentsDescription.setText( getString( R.string.settings_min_track_elapsed_time_in_percent_desc, WAILSettings.getMinTrackDurationInPercents(getActivity()) ) ); } @OnClick(R.id.settings_logout_menu_item) public void logout() { new MaterialDialog.Builder(getActivity()) .theme(Theme.DARK) .title(R.string.setting_logout_warning) .positiveText("Ok") .negativeText(R.string.dialog_cancel) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { WAILSettings.clearAllSettings(getActivity()); AppDBManager.getInstance(getActivity()).clearAll(); LocaleUtil.updateLanguage(getActivity(), null); startActivity(new Intent(getActivity(), MainActivity.class)); getActivity().finish(); } @Override public void onNegative(MaterialDialog dialog) { dialog.dismiss(); } }).build().show(); } @OnClick(R.id.settings_email_to_developers) public void emailToTheDeveloper() { try { final Intent emailIntent = new Intent(Intent.ACTION_SEND); String emailsString = getString(R.string.settings_developers_emails); String[] emails = emailsString.substring(0, emailsString.indexOf('(') - 1).split(","); emailIntent.putExtra(Intent.EXTRA_EMAIL, emails); emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.settings_email_to_the_developer_subj) + " " + buildVersionDescTextView.getText().toString()); emailIntent.setType("message/rfc822"); startActivity(Intent.createChooser(emailIntent, getString(R.string.settings_email_dialog_title))); EasyTracker.getInstance(getActivity()) .send(MapBuilder.createEvent(GA_EVENT_SETTINGS_FRAGMENT, "emailToTheDeveloperClicked", null, 1L).build()); } catch (Exception e) { EasyTracker.getInstance(getActivity()) .send(MapBuilder.createException("Can not send email to the developer: " + e, false).build()); } } @Override public void onDismiss() { refreshMinTrackDurationInPercents(); refreshMinTrackDurationInSeconds(); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-08-05"); this.setApiVersion("18.11.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package com.outerthoughts.notezap; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; public class SendIntentService extends IntentService { public static final String PARAM_IN_ZAP_TEXT = "zap"; private static final String ZAP_ENDPOINT = "https://zapier.com/hooks/catch/n/11lxg/"; // private LinkedList<String> queue = new LinkedList<String>(); public SendIntentService() { super("SendIntentService"); } @Override protected void onHandleIntent(Intent intent) { String zap = intent.getStringExtra(PARAM_IN_ZAP_TEXT); // queue.push(zap); while (true) { if (isNetworkAvailable()) { //catch failure to send sendZapNow(zap); break; //we are done. } else { // Log.i("NoteZap", "Network is not available. Wait for notification"); Log.i("NoteZap", "Network is not available. Sleep for 10 secs and try again. Thread id: " + Thread.currentThread().getId()); try { Thread.sleep(10*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //TODO: create broadcast listener, if possible? } } Log.i("NoteZap", "Done with zap: " + zap); } private void sendZapNow(String zap) { HttpClient myClient = new DefaultHttpClient(); HttpGet myConnection = new HttpGet(ZAP_ENDPOINT + "?zap=" + zap); String result = null; JSONObject json = null; try { HttpResponse response = myClient.execute(myConnection); result = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try{ json = new JSONObject(result); Log.i("ZAP result json: ", json.toString(2)); } catch ( JSONException e) { e.printStackTrace(); } } private boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); // if no network is available networkInfo will be null // otherwise check if we are connected if (networkInfo != null && networkInfo.isConnected()) { return true; } return false; } }
package net.dlogic.kryonet.common.manager; import net.dlogic.kryonet.common.constant.ErrorMessage; import net.dlogic.kryonet.common.entity.Room; import net.dlogic.kryonet.common.entity.User; public class RoomManager extends BaseManager<Room> { public void addUserToRoom(User user, int roomId) throws RoomManagerException { Room room = get(roomId); if (room.isFull()) { throw new RoomManagerException(ErrorMessage.ROOM_IS_FULL); } if (room.userList.contains(user)) { throw new RoomManagerException(ErrorMessage.USER_ALREADY_IN_ROOM); } room.userList.add(user); } public void removeUserToRoom(User user, int roomId) { get(roomId).userList.remove(user); } }
/** * * Sample.java * @author echeng (table2type.pl) * * the Sample * * */ package edu.yu.einstein.wasp.model; import java.util.Date; import java.util.List; import javax.persistence.*; import org.hibernate.envers.Audited; import org.hibernate.envers.NotAudited; import org.hibernate.validator.constraints.*; import org.codehaus.jackson.annotate.JsonIgnore; @Entity @Audited @Table(name="sample") public class Sample extends WaspModel { /** * sampleId * */ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) protected int sampleId; /** * setSampleId(int sampleId) * * @param sampleId * */ public void setSampleId (int sampleId) { this.sampleId = sampleId; } /** * getSampleId() * * @return sampleId * */ public int getSampleId () { return this.sampleId; } /** * typeSampleId * */ @Column(name="typesampleid") protected int typeSampleId; /** * setTypeSampleId(int typeSampleId) * * @param typeSampleId * */ public void setTypeSampleId (int typeSampleId) { this.typeSampleId = typeSampleId; } /** * getTypeSampleId() * * @return typeSampleId * */ public int getTypeSampleId () { return this.typeSampleId; } /** * subtypeSampleId * */ @Column(name="subtypesampleid") protected Integer subtypeSampleId; /** * setSubtypeSampleId(Integer subtypeSampleId) * * @param subtypeSampleId * */ public void setSubtypeSampleId (Integer subtypeSampleId) { this.subtypeSampleId = subtypeSampleId; } /** * getSubtypeSampleId() * * @return subtypeSampleId * */ public Integer getSubtypeSampleId () { return this.subtypeSampleId; } /** * submitterLabId * */ @Column(name="submitter_labid") protected int submitterLabId; /** * setSubmitterLabId(int submitterLabId) * * @param submitterLabId * */ public void setSubmitterLabId (int submitterLabId) { this.submitterLabId = submitterLabId; } /** * getSubmitterLabId() * * @return submitterLabId * */ public int getSubmitterLabId () { return this.submitterLabId; } /** * submitterUserId * */ @Column(name="submitter_userid") protected int submitterUserId; /** * setSubmitterUserId(int submitterUserId) * * @param submitterUserId * */ public void setSubmitterUserId (int submitterUserId) { this.submitterUserId = submitterUserId; } /** * getSubmitterUserId() * * @return submitterUserId * */ public int getSubmitterUserId () { return this.submitterUserId; } /** * submitterJobId * */ @Column(name="submitter_jobid") protected Integer submitterJobId; /** * setSubmitterJobId(Integer submitterJobId) * * @param submitterJobId * */ public void setSubmitterJobId (Integer submitterJobId) { this.submitterJobId = submitterJobId; } /** * getSubmitterJobId() * * @return submitterJobId * */ public Integer getSubmitterJobId () { return this.submitterJobId; } /** * isReceived * */ @Column(name="isreceived") protected int isReceived; /** * setIsReceived(int isReceived) * * @param isReceived * */ public void setIsReceived (int isReceived) { this.isReceived = isReceived; } /** * getIsReceived() * * @return isReceived * */ public int getIsReceived () { return this.isReceived; } /** * receiverUserId * */ @Column(name="receiver_userid") protected Integer receiverUserId; /** * setReceiverUserId(Integer receiverUserId) * * @param receiverUserId * */ public void setReceiverUserId (Integer receiverUserId) { this.receiverUserId = receiverUserId; } /** * getReceiverUserId() * * @return receiverUserId * */ public Integer getReceiverUserId () { return this.receiverUserId; } /** * receiveDts * */ @Column(name="receivedts") protected Date receiveDts; /** * setReceiveDts(Date receiveDts) * * @param receiveDts * */ public void setReceiveDts (Date receiveDts) { this.receiveDts = receiveDts; } /** * getReceiveDts() * * @return receiveDts * */ public Date getReceiveDts () { return this.receiveDts; } /** * name * */ @Column(name="name") protected String name; /** * setName(String name) * * @param name * */ public void setName (String name) { this.name = name; } /** * getName() * * @return name * */ public String getName () { return this.name; } /** * isGood * */ @Column(name="isgood") protected Integer isGood; /** * setIsGood(Integer isGood) * * @param isGood * */ public void setIsGood (Integer isGood) { this.isGood = isGood; } /** * getIsGood() * * @return isGood * */ public Integer getIsGood () { return this.isGood; } /** * isActive * */ @Column(name="isactive") protected int isActive; /** * setIsActive(int isActive) * * @param isActive * */ public void setIsActive (int isActive) { this.isActive = isActive; } /** * getIsActive() * * @return isActive * */ public int getIsActive () { return this.isActive; } /** * lastUpdTs * */ @Column(name="lastupdts") protected Date lastUpdTs; /** * setLastUpdTs(Date lastUpdTs) * * @param lastUpdTs * */ public void setLastUpdTs (Date lastUpdTs) { this.lastUpdTs = lastUpdTs; } /** * getLastUpdTs() * * @return lastUpdTs * */ public Date getLastUpdTs () { return this.lastUpdTs; } /** * lastUpdUser * */ @Column(name="lastupduser") protected int lastUpdUser; /** * setLastUpdUser(int lastUpdUser) * * @param lastUpdUser * */ public void setLastUpdUser (int lastUpdUser) { this.lastUpdUser = lastUpdUser; } /** * getLastUpdUser() * * @return lastUpdUser * */ public int getLastUpdUser () { return this.lastUpdUser; } /** * typeSample * */ @NotAudited @ManyToOne @JoinColumn(name="typesampleid", insertable=false, updatable=false) protected TypeSample typeSample; /** * setTypeSample (TypeSample typeSample) * * @param typeSample * */ public void setTypeSample (TypeSample typeSample) { this.typeSample = typeSample; this.typeSampleId = typeSample.typeSampleId; } /** * getTypeSample () * * @return typeSample * */ public TypeSample getTypeSample () { return this.typeSample; } /** * subtypeSample * */ @NotAudited @ManyToOne @JoinColumn(name="subtypesampleid", insertable=false, updatable=false) protected SubtypeSample subtypeSample; /** * setSubtypeSample (SubtypeSample subtypeSample) * * @param subtypeSample * */ public void setSubtypeSample (SubtypeSample subtypeSample) { this.subtypeSample = subtypeSample; this.subtypeSampleId = subtypeSample.subtypeSampleId; } /** * getSubtypeSample () * * @return subtypeSample * */ public SubtypeSample getSubtypeSample () { return this.subtypeSample; } /** * job * */ @NotAudited @ManyToOne @JoinColumn(name="submitter_jobid", insertable=false, updatable=false) protected Job job; /** * setJob (Job job) * * @param job * */ public void setJob (Job job) { this.job = job; this.submitterJobId = job.jobId; } /** * getJob () * * @return job * */ public Job getJob () { return this.job; } /** * lab * */ @NotAudited @ManyToOne @JoinColumn(name="submitter_labid", insertable=false, updatable=false) protected Lab lab; /** * setLab (Lab lab) * * @param lab * */ public void setLab (Lab lab) { this.lab = lab; this.submitterLabId = lab.labId; } /** * getLab () * * @return lab * */ public Lab getLab () { return this.lab; } /** * user * */ @NotAudited @ManyToOne @JoinColumn(name="submitter_userid", insertable=false, updatable=false) protected User user; /** * setUser (User user) * * @param user * */ public void setUser (User user) { this.user = user; this.submitterUserId = user.UserId; } /** * getUser () * * @return user * */ public User getUser () { return this.user; } /** * sampleMeta * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<SampleMeta> sampleMeta; /** * getSampleMeta() * * @return sampleMeta * */ public List<SampleMeta> getSampleMeta() { return this.sampleMeta; } /** * setSampleMeta * * @param sampleMeta * */ public void setSampleMeta (List<SampleMeta> sampleMeta) { this.sampleMeta = sampleMeta; } /** * sampleSource * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<SampleSource> sampleSource; /** * getSampleSource() * * @return sampleSource * */ public List<SampleSource> getSampleSource() { return this.sampleSource; } /** * setSampleSource * * @param sampleSource * */ public void setSampleSource (List<SampleSource> sampleSource) { this.sampleSource = sampleSource; } /** * sampleSourceViaSourceSampleId * */ @NotAudited @OneToMany @JoinColumn(name="source_sampleid", insertable=false, updatable=false) protected List<SampleSource> sampleSourceViaSourceSampleId; /** * getSampleSourceViaSourceSampleId() * * @return sampleSourceViaSourceSampleId * */ public List<SampleSource> getSampleSourceViaSourceSampleId() { return this.sampleSourceViaSourceSampleId; } /** * setSampleSourceViaSourceSampleId * * @param sampleSource * */ public void setSampleSourceViaSourceSampleId (List<SampleSource> sampleSource) { this.sampleSourceViaSourceSampleId = sampleSource; } /** * sampleBarcode * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<SampleBarcode> sampleBarcode; /** * getSampleBarcode() * * @return sampleBarcode * */ public List<SampleBarcode> getSampleBarcode() { return this.sampleBarcode; } /** * setSampleBarcode * * @param sampleBarcode * */ public void setSampleBarcode (List<SampleBarcode> sampleBarcode) { this.sampleBarcode = sampleBarcode; } /** * sampleLab * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<SampleLab> sampleLab; /** * getSampleLab() * * @return sampleLab * */ public List<SampleLab> getSampleLab() { return this.sampleLab; } /** * setSampleLab * * @param sampleLab * */ public void setSampleLab (List<SampleLab> sampleLab) { this.sampleLab = sampleLab; } /** * jobSample * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<JobSample> jobSample; /** * getJobSample() * * @return jobSample * */ public List<JobSample> getJobSample() { return this.jobSample; } /** * setJobSample * * @param jobSample * */ public void setJobSample (List<JobSample> jobSample) { this.jobSample = jobSample; } /** * sampleCell * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<SampleCell> sampleCell; /** * getSampleCell() * * @return sampleCell * */ public List<SampleCell> getSampleCell() { return this.sampleCell; } /** * setSampleCell * * @param sampleCell * */ public void setSampleCell (List<SampleCell> sampleCell) { this.sampleCell = sampleCell; } /** * sampleFile * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<SampleFile> sampleFile; /** * getSampleFile() * * @return sampleFile * */ public List<SampleFile> getSampleFile() { return this.sampleFile; } /** * setSampleFile * * @param sampleFile * */ public void setSampleFile (List<SampleFile> sampleFile) { this.sampleFile = sampleFile; } /** * run * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<Run> run; /** * getRun() * * @return run * */ public List<Run> getRun() { return this.run; } /** * setRun * * @param run * */ public void setRun (List<Run> run) { this.run = run; } /** * runLane * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<RunLane> runLane; /** * getRunLane() * * @return runLane * */ public List<RunLane> getRunLane() { return this.runLane; } /** * setRunLane * * @param runLane * */ public void setRunLane (List<RunLane> runLane) { this.runLane = runLane; } /** * statesample * */ @NotAudited @OneToMany @JoinColumn(name="sampleid", insertable=false, updatable=false) protected List<Statesample> statesample; /** * getStatesample() * * @return statesample * */ public List<Statesample> getStatesample() { return this.statesample; } /** * setStatesample * * @param statesample * */ public void setStatesample (List<Statesample> statesample) { this.statesample = statesample; } }
package com.learning.ads; public class EulerGCD { /** * A recursive implementation of EULER GCD algorithm * @param a * @param b * @return gcd of a and b */ public static int gcd(int a, int b){ if(b == 0){ return a; } return gcd(b, a%b); } public static void main(String[] args) { System.out.println(gcd(1071,462)); } }
package exnihiloadscensio.tiles; import java.util.List; import java.util.Random; import exnihiloadscensio.enchantments.ENEnchantments; import exnihiloadscensio.networking.PacketHandler; import exnihiloadscensio.registries.SieveRegistry; import exnihiloadscensio.registries.types.Siftable; import exnihiloadscensio.util.BlockInfo; import exnihiloadscensio.util.Util; import lombok.Getter; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Enchantments; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class TileSieve extends TileEntity { private BlockInfo currentStack; @Getter private byte progress = 0; @Getter private ItemStack meshStack; private static Random rand = new Random(); public TileSieve() {} /** * Sets the mesh type in the sieve. * @param newMesh * @return true if setting is successful. */ public boolean setMesh(ItemStack newMesh) { return setMesh(newMesh, false); } public boolean setMesh(ItemStack newMesh, boolean simulate) { if (progress != 0) return false; if (meshStack == null) { if (!simulate) { meshStack = newMesh.copy(); this.markDirty(); } return true; } if (meshStack != null && newMesh == null) { //Removing if (!simulate) { meshStack = null; this.markDirty(); } return true; } return false; } public boolean addBlock(ItemStack stack) { if (currentStack == null && SieveRegistry.canBeSifted(stack)) { if (meshStack == null) return false; int meshLevel = meshStack.getItemDamage(); for (Siftable siftable : SieveRegistry.getDrops(stack)) { if (siftable.getMeshLevel() == meshLevel) { currentStack = new BlockInfo(stack); PacketHandler.sendNBTUpdate(this); return true; } } } return false; } public void doSieving(EntityPlayer player) { if (currentStack == null) { return; } int efficiency = EnchantmentHelper.getEnchantmentLevel(ENEnchantments.efficiency, meshStack); efficiency += EnchantmentHelper.getEnchantmentLevel(Enchantments.EFFICIENCY, meshStack); int fortune = EnchantmentHelper.getEnchantmentLevel(ENEnchantments.fortune, meshStack); fortune += EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, meshStack); progress += 10 + 5 * efficiency; PacketHandler.sendNBTUpdate(this); if (progress >= 100) { List<ItemStack> drops = SieveRegistry.getRewardDrops(rand, currentStack.getBlockState(), meshStack.getMetadata(), fortune); if(drops != null) { for (int i = 0 ; i < EnchantmentHelper.getEnchantmentLevel(ENEnchantments.luckOfTheSea, meshStack) ; i++) { if (worldObj.rand.nextDouble() < 0.5) drops.add(new ItemStack(Items.FISH)); } drops.forEach(stack -> Util.dropItemInWorld(this, player, stack, 1)); } resetSieve(); } } private void resetSieve() { progress = 0; currentStack = null; PacketHandler.sendNBTUpdate(this); } @SideOnly(Side.CLIENT) public TextureAtlasSprite getTexture() { if (currentStack != null) { return Util.getTextureFromBlockState(currentStack.getBlockState()); } return null; } @Override public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState) { return oldState.getBlock() != newState.getBlock(); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { if (currentStack != null) { NBTTagCompound stackTag = currentStack.writeToNBT(new NBTTagCompound()); tag.setTag("stack", stackTag); } if (meshStack != null) { NBTTagCompound meshTag = meshStack.writeToNBT(new NBTTagCompound()); tag.setTag("mesh", meshTag); } tag.setByte("progress", progress); return super.writeToNBT(tag); } @Override public void readFromNBT(NBTTagCompound tag) { if (tag.hasKey("stack")) currentStack = BlockInfo.readFromNBT(tag.getCompoundTag("stack")); else currentStack = null; if (tag.hasKey("mesh")) meshStack = ItemStack.loadItemStackFromNBT(tag.getCompoundTag("mesh")); else meshStack = null; progress = tag.getByte("progress"); super.readFromNBT(tag); } @Override public SPacketUpdateTileEntity getUpdatePacket() { NBTTagCompound tag = new NBTTagCompound(); this.writeToNBT(tag); return new SPacketUpdateTileEntity(this.pos, this.getBlockMetadata(), tag); } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) { NBTTagCompound tag = pkt.getNbtCompound(); readFromNBT(tag); } @Override public NBTTagCompound getUpdateTag() { NBTTagCompound tag = writeToNBT(new NBTTagCompound()); return tag; } }
package com.lhkbob.entreri; /** * <p> * Result represents a computed result, preferably that of a bulk computation, * performed by a Controller. Results allow Controllers to easily pass data to * other controllers that might be interested in their computations. * </p> * <p> * Controllers that wish to expose results must define an interface that is * capable of receiving their computations. The signature of this method is * entirely up to the Controller. Then, the controller wraps the computed * results in an internal Result implementation that knows how to invoke the * listener interface defined previously with the just computed data. To provide * to all interested Controllers, the {@link ControllerManager#supply(Result)} * method can be used. * </p> * <p> * To receive computed results, Controllers merely have to implement the * listener interfaces defined by the controllers of interest and store the * supplied results. * </p> * * @author Michael Ludwig * @param <T> The listener type */ public interface Result<T> { /** * <p> * Supply this result to the provided listener of type T. It is expected * that a listener interface will define some method that enables compatible * Result implementations to inject the computed data. * </p> * <p> * This injection or supplying is performed by this method. Controllers that * compute results will define interfaces as appropriate to receive their * results, and result implementations to provide those results. * </p> * * @param listener The listener to receive the event */ public void supply(T listener); /** * @return The listener interface this result is supplied to */ public Class<T> getListenerType(); }
package net.miz_hi.smileessence.menu; import twitter4j.StatusUpdate; import net.miz_hi.smileessence.Client; import net.miz_hi.smileessence.activity.MainActivity; import net.miz_hi.smileessence.activity.SettingActivity; import net.miz_hi.smileessence.async.AsyncFavoriteTask; import net.miz_hi.smileessence.async.AsyncTweetTask; import net.miz_hi.smileessence.async.ConcurrentAsyncTaskHelper; import net.miz_hi.smileessence.core.EnumPreferenceKey; import net.miz_hi.smileessence.dialog.DialogAdapter; import net.miz_hi.smileessence.dialog.ReviewDialogHelper; import net.miz_hi.smileessence.dialog.SeekBarDialogHelper; import net.miz_hi.smileessence.status.StatusModel; import android.app.Activity; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; public class StatusMenuReview extends StatusMenuItemBase { public StatusMenuReview(Activity activity, DialogAdapter adapter, StatusModel model) { super(activity, adapter, model); } @Override public boolean isVisible() { return true; } @Override public String getText() { return "r["; } @Override public void work() { final ReviewDialogHelper helper = new ReviewDialogHelper(_activity, "cC[g]"); helper.setSeekBarMax(4); helper.setSeekBarStart(0); helper.setLevelCorrect(1); helper.setOnClickListener(new OnClickListener() { public void onClick(DialogInterface dialog, int which) { int star = helper.getProgress() + 1; StringBuilder builder = new StringBuilder(); for(int i = 0; i < 5; i++) { if(i < star) { builder.append(""); } else { builder.append(""); } } builder.append("\r\n"); builder.append("Rg: "); builder.append(helper.getText()); builder.append("\r\n"); builder.append("( http://twitter.com/"); builder.append(_model.screenName); builder.append("/status/"); builder.append(_model.statusId); builder.append(" )"); ConcurrentAsyncTaskHelper.addAsyncTask(new AsyncTweetTask(new StatusUpdate(builder.toString()))); ConcurrentAsyncTaskHelper.addAsyncTask(new AsyncFavoriteTask(_model.statusId)); } }); helper.createSeekBarDialog().show(); } }
package fi.eis.applications.dom4j; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Node; import org.dom4j.io.SAXReader; import org.joda.time.DateTime; @SuppressWarnings("unchecked") public class Example { public static void main(String args[]) throws Exception { System.out.println("Running"); // Create a null Document Object Document theXML = null; // Get the document of the XML and assign to Document object theXML = fromUrl("http: // Place the root element of theXML into a variable List<? extends Node> items = (List<? extends Node>) theXML .selectNodes("//rss/channel/item"); // RFC-dictated date format used with RSS DateFormat dateFormatterRssPubDate = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH); // today started at this time DateTime timeTodayStartedAt = new DateTime().withTimeAtStartOfDay(); for (Node node : items) { String pubDate = node.valueOf("pubDate"); DateTime date = new DateTime(dateFormatterRssPubDate.parse(pubDate)); if ((date).isAfter(timeTodayStartedAt)) { // it's today, do something! System.out.println("Today: " + date); } else { System.out.println("Not today: " + date); } } } public static Document fromUrl(String url) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(url); return document; } }
package com.timepath.hl2; import com.timepath.hl2.io.captions.VCCD; import com.timepath.plaf.x.filechooser.BaseFileChooser; import com.timepath.plaf.x.filechooser.NativeFileChooser; import com.timepath.steam.io.VDF; import com.timepath.steam.io.VDFNode; import com.timepath.steam.io.storage.ACF; import com.timepath.utils.Trie; import com.timepath.vfs.SimpleVFile; import org.apache.commons.io.IOUtils; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.*; import java.text.MessageFormat; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import java.util.zip.CRC32; /** * @author TimePath */ @SuppressWarnings("serial") class VCCDTest extends JFrame { private static final Logger LOG = Logger.getLogger(VCCDTest.class.getName()); private static final Preferences prefs = Preferences.userRoot() .node("timepath") .node("hl2-caption-editor"); private static final String CHAN_UNKNOWN = "CHAN_UNKNOWN"; private final Trie trie = new Trie(); private final Map<Integer, StringPair> hashmap = new HashMap<>(); private JCheckBoxMenuItem swapBytes; private File saveFile; private JTable jTable1; private JTextField jTextField3; private JTextField jTextField4; private VCCDTest() { // Load known mappings from preferences try { for(String channel : prefs.childrenNames()) { for(String name : prefs.node(channel).keys()) { int hash = prefs.getInt(name, -1); LOG.log(Level.FINER, "{0} = {1}", new Object[] { name, hash }); if(hash != -1) { hashmap.put(hash, new StringPair(name, channel)); trie.add(name); } } } } catch(BackingStoreException ex) { LOG.log(Level.SEVERE, null, ex); } initComponents(); jTextField3.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { updateHash(); } @Override public void removeUpdate(DocumentEvent e) { updateHash(); } @Override public void changedUpdate(DocumentEvent e) { updateHash(); } public void updateHash() { jTextField4.setText(hexFormat(VCCD.hash(jTextField3.getText()))); } }); } /** * @param args * the command line arguments * * @throws java.io.IOException */ public static void main(String... args) throws IOException { try { if(args.length > 0) { List<VCCD.VCCDEntry> in = VCCD.parse(new FileInputStream(args[0])); Map<Integer, StringPair> hashmap = new HashMap<>(); for(VCCD.VCCDEntry i : in) { // learning Object crc = i.getHash(); String token = i.getKey(); long hash = Long.parseLong(crc.toString().toLowerCase(), 16); hashmap.put((int) hash, new StringPair(token, CHAN_UNKNOWN)); } persistHashmap(hashmap); VCCD.save(in, new FileOutputStream("closecaption_english.dat")); return; } } catch(FileNotFoundException ex) { LOG.log(Level.SEVERE, null, ex); } EventQueue.invokeLater(new Runnable() { @Override public void run() { VCCDTest c = new VCCDTest(); c.setLocationRelativeTo(null); c.setVisible(true); } }); } private static void persistHashmap(Map<Integer, StringPair> map) { for(Map.Entry<Integer, StringPair> entry : map.entrySet()) { Integer key = entry.getKey(); String value = entry.getValue().name; if(( key == null ) || ( value == null )) { continue; } prefs.node(entry.getValue().channel).putInt(value, key); } } private static String hexFormat(int in) { String str = Integer.toHexString(in).toUpperCase(); while(str.length() < 8) { str = '0' + str; } return str; } private static TableCellEditor getKeyEditor() { JTextField t = new JTextField(); // new StringAutoCompleter(t, trie, 2); return new DefaultCellEditor(t); } private void generateHash() { new Thread(new Runnable() { @Override public void run() { JFrame frame = new JFrame("Generating hash codes..."); JProgressBar pb = new JProgressBar(); pb.setIndeterminate(true); frame.add(pb); frame.setMinimumSize(new Dimension(300, 50)); frame.setLocationRelativeTo(null); frame.setVisible(true); Map<Integer, StringPair> map = new HashMap<>(); LOG.info("Generating hash codes ..."); try { CRC32 crc = new CRC32(); List<SimpleVFile> caps = ACF.fromManifest(440).find("game_sounds"); pb.setMaximum(caps.size()); pb.setIndeterminate(false); int i = 0; for(SimpleVFile f : caps) { LOG.log(Level.INFO, "Parsing {0}", f); VDFNode root = VDF.load(f.openStream()); for(VDFNode node : root.getNodes()) { String str = (String) node.getCustom(); String channel = (String) node.getValue("channel", CHAN_UNKNOWN); LOG.log(Level.FINER, str); crc.reset(); crc.update(str.getBytes()); map.put((int) crc.getValue(), new StringPair(str, channel)); } pb.setValue(++i); } } catch(IOException ex) { LOG.log(Level.WARNING, "Error generating hash codes", ex); } hashmap.putAll(map); persistHashmap(hashmap); frame.dispose(); } }).start(); } private String attemptDecode(int hash) { if(!hashmap.containsKey(hash)) { // logger.log(Level.INFO, "hashmap does not contain {0}", hash); return null; } return hashmap.get(hash).name; } private void initMenu() { JMenuBar menuBar = new JMenuBar(); JMenu jMenu1 = new JMenu("File"); jMenu1.add(new JMenuItem("New", 'N') {{ setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK)); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { createNew(e); } }); }}); jMenu1.add(new JMenuItem("Open", 'O') {{ setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK)); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadCaptions(e); } }); }}); jMenu1.add(new JMenuItem("Import", 'I') {{ setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK)); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { importCaptions(e); } }); }}); jMenu1.add(new JMenuItem("Export", 'X') {{ addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { export(e); } }); }}); jMenu1.add(new JMenuItem("Export all", 'E') {{ addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { exportAll(e); } }); }}); jMenu1.add(new JMenuItem("Generate hash codes") {{ addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { generateHash(e); } }); }}); jMenu1.add(new JMenuItem("Save", 'S') {{ setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveCaptions(e); } }); }}); jMenu1.add(new JMenuItem("Save As...", 'V') {{ addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveCaptionsAs(e); } }); }}); menuBar.add(jMenu1); JMenu jMenu2 = new JMenu("Edit"); jMenu2.add(new JMenuItem("Insert row") {{ setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, InputEvent.CTRL_MASK)); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { insertRow(e); } }); }}); jMenu2.add(new JMenuItem("Delete row") {{ setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, InputEvent.CTRL_MASK)); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { deleteRow(e); } }); }}); jMenu2.add(new JMenuItem("Goto") {{ addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { gotoRow(e); } }); }}); menuBar.add(jMenu2); menuBar.add(new JMenu("Settings") {{ add(swapBytes = new JCheckBoxMenuItem("Swap byte order")); }}); JMenu jMenu3 = new JMenu("Help"); jMenu3.add(new JMenuItem("Formatting") {{ setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { formattingHelp(e); } }); }}); menuBar.add(jMenu3); setJMenuBar(menuBar); } private void initComponents() { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setTitle("Caption Editor"); getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); getContentPane().add(new JPanel() {{ setBorder(BorderFactory.createTitledBorder("CRC32")); setMaximumSize(new Dimension(2147483647, 83)); setLayout(new BorderLayout()); add(jTextField3 = new JTextField(), BorderLayout.PAGE_START); jTextField4 = new JTextField(); jTextField4.setEditable(false); jTextField4.setText("The CRC will appear here"); add(jTextField4, BorderLayout.PAGE_END); }}); jTable1 = new JTable(); jTable1.setAutoCreateRowSorter(true); jTable1.setModel(new DefaultTableModel(new Object[][] { }, new String[] { "CRC32", "Key", "Value" }) { Class[] types = { Object.class, String.class, String.class }; boolean[] canEdit = { false, true, true }; @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return canEdit[column]; } }); jTable1.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); jTable1.setRowHeight(24); if(jTable1.getColumnModel().getColumnCount() > 0) { jTable1.getColumnModel().getColumn(0).setMinWidth(85); jTable1.getColumnModel().getColumn(0).setPreferredWidth(85); jTable1.getColumnModel().getColumn(0).setMaxWidth(85); jTable1.getColumnModel().getColumn(1).setPreferredWidth(160); jTable1.getColumnModel().getColumn(1).setCellEditor(getKeyEditor()); jTable1.getColumnModel().getColumn(2).setPreferredWidth(160); } getContentPane().add(new JScrollPane(jTable1)); initMenu(); pack(); } private void loadCaptions(ActionEvent evt) { try { NativeFileChooser fc = new NativeFileChooser(); fc.setTitle("Open"); fc.addFilter(new BaseFileChooser.ExtensionFilter("VCCD Binary Files", ".dat")); fc.setParent(this); File[] files = fc.choose(); if(files == null) { return; } List<VCCD.VCCDEntry> entries; try { entries = VCCD.load(new FileInputStream(files[0])); } catch(FileNotFoundException ex) { LOG.log(Level.SEVERE, null, ex); return; } LOG.log(Level.INFO, "Entries: {0}", entries.size()); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); for(int i = model.getRowCount() - 1; i >= 0; i model.removeRow(i); } for(VCCD.VCCDEntry entry : entries) { model.addRow(new Object[] { hexFormat(entry.getHash()), attemptDecode(entry.getHash()), entry.getValue() }); } saveFile = files[0]; } catch(IOException ex) { LOG.log(Level.SEVERE, null, ex); } } private void save(boolean flag) { if(( saveFile == null ) || flag) { try { NativeFileChooser fc = new NativeFileChooser(); fc.setDialogType(BaseFileChooser.DialogType.SAVE_DIALOG); fc.setTitle("Save (as closecaption_<language>.dat)"); fc.addFilter(new BaseFileChooser.ExtensionFilter("VCCD Binary Files", ".dat")); fc.setParent(this); File[] fs = fc.choose(); if(fs == null) { return; } saveFile = fs[0]; } catch(IOException ex) { LOG.log(Level.SEVERE, null, ex); return; } } if(jTable1.isEditing()) { jTable1.getCellEditor().stopCellEditing(); } List<VCCD.VCCDEntry> entries = new LinkedList<>(); TableModel model = jTable1.getModel(); for(int i = 0; i < model.getRowCount(); i++) { Object crc = model.getValueAt(i, 0); if(( model.getValueAt(i, 1) != null ) && !model.getValueAt(i, 1).toString().isEmpty()) { crc = hexFormat(VCCD.hash(model.getValueAt(i, 1).toString())); } int hash = (int) Long.parseLong(crc.toString().toLowerCase(), 16); Object key = model.getValueAt(i, 1); String token = ( key instanceof String ) ? key.toString() : null; if(!hashmap.containsKey(hash)) { hashmap.put(hash, new StringPair(token, CHAN_UNKNOWN)); } entries.add(new VCCD.VCCDEntry(hash, model.getValueAt(i, 2).toString())); } persistHashmap(hashmap); try { VCCD.save(entries, new FileOutputStream(saveFile), swapBytes.isSelected()); } catch(IOException ex) { LOG.log(Level.SEVERE, null, ex); } } private void saveCaptions(ActionEvent evt) { save(false); } private void importCaptions(ActionEvent evt) { try { NativeFileChooser fc = new NativeFileChooser(); fc.setTitle("Import"); fc.setParent(this); fc.addFilter(new BaseFileChooser.ExtensionFilter("VCCD Source Files", ".txt")); File[] files = fc.choose(); if(files == null) { return; } List<VCCD.VCCDEntry> entries = VCCD.parse(new FileInputStream(files[0])); LOG.log(Level.INFO, "Entries: {0}", entries.size()); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); for(int i = model.getRowCount() - 1; i >= 0; i model.removeRow(i); } for(VCCD.VCCDEntry entrie : entries) { int hash = entrie.getHash(); String token = entrie.getKey(); if(!hashmap.containsKey(hash)) { hashmap.put(hash, new StringPair(token, CHAN_UNKNOWN)); } model.addRow(new Object[] { hexFormat(entrie.getHash()), entrie.getKey(), entrie.getValue() }); } persistHashmap(hashmap); } catch(IOException ex) { LOG.log(Level.SEVERE, null, ex); } } private void insertRow(ActionEvent evt) { DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); model.addRow(new Object[] { 0, "", "" }); } private void deleteRow(ActionEvent evt) { DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); int newRow = Math.min(jTable1.getSelectedRow(), jTable1.getRowCount() - 1); if(jTable1.getSelectedRow() == ( jTable1.getRowCount() - 1 )) { newRow = jTable1.getRowCount() - 2; } LOG.log(Level.FINER, "New row: {0}", newRow); model.removeRow(jTable1.getSelectedRow()); if(jTable1.getRowCount() > 0) { jTable1.setRowSelectionInterval(newRow, newRow); } } private void createNew(ActionEvent evt) { DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); for(int i = model.getRowCount() - 1; i >= 0; i model.removeRow(i); } model.addRow(new Object[] { 0, "", "" }); } private void formattingHelp(ActionEvent evt) { String message = "Unable to load"; try { message = IOUtils.toString(getClass().getResource("/VCCDTest.txt")); } catch(IOException ignored) { } JScrollPane jsp = new JScrollPane(new JTextArea(message)); jsp.setPreferredSize(new Dimension(500, 500)); JDialog dialog = new JOptionPane(jsp, JOptionPane.INFORMATION_MESSAGE).createDialog(this, "Formatting"); dialog.setResizable(true); dialog.setModal(false); dialog.setVisible(true); } private void export(ActionEvent evt) { StringBuilder sb = new StringBuilder(jTable1.getRowCount() * 100); // rough estimate TableModel model = jTable1.getModel(); for(int i = 0; i < model.getRowCount(); i++) { sb.append(MessageFormat.format("{0}\t{1}\n", model.getValueAt(i, 0), model.getValueAt(i, 2))); } JTextArea pane = new JTextArea(sb.toString()); Dimension s = Toolkit.getDefaultToolkit().getScreenSize(); pane.setLineWrap(false); pane.setPreferredSize(new Dimension(s.width / 3, s.height / 2)); pane.setEditable(false); pane.setOpaque(false); pane.setBackground(new Color(0, 0, 0, 0)); JScrollPane jsp = new JScrollPane(pane); jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); JOptionPane.showMessageDialog(this, jsp, "Hash List", JOptionPane.INFORMATION_MESSAGE); } private int showInputDialog() { String inputValue = JOptionPane.showInputDialog("Enter row", jTable1.getSelectedRow() + 1); int intValue = -1; if(inputValue != null) { try { intValue = Integer.parseInt(inputValue) - 1; } catch(NumberFormatException e) { showInputDialog(); } if(intValue < 0) { showInputDialog(); } } return intValue; } private void gotoRow(ActionEvent evt) { int row = showInputDialog(); if(row < 0) { return; } if(row > jTable1.getRowCount()) { row = jTable1.getRowCount(); } jTable1.setRowSelectionInterval(row, row); jTable1.scrollRectToVisible(jTable1.getCellRect(row, 0, true)); } private void saveCaptionsAs(ActionEvent evt) { save(true); } private void generateHash(ActionEvent evt) { generateHash(); } private void exportAll(ActionEvent evt) { try { NativeFileChooser fc = new NativeFileChooser(); fc.setDialogType(BaseFileChooser.DialogType.SAVE_DIALOG); fc.setTitle("Export"); fc.addFilter(new BaseFileChooser.ExtensionFilter("XML", ".xml")); fc.setParent(this); File[] fs = fc.choose(); if(fs == null) { return; } saveFile = fs[0]; prefs.exportSubtree(new FileOutputStream(saveFile)); } catch(IOException | BackingStoreException ex) { LOG.log(Level.SEVERE, null, ex); } } private static class StringPair { String channel, name; StringPair(String name, String channel) { this.channel = channel; this.name = name; } } }
package fi.tekislauta.webserver; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import fi.tekislauta.db.Database; import fi.tekislauta.db.objects.BoardDao; import fi.tekislauta.db.objects.DaoException; import fi.tekislauta.db.objects.ModelValidationException; import fi.tekislauta.db.objects.PostDao; import fi.tekislauta.models.Board; import fi.tekislauta.models.Post; import fi.tekislauta.models.Result; import spark.Request; import static spark.Spark.*; import java.io.PrintStream; import java.util.Map; import java.util.Base64; public class Webserver { private final int port; private final Gson gson; //private final Database db; private final BoardDao boardDao; private final PostDao postDao; private final String USER = System.getenv("USER"); private final String PW = System.getenv("PW"); public Webserver(int port) { this.port = port; this.gson = new Gson(); Database db = new Database(); this.boardDao = new BoardDao(db); this.postDao = new PostDao(db); } public void listen() { port(this.port); exception(ModelValidationException.class, (exception, req, res) -> { res.status(400); // "Bad request" Result r = new Result(); r.setStatus("Error"); r.setData("Malformed request or missing data! " + exception.getMessage()); res.body(gson.toJson(r)); }); exception(JsonSyntaxException.class, (ex, req, res) -> { res.status(400); // "Bad request" Result r = new Result(); r.setStatus("Error"); r.setData("Malformed request! Please check your JSON syntax!"); }); exception(DaoException.class, (exception, req, res) -> { res.status(500); // "Internal server error" Result r = new Result(); r.setStatus("Error"); r.setData("A server error has occurred."); dumpRequestException(req, exception); res.body(gson.toJson(r)); }); // spark starts listening when first method listener is added, I think ~cx get("/api/boards/", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); r.setData(boardDao.findAll("")); return gson.toJson(r); }); get("/api/boards/:abbreviation", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); r.setData(boardDao.find(req.params("abbreviation"))); return gson.toJson(r); }); get("/api/boards/:board/posts/", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); r.setData(postDao.findAll(req.params("board"))); return gson.toJson(r); }); get("/api/boards/:board/posts/:page", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); r.setData(postDao.findPageTopics(req.params("board"), req.params("page"))); return gson.toJson(r); }); get("/api/jerry", (req, res) -> { return "\uD83D\uDC4C\uD83D\uDC40\uD83D\uDC4C\uD83D\uDC40\uD83D\uDC4C\uD83D\uDC40\uD83D\uDC4C\uD83D\uDC40\uD83D\uDC4C\uD83D\uDC40 good shit go౦ԁ sHit\uD83D\uDC4C thats some good\uD83D\uDC4C\uD83D\uDC4Cshit right\uD83D\uDC4C\uD83D\uDC4Cthere\uD83D\uDC4C\uD83D\uDC4C\uD83D\uDC4C rightthere if i do ƽaү so my self \uD83D\uDCAF i say so \uD83D\uDCAF thats what im talking about right there right there (chorus: ʳᶦᵍʰᵗ ᵗʰᵉʳᵉ) mMMMMᎷМ\uD83D\uDCAF \uD83D\uDC4C\uD83D\uDC4C \uD83D\uDC4CНO0ОଠOOOOOОଠଠOoooᵒᵒᵒᵒᵒᵒᵒᵒᵒ\uD83D\uDC4C \uD83D\uDC4C\uD83D\uDC4C \uD83D\uDC4C \uD83D\uDCAF \uD83D\uDC4C \uD83D\uDC40 \uD83D\uDC40 \uD83D\uDC40 \uD83D\uDC4C\uD83D\uDC4CGood shit"; }); get("/api/boards/:board/posts/topics/:topic", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); r.setData(postDao.findByTopic(req.params("board"), req.params("topic"))); return gson.toJson(r); }); get("/api/posts/:id", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); r.setData(postDao.find(req.params("id"))); return gson.toJson(r); }); post("api/boards/:board/posts/", (req, res) -> { // This endpoint creates new topics. Responses go to POST api/boards/:board/posts/topics/:topic res.header("Content-Type", "application/json; charset=utf-8"); Result result = new Result(); Post post = gson.fromJson(req.body(), Post.class); // should parse subject and message if (post.getTopic_id() != null) { // This endpoint only creates new topics. No replies. Nada. noty. res.status(400); result.setStatus("Error"); result.setData("This endpoint creates new topics. Topic replies go to POST api/boards/:board/posts/topics/:topic"); return result; } post.setBoard_abbrevition(req.params("board")); post.setIp(req.ip()); post.setPost_time(getUnixTimestamp()); result.setData(postDao.post(post)); return result; }, gson::toJson); post("api/boards/:board/posts/topics/:topic", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); Map json = gson.fromJson(req.body(), Map.class); Post p = new Post(); p.setBoard_abbrevition(req.params("board")); p.setTopic_id(Integer.parseInt(req.params("topic"))); p.setIp(req.ip()); p.setSubject((String) json.get("subject")); p.setMessage((String) json.get("message")); p.setPost_time(getUnixTimestamp()); r.setData(postDao.post(p)); return gson.toJson(r); }); post("/api/boards/", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); Map json = gson.fromJson(req.body(), Map.class); Board b = new Board(); b.setName((String) json.get("name")); b.setAbbreviation((String) json.get("abbreviation")); b.setDescription((String) json.get("description")); r.setData(boardDao.post(b)); return gson.toJson(r); }); delete("api/posts/:id", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); if (!isAuthrorized(req.headers("Authorization"))) { res.status(401); // unauthorized r.setStatus("Unauthorized"); } postDao.delete(req.params("id")); return gson.toJson(r); }); delete("api/boards/:id", (req, res) -> { res.header("Content-Type", "application/json; charset=utf-8"); Result r = new Result(); if (!isAuthrorized(req.headers("Authorization"))) { res.status(401); // unauthorized r.setStatus("Unauthorized"); } boardDao.delete(req.params("id")); return gson.toJson(r); }); } private boolean isAuthrorized(String hdr) { byte[] decryptedHeader = Base64.getDecoder().decode(hdr.split(" ")[1]); String[] credentials = new String(decryptedHeader).split(":"); return (credentials[0].equals(USER) && credentials[1].equals(PW)); } private int getUnixTimestamp() { return (int)(System.currentTimeMillis() / 1000); // we deal with seconds around here } private void dumpRequestException(Request request, Exception e) { System.err.println("Error!"); System.err.printf("Request body:%n%s%n", request.body()); System.err.print("Exception: "); e.printStackTrace(new PrintStream(System.err)); } }
package de.teiesti.postie; import org.pmw.tinylog.Logger; import java.io.*; import java.net.Socket; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingDeque; public abstract class Postman<Letter> implements Cloneable { private Socket socket; private Serializer<Letter> serializer; protected final Set<Recipient<Letter>> recipients = new CopyOnWriteArraySet<>(); private final BlockingQueue<Letter> outbox = new LinkedBlockingDeque<>(); private Thread sender; private Thread receiver; @Override public Postman clone() { if (this.isRunning()) throw new IllegalStateException("cannot clone because this postman is running"); Postman result = null; try { result = (Postman) super.clone(); } catch (CloneNotSupportedException e) { Logger.error(e); System.exit(1); } return result; } public final Postman bind(Socket socket) { if (this.isRunning()) throw new IllegalStateException("cannot bind a socket because this postman is running"); if (socket == null) throw new IllegalArgumentException("socket == null"); // TODO check more about the socket state here this.socket = socket; return this; } public final Postman use(Serializer<Letter> serializer) { if (this.isRunning()) throw new IllegalStateException("cannot use a serializer because this postman is running"); if (serializer == null) throw new IllegalArgumentException("serializer == null"); this.serializer = serializer; return this; } public final Postman start() { // TODO check conditions: socket? sender = new Sender(); receiver = new Receiver(); sender.start(); receiver.start(); return this; } public final Postman register(Recipient recipient) { if (recipient == null) throw new IllegalArgumentException("recipient == null"); recipients.add(recipient); return this; } public final Postman unregister(Recipient recipient) { if (recipient == null) throw new IllegalArgumentException("recipient == null"); recipients.remove(recipient); return this; } public final Postman send(Letter letter) { // TODO question: Must this Postman be running if sending a message. --> no, but the message will not be sent yet if (letter == null) throw new IllegalArgumentException("letter == null"); try { outbox.put(letter); } catch(InterruptedException e) { Logger.error(e); System.exit(1); } return this; } protected abstract Postman deliver(Letter letter); public final Postman stop() { if (!isRunning()) throw new IllegalStateException("cannot stop because this postman is not running"); sender.interrupt(); try { sender.join(); receiver.join(); } catch (InterruptedException e) { Logger.error(e); System.exit(1); } sender = null; receiver = null; return this; } public final boolean isRunning() { return sender != null && !sender.isInterrupted(); } private class Sender extends Thread { @Override public void run() { // open output writer BufferedWriter out = openOutput(); // send letters Letter letter; try { while (!this.isInterrupted()) { letter = outbox.take(); serializer.encodeNext(out, letter); if (outbox.isEmpty()) out.flush(); } } catch (InterruptedException e) { // reset interrupt status this.interrupt(); } catch (IOException e) { Logger.error(e); System.exit(1); } // clean up // TODO // close the postman output try { socket.shutdownOutput(); } catch (IOException e) { e.printStackTrace(); } } private BufferedWriter openOutput() { BufferedWriter result = null; try { int outBuffer = socket.getSendBufferSize(); OutputStream outStream = socket.getOutputStream(); result = new BufferedWriter(new OutputStreamWriter(outStream), outBuffer); } catch (IOException e) { Logger.error(e); System.exit(1); } return result; } } private class Receiver extends Thread { @Override public void run() { // open input reader BufferedReader in = openInput(); // receive letters try { Letter letter = serializer.decodeNext(in); while (letter != null) { deliver(letter); letter = serializer.decodeNext(in); } } catch (IOException e) { Logger.error(e); System.exit(1); } // close sender: receiving EOF shows that the opposite site wants to close the connection sender.interrupt(); try { sender.join(); } catch (InterruptedException e) { Logger.error(e); System.exit(1); } // close socket try { socket.close(); } catch (IOException e) { Logger.error(e); System.exit(1); } } private BufferedReader openInput() { BufferedReader result = null; try { int inBuffer = socket.getReceiveBufferSize(); InputStream inStream = socket.getInputStream(); result = new BufferedReader(new InputStreamReader(inStream), inBuffer); } catch (IOException e) { Logger.error(e); System.exit(1); } return result; } } }
package ca.corefacility.bioinformatics.irida.service.impl.integration.analysis.submission; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.context.support.WithSecurityContextTestExcecutionListener; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import ca.corefacility.bioinformatics.irida.config.IridaApiGalaxyTestConfig; import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException; import ca.corefacility.bioinformatics.irida.exceptions.ExecutionManagerException; import ca.corefacility.bioinformatics.irida.exceptions.NoPercentageCompleteException; import ca.corefacility.bioinformatics.irida.model.enums.AnalysisState; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.sequenceFile.SingleEndSequenceFile; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission; import ca.corefacility.bioinformatics.irida.model.workflow.submission.IridaWorkflowNamedParameters; import ca.corefacility.bioinformatics.irida.model.workflow.submission.ProjectAnalysisSubmissionJoin; import ca.corefacility.bioinformatics.irida.repositories.analysis.submission.WorkflowNamedParametersRepository; import ca.corefacility.bioinformatics.irida.repositories.sequencefile.SequencingObjectRepository; import ca.corefacility.bioinformatics.irida.repositories.specification.AnalysisSubmissionSpecification; import ca.corefacility.bioinformatics.irida.repositories.user.UserRepository; import ca.corefacility.bioinformatics.irida.service.AnalysisSubmissionService; import ca.corefacility.bioinformatics.irida.service.ProjectService; /** * Tests for an analysis service. * * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { IridaApiGalaxyTestConfig.class }) @ActiveProfiles("test") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class, WithSecurityContextTestExcecutionListener.class }) @DatabaseSetup("/ca/corefacility/bioinformatics/irida/service/impl/analysis/submission/AnalysisSubmissionServiceIT.xml") @DatabaseTearDown("/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml") public class AnalysisSubmissionServiceImplIT { private static float DELTA = 0.000001f; @Autowired private AnalysisSubmissionService analysisSubmissionService; @Autowired private UserRepository userRepository; @Autowired private SequencingObjectRepository sequencingObjectRepository; @Autowired private WorkflowNamedParametersRepository parametersRepository; @Autowired private ProjectService projectService; private UUID workflowId = UUID.randomUUID(); /** * Tests successfully getting a state for an analysis submission. */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testGetStateForAnalysisSubmissionSuccess() { AnalysisState state = analysisSubmissionService.getStateForAnalysisSubmission(1L); assertEquals(AnalysisState.SUBMITTING, state); } /** * Tests failing to get a state for an analysis submission. */ @Test(expected = EntityNotFoundException.class) @WithMockUser(username = "aaron", roles = "ADMIN") public void testGetStateForAnalysisSubmissionFail() { analysisSubmissionService.getStateForAnalysisSubmission(20L); } @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void searchAnalyses() { Specification<AnalysisSubmission> specification = AnalysisSubmissionSpecification.filterAnalyses(null, null, null, null, null, null); Page<AnalysisSubmission> paged = analysisSubmissionService.search(specification, new PageRequest(0, 10, new Sort(Direction.ASC, "createdDate"))); assertEquals(10, paged.getContent().size()); // Try filtering a by names String name = "My"; specification = AnalysisSubmissionSpecification.filterAnalyses(null, name, null, null, null, null); paged = analysisSubmissionService.search(specification, new PageRequest(0, 10, new Sort(Direction.ASC, "createdDate"))); assertEquals(8, paged.getContent().size()); // Add a state filter AnalysisState state = AnalysisState.COMPLETED; specification = AnalysisSubmissionSpecification.filterAnalyses(null, name, state, null, null, null); paged = analysisSubmissionService.search(specification, 0, 10, Sort.Direction.ASC, "createdDate"); assertEquals(2, paged.getContent().size()); } /** * Tests reading a submission as a regular user */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testReadGrantedRegularUser() { AnalysisSubmission submission = analysisSubmissionService.read(1L); assertNotNull("submission was not properly returned", submission); } /** * Tests being denied to read a submission as a regular user */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void testReadDeniedRegularUser() { analysisSubmissionService.read(1L); } /** * Tests reading a submission as an admin user */ @Test @WithMockUser(username = "otheraaron", roles = "ADMIN") public void testReadSuccessAdmin() { AnalysisSubmission submission = analysisSubmissionService.read(1L); assertNotNull("submission was not properly returned", submission); } /** * Tests reading multiple submissions as a regular user */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testReadMultipleGrantedRegularUser() { Iterable<AnalysisSubmission> submissions = analysisSubmissionService.readMultiple(Sets.newHashSet(1L, 2L)); Iterator<AnalysisSubmission> submissionIter = submissions.iterator(); assertNotNull("Should have one submission", submissionIter.next()); assertNotNull("Should have two submissions", submissionIter.next()); } /** * Tests reading multiple submissions as a regular user and being denied. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void testReadMultipleDeniedRegularUser() { analysisSubmissionService.readMultiple(Sets.newHashSet(1L, 2L)); } /** * Tests finding all as an admin user. */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFindAllAdminUser() { Iterable<AnalysisSubmission> submissions = analysisSubmissionService.findAll(); Set<Long> submissionIds = Sets.newHashSet(); submissions.forEach(submission -> submissionIds.add(submission.getId())); assertEquals("Invalid analysis submissions found", ImmutableSet.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), submissionIds); } /** * Tests finding all accessible to regular user. */ @Test @WithMockUser(username = "otheraaron", roles = "USER") public void testFindAllRegularUser() { Iterable<AnalysisSubmission> submissions = analysisSubmissionService.findAll(); Set<Long> submissionIds = Sets.newHashSet(); submissions.forEach(submission -> submissionIds.add(submission.getId())); assertEquals("Invalid analysis submissions found", ImmutableSet.of(3L, 9L, 11L, 12L), submissionIds); } /** * Tests checking for existence of an {@link AnalysisSubmission} as a * regular user. */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testExistsRegularUser() { assertTrue("Submission should exist", analysisSubmissionService.exists(1L)); } /** * Tests checking for existence of an {@link AnalysisSubmission} as a * regular non-owner user. */ @Test @WithMockUser(username = "otheraaron", roles = "USER") public void testExistsRegularNonOwnerUser() { assertTrue("Submission should exist", analysisSubmissionService.exists(1L)); } /** * Tests finding revisions for a {@link AnalysisSubmission} as a regular * user. */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testFindRevisionsRegularUser() { assertNotNull("should return revisions exist", analysisSubmissionService.findRevisions(1L)); } /** * Tests being denied to find revisions for a {@link AnalysisSubmission} as * a regular user. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void testFindRevisionsDeniedUser() { analysisSubmissionService.findRevisions(1L); } /** * Tests finding pageable revisions for a {@link AnalysisSubmission} as a * regular user. */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testFindRevisionsPageRegularUser() { assertNotNull("should return revisions exist", analysisSubmissionService.findRevisions(1L, new PageRequest(1, 1))); } /** * Tests being denied to find revisions for a {@link AnalysisSubmission} as * a regular user. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void testFindRevisionsPageDeniedUser() { analysisSubmissionService.findRevisions(1L, new PageRequest(1, 1)); } /** * Tests getting state for a {@link AnalysisSubmission} as a regular user. */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetStateForAnalysisSubmissionRegularUser() { assertNotNull("state should return successfully", analysisSubmissionService.getStateForAnalysisSubmission(1L)); } /** * Tests being denied to get the state for a {@link AnalysisSubmission} as a * regular user. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void testGetStateForAnalysisSubmissionDeniedUser() { analysisSubmissionService.getStateForAnalysisSubmission(1L); } /** * Tests listing submissions as the regular user and being denied. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "aaron", roles = "USER") public void testListDeniedRegularUser() { analysisSubmissionService.list(1, 1, Direction.ASC); } /** * Tests listing submissions as an admin user. */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testListAdminUser() { assertNotNull("Should list submissions", analysisSubmissionService.list(1, 1, Direction.ASC)); } /** * Tests listing submissions as the regular user with sort properties and * being denied. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "aaron", roles = "USER") public void testListSortPropertiesDeniedRegularUser() { analysisSubmissionService.list(1, 1, Direction.ASC, ""); } /** * Tests listing submissions with sort properties as an admin user. */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testListSortPropertiesAdminUser() { assertNotNull("Should list submissions", analysisSubmissionService.list(1, 1, Direction.ASC, "submitter")); } /** * Tests counting analysis submissions as regular user and being denied. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "aaron", roles = "USER") public void testCountRegularUser() { analysisSubmissionService.count(); } /** * Tests counting analysis submissions as an admin user. */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testCountAdminUser() { assertNotNull("Should count submissions", analysisSubmissionService.count()); } /** * Tests deleting as a regular user and being denied. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void testDeleteSubmissionOwnedByOtherAsUser() { analysisSubmissionService.delete(1L); } /** * Tests deleting an analysis submission as an admin user. */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testDeleteAdminUser() { assertTrue("submission should exists", analysisSubmissionService.exists(1L)); analysisSubmissionService.delete(1L); assertFalse("submission should have been deleted", analysisSubmissionService.exists(1L)); } /** * Tests deleting as a regular user. */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testDeleteSubmissionOwnedBySelf() { assertTrue("submission should exists", analysisSubmissionService.exists(1L)); analysisSubmissionService.delete(1L); assertFalse("submission should have been deleted", analysisSubmissionService.exists(1L)); } /** * Tests updating a submission as a non admin */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testUpdateRegularUser() { AnalysisSubmission submission = analysisSubmissionService.read(1L); submission.setAnalysisState(AnalysisState.COMPLETED); AnalysisSubmission updated = analysisSubmissionService.update(submission); assertEquals("analysis should be completed", AnalysisState.COMPLETED, updated.getAnalysisState()); } /** * Tests updating the analysis as the admin user. */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testUpdateAdminUser() { AnalysisSubmission submission = analysisSubmissionService.read(1L); submission.setAnalysisState(AnalysisState.COMPLETED); assertNotNull("submission should be updated", analysisSubmissionService.update(submission)); } /** * Tests creating a submission as a regular user. */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testCreateRegularUser() { SingleEndSequenceFile sequencingObject = (SingleEndSequenceFile) sequencingObjectRepository.findOne(1L); AnalysisSubmission submission = AnalysisSubmission.builder(workflowId).name("test") .inputFiles(Sets.newHashSet(sequencingObject)).build(); AnalysisSubmission createdSubmission = analysisSubmissionService.create(submission); assertNotNull("Submission should have been created", createdSubmission); assertEquals("submitter should be set properly", Long.valueOf(1L), createdSubmission.getSubmitter().getId()); } /** * Tests creating a submission as a second regular user. */ @Test @WithMockUser(username = "otheraaron", roles = "USER") public void testCreateRegularUser2() { SingleEndSequenceFile sequencingObject = (SingleEndSequenceFile) sequencingObjectRepository.findOne(1L); AnalysisSubmission submission = AnalysisSubmission.builder(workflowId).name("test") .inputFiles(Sets.newHashSet(sequencingObject)).build(); AnalysisSubmission createdSubmission = analysisSubmissionService.create(submission); assertNotNull("Submission should have been created", createdSubmission); assertEquals("submitter should be set properly", Long.valueOf(2L), createdSubmission.getSubmitter().getId()); } /** * Tests searching as an admin user. */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testSearchAdminUser() { assertNotNull("search should succeed", analysisSubmissionService.search(new AnalysisSubmissionTestSpecification(), new PageRequest(1, 1, new Sort(Direction.ASC, "createdDate")))); } /** * Tests getting a set of submissions as a regular user for the user. */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetAnalysisSubmissionsForUserAsRegularUser() { User user = userRepository.findOne(1L); Set<AnalysisSubmission> submissions = analysisSubmissionService.getAnalysisSubmissionsForUser(user); assertNotNull("should get submissions for the user", submissions); assertEquals("submissions should have correct number", 9, submissions.size()); } /** * Tests being denied getting submissions for a different user. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void testGetAnalysisSubmissionsForUserAsRegularUserDenied() { User user = userRepository.findOne(1L); analysisSubmissionService.getAnalysisSubmissionsForUser(user); } /** * Tests getting a set of submissions as an admin user for a different user. */ @Test @WithMockUser(username = "otheraaron", roles = "ADMIN") public void testGetAnalysisSubmissionsForUserAsAdminUser() { User user = userRepository.findOne(1L); Set<AnalysisSubmission> submissions = analysisSubmissionService.getAnalysisSubmissionsForUser(user); assertNotNull("should get submissions for the user", submissions); assertEquals("submissions should have correct number", 9, submissions.size()); } /** * Tests getting a set of submissions for the current user as a regular * user. */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetAnalysisSubmissionsForCurrentUserAsRegularUser() { Set<AnalysisSubmission> submissions = analysisSubmissionService.getAnalysisSubmissionsForCurrentUser(); assertNotNull("should get submissions for the user", submissions); assertEquals("submissions should have correct number", 9, submissions.size()); } /** * Tests getting a set of submissions for the current user as a 2nd regular * user. */ @Test @WithMockUser(username = "otheraaron", roles = "USER") public void testGetAnalysisSubmissionsForCurrentUserAsRegularUser2() { Set<AnalysisSubmission> submissions = analysisSubmissionService.getAnalysisSubmissionsForCurrentUser(); assertNotNull("should get submissions for the user", submissions); assertEquals("submissions should have correct number", 3, submissions.size()); } /** * Tests getting a set of submissions for the current user with an admin * role */ @Test @WithMockUser(username = "otheraaron", roles = "ADMIN") public void testGetAnalysisSubmissionsForCurrentUserAsAdminUser() { Set<AnalysisSubmission> submissions = analysisSubmissionService.getAnalysisSubmissionsForCurrentUser(); assertNotNull("should get submissions for the user", submissions); assertEquals("submissions should have correct number", 3, submissions.size()); } /** * Tests failing to get a set of submissions for the current user when there * is no current user. */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "aaron", roles = "") public void testGetAnalysisSubmissionsForCurrentUserAsRegularUserFail() { analysisSubmissionService.getAnalysisSubmissionsForCurrentUser(); } @Test(expected = UnsupportedOperationException.class) @WithMockUser(username = "aaron", roles = "ADMIN") public void testCreateSubmissionWithUnsavedNamedParameters() { final SingleEndSequenceFile sequencingObject = (SingleEndSequenceFile) sequencingObjectRepository.findOne(1L); final IridaWorkflowNamedParameters params = new IridaWorkflowNamedParameters("named parameters.", workflowId, ImmutableMap.of("named", "parameter")); final AnalysisSubmission submission = AnalysisSubmission.builder(workflowId) .inputFiles(Sets.newHashSet(sequencingObject)).withNamedParameters(params).build(); analysisSubmissionService.create(submission); } @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testCreateSubmissionWithNamedParameters() { final SingleEndSequenceFile sequencingObject = (SingleEndSequenceFile) sequencingObjectRepository.findOne(1L); final IridaWorkflowNamedParameters params = parametersRepository.findOne(1L); final AnalysisSubmission submission = AnalysisSubmission.builder(workflowId) .inputFiles(Sets.newHashSet(sequencingObject)).withNamedParameters(params).build(); analysisSubmissionService.create(submission); assertNotNull("Should have saved and created an id for the submission", submission.getId()); assertNotNull("Submission should have a map of parameters", submission.getInputParameters()); assertEquals("Submission parameters should be the same as the named parameters", params.getInputParameters(), submission.getInputParameters()); } /** * Tests getting the percentage complete for a submission as a regular user * * @throws EntityNotFoundException * @throws ExecutionManagerException */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetPercentageCompleteGrantedRegularUser() throws EntityNotFoundException, ExecutionManagerException { float percentageComplete = analysisSubmissionService.getPercentCompleteForAnalysisSubmission(10L); assertEquals("submission was not properly returned", 0.0f, percentageComplete, DELTA); } /** * Tests being denied to get the percentage complete a submission as a * regular user * * @throws EntityNotFoundException * @throws ExecutionManagerException */ @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void testGetPercentageCompleteDeniedRegularUser() throws EntityNotFoundException, ExecutionManagerException { analysisSubmissionService.getPercentCompleteForAnalysisSubmission(10L); } /** * Tests getting the percentage complete for a submission as an admin user. * * @throws EntityNotFoundException * @throws ExecutionManagerException */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testGetPercentageCompleteGrantedAdminUser() throws EntityNotFoundException, ExecutionManagerException { float percentageComplete = analysisSubmissionService.getPercentCompleteForAnalysisSubmission(10L); assertEquals("submission was not properly returned", 0.0f, percentageComplete, DELTA); } /** * Tests getting the percentage complete for a submission as a regular user * with an alternative state. * * @throws EntityNotFoundException * @throws ExecutionManagerException */ @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetPercentageCompleteAlternativeState() throws EntityNotFoundException, ExecutionManagerException { float percentageComplete = analysisSubmissionService.getPercentCompleteForAnalysisSubmission(3L); assertEquals("submission was not properly returned", 15.0f, percentageComplete, DELTA); } /** * Tests getting the percentage complete for a submission as a regular user * and failing due to an error. * * @throws EntityNotFoundException * @throws ExecutionManagerException */ @Test(expected = NoPercentageCompleteException.class) @WithMockUser(username = "aaron", roles = "USER") public void testGetPercentageCompleteFailError() throws EntityNotFoundException, ExecutionManagerException { analysisSubmissionService.getPercentCompleteForAnalysisSubmission(7L); } /** * Tests whether a user can read an analysis when they are not the submitter * but they are on a project where the analysis is shared */ @Test @WithMockUser(username = "otheraaron", roles = "USER") public void testReadSharedAnalysis() { AnalysisSubmission read = analysisSubmissionService.read(3L); assertEquals("id should be 3", new Long(3), read.getId()); } @Test @WithMockUser(username = "aaron", roles = "USER") public void shareAnalysisSubmissionWithProject() { AnalysisSubmission read = analysisSubmissionService.read(3L); Project project2 = projectService.read(2L); ProjectAnalysisSubmissionJoin shareAnalysisSubmissionWithProject = analysisSubmissionService .shareAnalysisSubmissionWithProject(read, project2); assertNotNull(shareAnalysisSubmissionWithProject.getId()); } @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void shareAnalysisSubmissionWithProjectFail() { AnalysisSubmission read = analysisSubmissionService.read(3L); Project project2 = projectService.read(2L); analysisSubmissionService.shareAnalysisSubmissionWithProject(read, project2); } @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetAnalysisSubmissionsSharedToProject() { Project project = projectService.read(1L); Collection<AnalysisSubmission> submissions = analysisSubmissionService.getAnalysisSubmissionsSharedToProject(project); Set<Long> submissionIds = submissions.stream().map(AnalysisSubmission::getId).collect(Collectors.toSet()); assertEquals("Incorrect analysis submissions for project", Sets.newHashSet(3L, 12L), submissionIds); } @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetAnalysisSubmissionsSharedToProjectNoSubmissions() { Project project = projectService.read(2L); Collection<AnalysisSubmission> submissions = analysisSubmissionService.getAnalysisSubmissionsSharedToProject(project); assertEquals("Unexpected analysis submission in project", 0, submissions.size()); } @Test @WithMockUser(username = "aaron", roles = "USER") public void testRemoveAnalysisSubmissionFromProject() { AnalysisSubmission read = analysisSubmissionService.read(3L); Project project2 = projectService.read(1L); analysisSubmissionService.removeAnalysisProjectShare(read, project2); } @Test(expected = AccessDeniedException.class) @WithMockUser(username = "otheraaron", roles = "USER") public void testRemoveAnalysisSubmissionFromProjectFail() { AnalysisSubmission read = analysisSubmissionService.read(3L); Project project2 = projectService.read(1L); analysisSubmissionService.removeAnalysisProjectShare(read, project2); } @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIdsUser1Pass1() { List<AnalysisSubmission> submissions = analysisSubmissionService .getAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIds( Sets.newHashSet(UUID.fromString("e47c1a8b-4ccd-4e56-971b-24c384933f44"))); Set<Long> submissionIds = submissions.stream().map(AnalysisSubmission::getId).collect(Collectors.toSet()); assertEquals("Got incorrect analysis submissions", ImmutableSet.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 10L, 12L), submissionIds); } @Test @WithMockUser(username = "otheraaron", roles = "USER") public void testGetAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIdsUser2Pass1() { List<AnalysisSubmission> submissions = analysisSubmissionService .getAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIds( Sets.newHashSet(UUID.fromString("e47c1a8b-4ccd-4e56-971b-24c384933f44"))); Set<Long> submissionIds = submissions.stream().map(AnalysisSubmission::getId).collect(Collectors.toSet()); assertEquals("Got incorrect analysis submissions", ImmutableSet.of(3L, 9L, 12L), submissionIds); } @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIdsUser1Pass2() { List<AnalysisSubmission> submissions = analysisSubmissionService .getAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIds( Sets.newHashSet(UUID.fromString("e47c1a8b-4ccd-4e56-971b-24c384933f44"), UUID.fromString("d18dfcfe-f10c-48c0-b297-4f90cb9c44bc"))); Set<Long> submissionIds = submissions.stream().map(AnalysisSubmission::getId).collect(Collectors.toSet()); assertEquals("Got incorrect analysis submissions", ImmutableSet.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 10L, 12L), submissionIds); } @Test @WithMockUser(username = "otheraaron", roles = "USER") public void testGetAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIdsUser2Pass2() { List<AnalysisSubmission> submissions = analysisSubmissionService .getAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIds( Sets.newHashSet(UUID.fromString("e47c1a8b-4ccd-4e56-971b-24c384933f44"), UUID.fromString("d18dfcfe-f10c-48c0-b297-4f90cb9c44bc"))); Set<Long> submissionIds = submissions.stream().map(AnalysisSubmission::getId).collect(Collectors.toSet()); assertEquals("Got incorrect analysis submissions", ImmutableSet.of(3L, 9L, 11L, 12L), submissionIds); } @Test @WithMockUser(username = "aaron", roles = "USER") public void testGetAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIdsUser1NoSubmissions() { List<AnalysisSubmission> submissions = analysisSubmissionService .getAnalysisSubmissionsAccessibleByCurrentUserByWorkflowIds( Sets.newHashSet(UUID.fromString("d18dfcfe-f10c-48c0-b297-4f90cb9c44bc"))); Set<Long> submissionIds = submissions.stream().map(AnalysisSubmission::getId).collect(Collectors.toSet()); assertEquals("Got incorrect analysis submissions", ImmutableSet.of(), submissionIds); } /** * Test specification. * * */ private class AnalysisSubmissionTestSpecification implements Specification<AnalysisSubmission> { @Override public Predicate toPredicate(Root<AnalysisSubmission> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return null; } } }
package hk.ust.comp4321.engine; import java.io.IOException; import hk.ust.comp4321.database.InvertedIndexTable; /** * * @author Paul Wong * */ public class TermWeight { // Constants and fields. InvertedIndexTable invertedIndexTable; private int wordId; private int pageId; private final int totalPage = 300; // Constructors. /** * This constructor encapsulates the WordId and PageId. * * @param WordId the word's id * @param PageId the page's id */ public TermWeight(int WordId, int PageId) { wordId = WordId; pageId = PageId; } /** * This method converts base 10 log to base 2 log. * * @param n number needed to be log */ private static double log2(int n) { return (Math.log(n) / Math.log(2)); } /** * This method finds the termWeight by (tf/max. tf) * log (N/df). * * @return termWeight */ public double getTermWeight() throws IOException { invertedIndexTable = InvertedIndexTable.getTable(); int tfmax=0; int tf = invertedIndexTable.getIndexInfo(wordId, pageId).getPositionList().size(); int numOfPage = invertedIndexTable.getIndexInfoList(wordId).size(); for(int i=0; i<numOfPage; i++) // max. tf { if (invertedIndexTable.getIndexInfoList(wordId, i).getPositionList().size() > tfmax) { tfmax = invertedIndexTable.getIndexInfoList(wordId, i).getPositionList().size(); } } return (tf/tfmax)*log2(totalPage/numOfPage); } }
package embeddings; import java.util.Arrays; import java.util.HashMap; import static embeddings.EmbeddingsParser.NBYTES; import static java.nio.charset.StandardCharsets.UTF_8; /** * Sample class for using word embeddings. * Provides an enum that statically loads embeddings */ public class WordEmbeddings { private float _scale; private int _shift; private short _vec_sz; public enum EMBEDDINGS { GLOVE(EmbeddingsParser.parse("./data/glove.bin")), GOOGL(EmbeddingsParser.parse("./data/googl.bin")); private final WordEmbeddings _em; private EMBEDDINGS(EmbeddingsParser ep) { _em=new WordEmbeddings(ep._maps); _em._scale = 1.f/(float)Math.pow(10,ep._scale); _em._shift = ep._shift; _em._vec_sz = ep._vec_sz; } /** * Fill res with the word embeddings for word w. * The expectation is that res is zero'd out before use. * This will force the word into UTF_8 bytes. * This will allocate a new BufferedBytes instance to wrap the bytes of w. * * @param w lookup w in the word embeddings * @param res fill this float array with word embeddings */ public void get(String w, float[] res) { _em.get(new BufferedBytes(w.getBytes(UTF_8)),res); } /** * Fill res with the word embeddings for word w. * The expectation is that res is zero'd out before use. * This allocates a new BufferedBytes instance to wrap w. * * @param w lookup w in the word embeddings * @param res fill this float array with word embeddings */ public void get(byte[] w, float[] res) { _em.get(new BufferedBytes(w),res); } /** * Fill res with the word embeddings for the BufferedBytes instance. * This is the best performing option. * The expectation is that res is zero'd out before use. * * @param bb BufferedBytes holding the bytes of the word to lookup * @param res fill this float array with the word embeddings */ public void get(BufferedBytes bb, float[] res) { _em.get(bb, res); } } private transient HashMap<BufferedBytes,BufferedBytes> _map; // takes the result of a parse_bin call and flattens all maps into a single map private WordEmbeddings(HashMap<BufferedBytes,BufferedBytes>[] maps) { _map=new HashMap<>(); for (HashMap<BufferedBytes, BufferedBytes> map : maps) _map.putAll(map); } private void get(BufferedBytes s, float[] res) { Arrays.fill(res,0); BufferedBytes bb= _map.get(s); if( bb==null ) return; int off=bb._off + bb._len; // _off is the start of the string, _len is the length of the string byte[] buf = bb._buf; int idx=0; int i=off; for(;i<off+NBYTES*_vec_sz;i+=NBYTES) { // decode the embedding value by combining 3 bytes, then shift & scale int r = (buf[i ] & 0xFF) | (buf[i+1] & 0xFF) << 8 | (buf[i+2] & 0xFF) << 16; res[idx++] = ((r + _shift)*_scale); } } }
package i5.las2peer.communication; import i5.las2peer.p2p.AgentNotKnownException; import i5.las2peer.persistency.EncodingFailedException; import i5.las2peer.persistency.MalformedXMLException; import i5.las2peer.persistency.XmlAble; import i5.las2peer.security.Agent; import i5.las2peer.security.AgentStorage; import i5.las2peer.security.L2pSecurityException; import i5.las2peer.tools.CryptoException; import i5.las2peer.tools.CryptoTools; import i5.las2peer.tools.SerializationException; import i5.las2peer.tools.SerializeTools; import i5.las2peer.tools.XmlTools; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Signature; import java.security.SignatureException; import java.util.Base64; import java.util.Date; import java.util.Random; import javax.crypto.SecretKey; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import rice.p2p.commonapi.NodeHandle; /** * Base class for sending messages between {@link Agent}s. * * The content of the message will be encrypted symmetrically with a randomly generated key, this key will be encrypted * asymmetrically for the recipient of the message. * * Additionally, the contents will be signed with the private key of the sender. * * Therefore, it is necessary, that the generating Thread has access to the private key of the sending agent. * * When specifying a topic, the message will be sent to all agents listening to the topic. Since these agents are not * known, the message will not be encrypted. * */ public class Message implements XmlAble, Cloneable { public static final long DEFAULT_TIMEOUT = 30 * 1000; // 30 seconds /** * sender of the message */ private Agent sender = null; /** * id of the sending agent */ private long senderId; /** * recipient of the message */ private Agent recipient = null; /** * id of the receiving agent */ private Long recipientId = null; /** * id of the receiving topic */ private Long topicId = null; /** * message content (if opened) */ private Object content = null; /** * (asymmetrically) encrypted content of the message */ private byte[] baEncryptedContent; /** * signature of the message content */ private byte[] baSignature; /** * symmetric key for the content of this message encrypted for the recipient */ private byte[] baContentKey; /** * timestamp of the message generation */ private long timestampMs; /** * how long in milliseconds is this message valid (timestamp of timeout is timestamp + validMs) */ private long validMs; /** * a simple message id for reference, i.e. answer messages */ private long id; /** * id of a message, this one is a response to */ private Long responseToId = null; private Serializable sendingNodeId = null; /** * constructor for the {@link XmlAble} facilities */ public Message() { // just for XmlAble } /** * create a new message with default timeout * * @param from * @param to * @param data * @throws EncodingFailedException * @throws L2pSecurityException the private key of the sender is not accessible for signing * @throws SerializationException * */ public Message(Agent from, Agent to, Serializable data) throws EncodingFailedException, L2pSecurityException, SerializationException { this(from, to, data, DEFAULT_TIMEOUT); } /** * create a new message * * @param from * @param to * @param data * @param timeOutMs timeout for the validity of the new message * @throws EncodingFailedException * @throws L2pSecurityException the private key of the sender is not accessible for signing * @throws SerializationException */ public Message(Agent from, Agent to, Serializable data, long timeOutMs) throws EncodingFailedException, L2pSecurityException, SerializationException { if (from == null || to == null) { throw new IllegalArgumentException("null not allowed as sender or recipient!"); } sender = from; senderId = from.getId(); recipient = to; recipientId = to.getId(); content = data; timestampMs = new Date().getTime(); validMs = timeOutMs; id = new Random().nextLong(); encryptContent(); signContent(); close(); } /** * create a new message with default timeout * * @param from * @param to * @param data * @throws EncodingFailedException * @throws L2pSecurityException the private key of the sender is not accessible for signing * @throws SerializationException */ public Message(Agent from, Agent to, XmlAble data) throws EncodingFailedException, L2pSecurityException, SerializationException { this(from, to, data, DEFAULT_TIMEOUT); } /** * create a new message * * @param from * @param to * @param data * @param timeoutMs timeout for the validity of the new message * @throws EncodingFailedException * @throws L2pSecurityException the private key of the sender is not accessible for signing * @throws SerializationException */ public Message(Agent from, Agent to, XmlAble data, long timeoutMs) throws EncodingFailedException, L2pSecurityException, SerializationException { sender = from; senderId = from.getId(); recipient = to; recipientId = to.getId(); content = data; validMs = timeoutMs; finalizeConstructor(); } /** * create a new message to a topic with default timeout * * @param from * @param topic * @param data * @throws EncodingFailedException * @throws L2pSecurityException * @throws SerializationException */ public Message(Agent from, long topic, Serializable data) throws EncodingFailedException, L2pSecurityException, SerializationException { this(from, topic, data, DEFAULT_TIMEOUT); } /** * create a new message to all agents listening on the given topic * * @param from * @param topic * @param data * @param timeoutMs * @throws EncodingFailedException * @throws L2pSecurityException * @throws SerializationException */ public Message(Agent from, long topic, Serializable data, long timeoutMs) throws EncodingFailedException, L2pSecurityException, SerializationException { if (from == null) { throw new IllegalArgumentException("null not allowed as sender!"); } sender = from; senderId = from.getId(); topicId = topic; content = data; validMs = timeoutMs; timestampMs = new Date().getTime(); // id = new Random().nextLong(); finalizeConstructor(); } /** * common to all constructors * * @throws EncodingFailedException * @throws L2pSecurityException * @throws SerializationException */ private void finalizeConstructor() throws EncodingFailedException, L2pSecurityException, SerializationException { timestampMs = new Date().getTime(); id = new Random().nextLong(); if (!isTopic()) { encryptContent(); } else { baEncryptedContent = getContentString().getBytes(StandardCharsets.UTF_8); } signContent(); close(); } /** * Generate a new message in response to the given one. Sender and recipient will be derived from the given message. * * @param responseTo * @param data * @param timeoutMs timeout for the validity of the new message * @throws EncodingFailedException * @throws L2pSecurityException the private key of the sender is not accessible for signing * @throws SerializationException */ public Message(Message responseTo, XmlAble data, long timeoutMs) throws EncodingFailedException, L2pSecurityException, SerializationException { if (!responseTo.isOpen()) { throw new IllegalStateException("the original message has to be open to create a response to it!"); } if (responseTo.getRecipient() == null) { throw new IllegalStateException("the original message has to have an recipient attached"); } sender = responseTo.getRecipient(); senderId = responseTo.getRecipientId(); recipient = responseTo.getSender(); recipientId = responseTo.getSenderId(); validMs = timeoutMs; content = data; responseToId = responseTo.getId(); finalizeConstructor(); } /** * Generate a new message in response to the given one. Sender and recipient will be derived from the given message. * * @param responseTo * @param data * @throws SerializationException * @throws L2pSecurityException the private key of the sender is not accessible for signing * @throws EncodingFailedException */ public Message(Message responseTo, XmlAble data) throws EncodingFailedException, L2pSecurityException, SerializationException { this(responseTo, data, DEFAULT_TIMEOUT); } /** * Generate a new message in response to the given one. Sender and recipient will be derived from the given message. * * @param responseTo * @param data * @param timeoutMs * @throws EncodingFailedException * @throws L2pSecurityException the private key of the sender is not accessible for signing * @throws SerializationException */ public Message(Message responseTo, Serializable data, long timeoutMs) throws EncodingFailedException, L2pSecurityException, SerializationException { if (!responseTo.isOpen()) { throw new IllegalStateException("the original message has to be open to create a response to it!"); } if (responseTo.getRecipient() == null) { throw new IllegalStateException("the original message has to have an recipient attached"); } sender = responseTo.getRecipient(); senderId = responseTo.getRecipientId(); recipient = responseTo.getSender(); recipientId = responseTo.getSenderId(); validMs = timeoutMs; content = data; responseToId = responseTo.getId(); finalizeConstructor(); } /** * Generate a new message in response to the given one. Sender and recipient will be derived from the given message. * * @param responseTo * @param data * @throws EncodingFailedException * @throws L2pSecurityException the private key of the sender is not accessible for signing * @throws SerializationException */ public Message(Message responseTo, Serializable data) throws EncodingFailedException, L2pSecurityException, SerializationException { this(responseTo, data, DEFAULT_TIMEOUT); } /** * get the contents of this message as base 64 encoded string * * @return message contents in xml format with all important attributes and the actual content as base64 encoded * string * * @throws SerializationException */ private String getContentString() throws SerializationException { String typeAttr; String sContent; if (content instanceof XmlAble) { typeAttr = "XmlAble"; sContent = ((XmlAble) content).toXmlString(); } else { typeAttr = "Serializable"; sContent = Base64.getEncoder().encodeToString(SerializeTools.serialize((Serializable) content)); } String attrs = ""; if (responseToId != null) { attrs += " responseTo=\"" + responseToId + "\""; } if (!isTopic()) { attrs += " recipient=\"" + recipient.getId() + "\""; } else { attrs += " topic=\"" + topicId + "\""; } return "<las2peer:messageContent" + " id=\"" + id + "\"" + " sender=\"" + sender.getId() + "\"" + " class=\"" + content.getClass().getCanonicalName() + "\"" + " type=\"" + typeAttr + "\"" + " timestamp=\"" + timestampMs + "\"" + " timeout=\"" + validMs + "\"" + attrs + ">" + sContent + "</las2peer:messageContent>"; } /** * encrypt the content of this message (as base64 encoded string) with asymmetric encryption * * @throws EncodingFailedException */ private void encryptContent() throws EncodingFailedException { if (recipient == null) { return; } try { SecretKey contentKey = CryptoTools.generateSymmetricKey(); baContentKey = CryptoTools.encryptAsymmetric(contentKey, recipient.getPublicKey()); String contentString = getContentString(); baEncryptedContent = CryptoTools.encryptSymmetric(contentString.getBytes(StandardCharsets.UTF_8), contentKey); } catch (SerializationException e) { throw new EncodingFailedException("serialization problems with encryption", e); } catch (CryptoException e) { throw new EncodingFailedException("unable to encrypt the secret message key", e); } } /** * sign the contents of this message * * @throws L2pSecurityException * @throws SerializationException * @throws EncodingFailedException */ private void signContent() throws L2pSecurityException, SerializationException, EncodingFailedException { try { byte[] contentBytes = getContentString().getBytes(StandardCharsets.UTF_8); Signature sig = sender.createSignature(); sig.update(contentBytes); baSignature = sig.sign(); } catch (InvalidKeyException e) { throw new EncodingFailedException("Key problems", e); } catch (NoSuchAlgorithmException e) { throw new EncodingFailedException("Algorithm problems", e); } catch (SignatureException e) { throw new EncodingFailedException("Signature problems", e); } } /** * get the sending agent of this message * * only works after opening or creation the message * * @return sending agent */ public Agent getSender() { return sender; } /** * get the id of the sending agent * * @return id of the sending agent */ public long getSenderId() { return senderId; } /** * get the designated recipient of this message * * only works after opening or creating of the message * * @return (designated) receiver */ public Agent getRecipient() { return recipient; } /** * get the id of the recipient agent * * @return id of the receiving agent */ public Long getRecipientId() { return recipientId; } /** * get the id of the receiving topic * * @return */ public Long getTopicId() { return topicId; } /** * check if this message is sent to a topic * * @return */ public boolean isTopic() { return topicId != null; } /** * get the id of this message * * @return id */ public long getId() { return id; } /** * * @return id of the message, this one is a response to */ public Long getResponseToId() { if (responseToId == null) { return null; } return new Long(responseToId); } /** * * @return true, if this message is a response to another one */ public boolean isResponse() { return responseToId != null; } /** * get the content of this message may be Serializable or XmlAble * * @return actual content of the message * @throws L2pSecurityException the message (envelope) has to be opened (decrypted) first */ public Object getContent() throws L2pSecurityException { if (!isOpen()) { throw new L2pSecurityException("You have to open the envelope first!"); } return content; } /** * open the envelope, i.e. decrypt the content with the private key of the receiving agent * * The storage has to know an unlocked version of the recipient agent! (i.e. a * {@link i5.las2peer.security.AgentContext} bound to him. * * @param storage * @throws L2pSecurityException * @throws AgentNotKnownException */ public void open(AgentStorage storage) throws L2pSecurityException, AgentNotKnownException { open(null, storage); } /** * open the envelope, i.e. decrypt the content with the private key of the receiving agent * * the private key has to be unlocked first! * * @param unlockedRecipient * @param storage * * * @throws L2pSecurityException the private key of the receiver has to be unlocked for decryption * @throws AgentNotKnownException */ public void open(Agent unlockedRecipient, AgentStorage storage) throws L2pSecurityException, AgentNotKnownException { if (isOpen()) { return; } sender = storage.getAgent(senderId); if (recipientId != null) { // topic messages are not encrypted if (unlockedRecipient != null && unlockedRecipient.getId() == recipientId) { recipient = unlockedRecipient; } else { recipient = storage.getAgent(recipientId); } if (recipient.isLocked()) { throw new L2pSecurityException("private key of recipient is locked!"); } } try { byte[] rawContent; if (!isTopic()) { SecretKey contentKey = recipient.decryptSymmetricKey(baContentKey); rawContent = CryptoTools.decryptSymmetric(baEncryptedContent, contentKey); } else { // topics are not encrypted rawContent = baEncryptedContent; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new ByteArrayInputStream(rawContent)); doc.getDocumentElement().normalize(); Element root = doc.getDocumentElement(); if (!root.hasAttribute("sender")) { throw new L2pSecurityException("content block needs sender attribute!"); } if (!root.hasAttribute("recipient") && !root.hasAttribute("topic")) { throw new L2pSecurityException("content block needs recipient or topic attribute!"); } if (!root.hasAttribute("timestamp")) { throw new L2pSecurityException("content block needs timestamp attribute!"); } if (!root.hasAttribute("timeout")) { throw new L2pSecurityException("content block needs timeout attribute!"); } if (!root.hasAttribute("id")) { throw new L2pSecurityException("content block needs id attribute!"); } if (Long.parseLong(root.getAttribute("sender")) != (sender.getId())) { throw new L2pSecurityException("message is signed for another sender!!"); } if (root.hasAttribute("recipient") && (recipient == null || Long.parseLong(root.getAttribute("recipient")) != (recipient.getId()))) { throw new L2pSecurityException("message is signed for another recipient!!"); } if (root.hasAttribute("topic") && Long.parseLong(root.getAttribute("topic")) != (topicId)) { throw new L2pSecurityException("message is signed for another topic!!"); } if (Long.parseLong(root.getAttribute("timestamp")) != timestampMs) { throw new L2pSecurityException("message is signed for another timestamp!!"); } if (Long.parseLong(root.getAttribute("timeout")) != validMs) { throw new L2pSecurityException("message is signed for another timeout value!!"); } if (Long.parseLong(root.getAttribute("id")) != id) { throw new L2pSecurityException("message is signed for another id!"); } if ((root.hasAttribute("responseTo") || responseToId != null) && !responseToId.equals(Long.parseLong(root.getAttribute("responseTo")))) { throw new L2pSecurityException("message is signed as response to another message!"); } if (root.getAttribute("type").equals("Serializable")) { content = SerializeTools.deserializeBase64(root.getTextContent()); } else { content = XmlAble.createFromXml(root.getFirstChild().toString(), root.getAttribute("class")); } } catch (CryptoException e) { throw new L2pSecurityException("Crypto-Problems: Unable to open message content", e); } catch (SerializationException e) { throw new L2pSecurityException("deserializiation problems with decryption!", e); } catch (ClassNotFoundException e) { throw new L2pSecurityException("content class missing with decryption!", e); } catch (MalformedXMLException | ParserConfigurationException | SAXException | IOException e) { throw new L2pSecurityException("xml syntax problems with decryption!", e); } // verify signature verifySignature(); } /** * verify the signature of this message the content has to be available for this * * @throws L2pSecurityException */ public void verifySignature() throws L2pSecurityException { Signature sig; try { byte[] contentBytes = getContentString().getBytes(StandardCharsets.UTF_8); sig = Signature.getInstance(CryptoTools.getSignatureMethod()); sig.initVerify(sender.getPublicKey()); sig.update(contentBytes); if (!sig.verify(baSignature)) { System.out.println(" System.out.println("Signature invalid. Please report the following output to LAS-353."); System.out.println(" System.out.println(this.toXmlString()); // TODO LAS-353 logging; remove when resolved System.out.println(" System.out.println(getContentString()); System.out.println(" System.out.println(sender.getPublicKey()); System.out.println(" throw new L2pSecurityException("Signature invalid!"); } } catch (InvalidKeyException e) { throw new L2pSecurityException("unable to verify signature: key problems", e); } catch (NoSuchAlgorithmException e) { throw new L2pSecurityException("unable to verify signature: algorithm problems", e); } catch (SignatureException e) { throw new L2pSecurityException("unable to verify signature: signature problems", e); } catch (SerializationException e) { throw new L2pSecurityException("unable to verify signature: serialization problems", e); } } /** * close this message (envelope) */ public void close() { content = null; sender = null; recipient = null; } /** * @return true, if the content of this message is accessible */ public boolean isOpen() { return (content != null); } /** * @return unix timestamp of message creation */ public long getTimestamp() { return timestampMs; } /** * @return timestamp of message creation as Date object */ public Date getTimestampDate() { return new Date(timestampMs); } /** * @return the date of timeout for this message */ public Date getTimeoutDate() { return new Date(timestampMs + validMs); } /** * * @return timestamp of the timeout for this message */ public long getTimeoutTs() { return timestampMs + validMs; } /** * @return true, if this message is expired */ public boolean isExpired() { return timestampMs + validMs - new Date().getTime() < 0; } /** * from XmlAble return a XML representation of this instance * */ @Override public String toXmlString() { String response = ""; if (responseToId != null) { response = " responseTo=\"" + responseToId + "\""; } String sending = ""; if (sendingNodeId != null) { if (sendingNodeId instanceof Long || sendingNodeId instanceof NodeHandle) { try { sending = "\t<sendingNode encoding=\"base64\">" + SerializeTools.serializeToBase64(sendingNodeId) + "</sendingNode>\n"; } catch (SerializationException e) { } } } String receiver; String contentKey = ""; String encryption = ""; if (!isTopic()) { receiver = "to=\"" + recipientId + "\""; encryption = " encryption=\"" + CryptoTools.getSymmetricAlgorithm() + "\""; contentKey = "\t<contentKey encryption=\"" + CryptoTools.getAsymmetricAlgorithm() + "\" encoding=\"base64\">" + Base64.getEncoder().encodeToString(baContentKey) + "</contentKey>\n"; } else { receiver = "topic=\"" + topicId + "\""; } return "<las2peer:message" + " id=\"" + id + "\"" + response + " from=\"" + senderId + "\" " + receiver + " generated=\"" + timestampMs + "\" timeout=\"" + validMs + "\">\n" + sending + "\t<content" + encryption + " encoding=\"base64\">" + Base64.getEncoder().encodeToString(baEncryptedContent) + "</content>\n" + contentKey + "\t<signature encoding=\"base64\" method=\"" + CryptoTools.getSignatureMethod() + "\">" + Base64.getEncoder().encodeToString(baSignature) + "</signature>\n" + "</las2peer:message>\n"; } /** * for XmlAble: set the state of this object from the given xml document * * @param xml * @throws MalformedXMLException */ public void setStateFromXml(String xml) throws MalformedXMLException { try { Element root = XmlTools.getRootElement(xml, "las2peer:message"); Element sending = XmlTools.getOptionalElement(root, "sendingNode"); if (sending != null) { if (!"base64".equals(sending.getAttribute("encoding"))) { throw new MalformedXMLException("base64 encoding of sending node expected!"); } sendingNodeId = SerializeTools.deserializeBase64(sending.getTextContent()); } Element content = XmlTools.getSingularElement(root, "content"); Element contentKey = XmlTools.getOptionalElement(root, "contentKey"); Element signature = XmlTools.getSingularElement(root, "signature"); if (!root.hasAttribute("from")) { throw new MalformedXMLException("needed from attribute missing!"); } if (!root.hasAttribute("to") && !root.hasAttribute("topic")) { throw new MalformedXMLException("needed to or topic attribute missing!"); } if (!root.hasAttribute("topic") && contentKey == null) { throw new MalformedXMLException("content key missing!"); } if (!root.hasAttribute("generated")) { throw new MalformedXMLException("needed generated attribute missing!"); } if (!root.hasAttribute("timeout")) { throw new MalformedXMLException("needed timeout attribute missing!"); } if (!root.hasAttribute("id")) { throw new MalformedXMLException("needed id attribute missing!"); } if (!content.getAttribute("encoding").equals("base64")) { throw new MalformedXMLException("base64 encoding expected"); } if (contentKey != null && !contentKey.getAttribute("encoding").equals("base64")) { throw new MalformedXMLException("base64 encoding expected"); } if (!signature.getAttribute("encoding").equals("base64")) { throw new MalformedXMLException("base64 encoding expected"); } senderId = Long.parseLong(root.getAttribute("from")); if (root.hasAttribute("to")) { recipientId = Long.parseLong(root.getAttribute("to")); } if (root.hasAttribute("topic")) { topicId = Long.parseLong(root.getAttribute("topic")); } // sender = AgentStorage.getAgent( Long.parseLong(root.getAttribute ( "from"))); // recipient = AgentStorage.getAgent( Long.parseLong(root.getAttribute ( "to"))); baEncryptedContent = Base64.getDecoder().decode(content.getTextContent()); baSignature = Base64.getDecoder().decode(signature.getTextContent()); if (contentKey != null) { baContentKey = Base64.getDecoder().decode(contentKey.getTextContent()); } timestampMs = Long.parseLong(root.getAttribute("generated")); validMs = Long.parseLong(root.getAttribute("timeout")); id = Long.parseLong(root.getAttribute("id")); if (root.hasAttribute("responseTo")) { responseToId = Long.parseLong(root.getAttribute("responseTo")); } } catch (NumberFormatException e) { throw new MalformedXMLException("to or from attribute is not a long!", e); } catch (SerializationException e) { throw new MalformedXMLException("deserialization problems (sending node id)", e); } } /** * set the if of the node sending this message The NodeHandle-variant is for Pastry based networks. * * @param handle */ public void setSendingNodeId(NodeHandle handle) { sendingNodeId = handle; } /** * set the id of the node sending this message The long-variant is to use in case of a LocalNode network. * * @param id */ public void setSendingNodeId(Long id) { sendingNodeId = id; } /** * set the id of the recipient (used by the node when receiving messages from topics) * * @param id */ public void setRecipientId(Long id) { recipientId = id; } /** * set the id of the node sending this message * * @param id */ public void setSendingNodeId(Object id) { if (id instanceof NodeHandle) { setSendingNodeId((NodeHandle) id); } else if (id instanceof Long) { setSendingNodeId((Long) id); } else { throw new IllegalArgumentException("Illegal Node Id class " + id.getClass().getName()); } } /** * get the id of the sending node The type depends on on the Node implementation (Long for * {@link i5.las2peer.p2p.LocalNode} and NodeHandle for {@link i5.las2peer.p2p.PastryNodeImpl} * * @return id of the sending las2peer node */ public Serializable getSendingNodeId() { return sendingNodeId; } /** * factory: create a message from an XML document * * @param xml * @return a message generated from the given XML document * @throws MalformedXMLException */ public static Message createFromXml(String xml) throws MalformedXMLException { Message result = new Message(); result.setStateFromXml(xml); return result; } @Override public Message clone() throws CloneNotSupportedException { return (Message) super.clone(); } }
package org.jboss.as.test.integration.jpa.hibernate.sessionfactorytest; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.jpa.hibernate.Employee; import org.jboss.as.test.integration.jpa.hibernate.SFSB1; import org.jboss.as.test.integration.jpa.hibernate.SFSBHibernateSession; import org.jboss.as.test.integration.jpa.hibernate.SFSBHibernateSessionFactory; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Hibernate session factory tests * * @author Scott Marlow */ @RunWith(Arquillian.class) public class SessionFactoryTestCase { private static final String ARCHIVE_NAME = "jpa_sessionfactory"; // This test needs to be recompiled against Hibernater ORM 6 (WFLY-16178) in order to pass. @BeforeClass public static void beforeClass() { assumeTrue(System.getProperty("ts.ee9") == null); } @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(SessionFactoryTestCase.class, Employee.class, SFSB1.class, SFSBHibernateSession.class, SFSBHibernateSessionFactory.class ); jar.addAsManifestResource(SessionFactoryTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @ArquillianResource private InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { try { return interfaceType.cast(iniCtx.lookup(name)); } catch (NamingException e) { throw e; } } // test that we didn't break the Hibernate hibernate.session_factory_name (bind Hibernate session factory to // specified jndi name) functionality. @Test public void testHibernateSessionFactoryName() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployee("Sally", "1 home street", 1); // check if we can look up the Hibernate session factory that should of been bound because of // the hibernate.session_factory_name was specified in the properties (in peristence.xml above). SessionFactory hibernateSessionFactory = rawLookup("modelSessionFactory", SessionFactory.class); assertNotNull("jndi lookup of hibernate.session_factory_name should return HibernateSessionFactory", hibernateSessionFactory); Session session = hibernateSessionFactory.openSession(); Employee emp = session.get(Employee.class, 1); assertTrue("name read from hibernate session is Sally", "Sally".equals(emp.getName())); } // Test that an extended Persistence context can be injected into a Hibernate Session // We use extended persistence context, otherwise the Hibernate session will be closed after each transaction and // the assert test would fail (due to lazy loading of the Employee entity. // Using extended persistence context allows the hibernate session to stay open long enough for the lazy fetch. @Test public void testInjectPCIntoHibernateSession() throws Exception { SFSBHibernateSession sfsbHibernateSession = lookup("SFSBHibernateSession", SFSBHibernateSession.class); sfsbHibernateSession.createEmployee("Molly", "2 apple way", 2); Employee emp = sfsbHibernateSession.getEmployee(2); assertTrue("name read from hibernate session is Molly", "Molly".equals(emp.getName())); } // Test that a Persistence unit can be injected into a Hibernate Session factory @Test public void testInjectPUIntoHibernateSessionFactory() throws Exception { SFSBHibernateSessionFactory sfsbHibernateSessionFactory = lookup("SFSBHibernateSessionFactory", SFSBHibernateSessionFactory.class); sfsbHibernateSessionFactory.createEmployee("Sharon", "3 beach ave", 3); Employee emp = sfsbHibernateSessionFactory.getEmployee(3); assertTrue("name read from hibernate session is Sharon", "Sharon".equals(emp.getName())); } }
package info.losd.galen.client; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Request; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringWriter; public class ApiRequest { Logger logger = LoggerFactory.getLogger(ApiRequest.class); private String url; private ApiMethod method; private ApiRequest(ApiMethod method, String url) { this.method = method; this.url = url; } public ApiResponse execute() { try { HttpResponse response = request().execute().returnResponse(); return new ApiResponse.Builder() .statusCode(response.getStatusLine().getStatusCode()) .body(getResponseBody(response)).build(); } catch (IOException e) { logger.error("IO Exception", e); throw new RuntimeException(e); } } private String getResponseBody(HttpResponse response) throws IOException { StringWriter writer = new StringWriter(); IOUtils.copy(response.getEntity().getContent(), writer); return writer.toString(); } private Request request() { switch (method) { case GET: return Request.Get(url); case POST: return Request.Post(url); default: throw new RuntimeException("Unimplemented ApiRequest type"); } } public static class Builder { private String url; private ApiMethod method; Builder url(String url) { this.url = url; return this; } ApiRequest build() { return new ApiRequest(method, url); } public Builder method(ApiMethod method) { this.method = method; return this; } } }
package org.jboss.aerogear.unifiedpush.test; import com.google.android.gcm.server.Message; import java.util.List; import java.util.ArrayList; public class SenderStatistics { public List<String> deviceTokens = new ArrayList<String>(); public Message gcmMessage; public String apnsAlert; public int apnsBadge; public String apnsSound; public String apnsCustomFields; public long apnsExpiry; public String gcmForChromeAlert; }
package file; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; /** * * ClassName: ReadAndWriteTextFile * Description: * @author angilin * @date 2014-2-11 11:12:24 * */ public class ReadAndWriteTextFile { public static void main(String[] args){ System.out.println(System.getProperty("line.separator")); System.out.println(readFile("d:\\00225619\\\\.html")); //writeFile("D:\\test.txt", readFile("d:\\eclipse.txt"),false); } /** * * Title: readFile <br> * Description: UTF-8 <br> * @param filePath * @return * String <br> * @throws */ public static String readFile(String filePath){ return readFile(filePath, "UTF-8", System.getProperty("line.separator")); } /** * * Title: readFile <br> * Description: <br> * @param filePath * @param charset * @return * String <br> * @throws */ public static String readFile(String filePath, String charset){ return readFile(filePath, charset, System.getProperty("line.separator")); } /** * * Title: readFile <br> * Description: <br> * @param filePath * @param charset * @param lineBreak * @return * String <br> * @throws */ public static String readFile(String filePath, String charset, String lineBreak){ BufferedReader reader = null; StringBuilder s = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),charset)); String line = null; while((line = reader.readLine())!=null){ s.append(line); if(lineBreak!=null){ s.append(lineBreak); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ if(reader!=null){ try { reader.close(); } catch (IOException e) { } } } return s.toString(); } /** * * Title: writeFile <br> * Description: <br> * @param filePath * @param content * @param append false * void <br> * @throws */ public static void writeFile(String filePath, String content,Boolean append){ try { FileWriter fWriter = new FileWriter(filePath,append); BufferedWriter bWriter = new BufferedWriter(fWriter); bWriter.write(content); bWriter.close(); fWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
package fileManager; //Servlet-importer import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; //IO-Stream import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Emil-Ruud */ @WebServlet(name = "UploadServlet", urlPatterns = {"/Upload"}) @HttpConstraint(rolesAllowed = {"Teacher", "Admin", "Student", "AssistantTeacher"}) @MultipartConfig(maxFileSize = 15728640) //16Mib public class UploadServlet extends HttpServlet { private final static Logger LOGGER = Logger.getLogger(UploadServlet.class.getCanonicalName()); @EJB FileManagerLocal fml; private void Upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //Globale variabler final String id = UUID.randomUUID().toString(); final Part filePart = request.getPart("file"); InputStream filePartInputStream; try { final String fileName = getFileName(filePart); filePartInputStream = filePart.getInputStream(); if (fileName.endsWith(".zip")) { //Sjekker om fil-endelsen er .zip if (filePart.getSize() <= 15728640) { byte[] fileContent = convertToByteArray(filePartInputStream); //fileContent er selve filen som array av bytes FileEntity fileEntity = new FileEntity(id, fileName, fileContent); if (fml.saveFile(fileEntity)) { String message = "Hurra! Filen er lastet opp!"; request.getSession().setAttribute("message", message); response.sendRedirect("welcome.jsp"); } else { String message = "Får ikke lastet filen opp til databasen."; request.getSession().setAttribute("message", message); response.sendRedirect("welcome.jsp"); } } else { String message = "Filen kan ikke være større enn 15Mib (15 728 640 bytes)."; request.getSession().setAttribute("message", message); response.sendRedirect("welcome.jsp"); } } else { String message = "Filen må være av typen .zip (en helt vanlig zip-fil)."; request.getSession().setAttribute("message", message); response.sendRedirect("welcome.jsp"); } } catch (IOException ioe) { throw new ServletException(); } } private String getFileName(final Part part) { final String partHeader = part.getHeader("content-disposition"); LOGGER.log(Level.INFO, "Part Header = {0}", partHeader); for (String content : part.getHeader("content-disposition").split(";")) { if (content.trim().startsWith("filename")) { return content.substring( content.indexOf('=') + 1).trim().replace("\"", ""); } } return null; } /** * @param filePartInputStream * @return fileOutPutStream som en array av bytes. * @throws IOException * Skriver InputStream-en til en ByteArrayOutputStream som blir returnert * som en array av bytes. */ private byte[] convertToByteArray(InputStream filePartInputStream) throws IOException { int bytesRead; byte[] buffer = new byte[8192]; ByteArrayOutputStream fileOutPutStream = new ByteArrayOutputStream(); while ((bytesRead = filePartInputStream.read(buffer)) != -1) { fileOutPutStream.write(buffer, 0, bytesRead); } fileOutPutStream.flush(); return fileOutPutStream.toByteArray(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Upload(request, response); } }
package main.java.filemanager; import java.io.File; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet("/api/v1/UploadServlet") @MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB maxFileSize=1024*1024*10, // 10MB maxRequestSize=1024*1024*50) // 50MB public class UploadServlet extends HttpServlet { /** * Name of the directory where uploaded files will be saved, relative to * the web application directory. */ private static final String SAVE_DIR = "uploadFiles"; /** * handles file upload */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // gets absolute path of the web application String appPath = request.getServletContext().getRealPath(""); // constructs path of the directory to save uploaded file String savePath = appPath + File.separator + SAVE_DIR; // creates the save directory if it does not exists File fileSaveDir = new File(savePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } for (Part part : request.getParts()) { String fileName = extractFileName(part); part.write(savePath + File.separator + fileName); } request.setAttribute("message", "Upload has been done successfully into " + savePath + " !"); getServletContext().getRequestDispatcher("/api/v1/message.jsp").forward( request, response); } /** * Extracts file name from HTTP header content-disposition */ private String extractFileName(Part part) { String contentDisp = part.getHeader("content-disposition"); String[] items = contentDisp.split(";"); for (String s : items) { if (s.trim().startsWith("filename")) { return s.substring(s.indexOf("=") + 2, s.length()-1); } } return ""; } }
package gg.uhc.uhc.modules; import com.google.common.base.Preconditions; import gg.uhc.uhc.inventory.IconStack; import gg.uhc.uhc.messages.MessageTemplates; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.plugin.Plugin; public abstract class Module { protected final IconStack icon = new IconStack(Material.BARRIER, 1); protected ConfigurationSection config; protected MessageTemplates messages; protected Plugin plugin; protected String id; /** * @param plugin the plugin instance to use for timers e.t.c. */ public void setPlugin(Plugin plugin) { this.plugin = plugin; } /** * @return the plugin instance used by this module. May be null if not set yet */ public Plugin getPlugin() { return plugin; } /** * @param messages templating section to pull messages from */ public void setMessageTemplates(MessageTemplates messages) { this.messages = messages; } /** * @return templating section, null if not set yet. */ public MessageTemplates getMessageTemaplates() { return messages; } /** * @param section the config section to pull values from */ public void setConfig(ConfigurationSection section) { this.config = section; } /** * @return config section to pull config from, null if not set yet */ public ConfigurationSection getConfig() { return config; } public void setId(String id) { Preconditions.checkState(this.id == null, "ID has already been set, cannot be set again"); this.id = id; } /** * @return the id of this module, may be null if not set yet */ public String getId() { return this.id; } /** * Should be called after constuctor and setters have been called * @throws InvalidConfigurationException */ public abstract void initialize() throws InvalidConfigurationException; /** * Simple wrapper around plugin.saveConfig(); */ protected void saveConfig() { plugin.saveConfig(); } /** * @return this modules IconStack */ public final IconStack getIconStack() { return icon; } }
package info.bitrich.xchangestream.okex; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import info.bitrich.xchangestream.okex.dto.RequestMessage; import info.bitrich.xchangestream.service.netty.JsonNettyStreamingService; import info.bitrich.xchangestream.service.netty.WebSocketClientHandler; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.reactivex.Completable; import io.reactivex.CompletableSource; import io.reactivex.ObservableEmitter; import org.knowm.xchange.ExchangeSpecification; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.zip.Inflater; public class OkexStreamingService extends JsonNettyStreamingService { private final Logger LOG = LoggerFactory.getLogger(OkexStreamingService.class); private final ObjectMapper objectMapper = new ObjectMapper(); private List<ObservableEmitter<Long>> delayEmitters = new LinkedList<>(); protected ExchangeSpecification exchangeSpecification; private ConcurrentHashMap<String, JsonNode> eventResponse = new ConcurrentHashMap<>(); public OkexStreamingService(String apiUrl) { super(apiUrl); } public void setExchangeSpecification(ExchangeSpecification exchangeSpecification) { this.exchangeSpecification = exchangeSpecification; } @Override public Completable connect() { Completable conn = super.connect(); if (this.exchangeSpecification.getApiKey() == null) { return conn; } return conn.andThen((CompletableSource) (completable) -> { try { String apiKey = exchangeSpecification.getApiKey(); String apiSecret = exchangeSpecification.getSecretKey(); String passphrase; if (exchangeSpecification.getExchangeSpecificParametersItem("Passphrase") == null) { passphrase = exchangeSpecification.getPassword(); } else { passphrase = exchangeSpecification.getExchangeSpecificParametersItem("Passphrase").toString(); } sendMessage(objectMapper.writeValueAsString(OkexAuthenticator.authenticateMessage(apiKey, apiSecret, passphrase))); eventResponse.remove("error"); eventResponse.remove("login"); while (!eventResponse.containsKey("error") && !eventResponse.containsKey("login")) { try { Thread.sleep(1); } catch (InterruptedException e) { } } if (eventResponse.containsKey("login")) { completable.onComplete(); } else { completable.onError(new Exception(eventResponse.get("error").asText())); } } catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) { completable.onError(e); } }); } @Override protected String getChannelNameFromMessage(JsonNode message) throws IOException { return message.get("channel").asText(); } @Override public String getSubscribeMessage(String channelName, Object... args) throws IOException { RequestMessage requestMessage = new RequestMessage(RequestMessage.Operation.SUBSCRIBE, Collections.singletonList(channelName)); return objectMapper.writeValueAsString(requestMessage); } @Override public String getUnsubscribeMessage(String channelName) throws IOException { RequestMessage requestMessage = new RequestMessage(RequestMessage.Operation.UNSUBSCRIBE, Collections.singletonList(channelName)); return objectMapper.writeValueAsString(requestMessage); } @Override protected void handleMessage(JsonNode message) { if (message.has("event")) { eventResponse.put(message.get("event").asText(), message); if ("error".equals(message.get("event").asText())) { LOG.error("Error Message Received: {}", message); return; } } if (message.get("table") != null && message.get("data") != null) { String table = message.get("table").asText(); Set<String> instrumentIds = new HashSet<>(); boolean delayEmitted = false; for (JsonNode data : message.get("data")) { if (data.get("instrument_id") != null) { instrumentIds.add(data.get("instrument_id").asText()); } if (data.get("timestamp") != null && !delayEmitted) { delayEmitted = true; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); format.setTimeZone(TimeZone.getTimeZone("UTC")); for (ObservableEmitter<Long> emitter : delayEmitters) { try { emitter.onNext(System.currentTimeMillis() - format.parse(data.get("timestamp").asText()).getTime()); } catch (ParseException e) { LOG.error("Parse timestamp error", e); } } } } for (String instrumentId : instrumentIds) { handleChannelMessage(String.format("%s:%s", table, instrumentId), message); } } } public void addDelayEmitter(ObservableEmitter<Long> delayEmitter) { delayEmitters.add(delayEmitter); } @Override protected WebSocketClientHandler getWebSocketClientHandler(WebSocketClientHandshaker handshaker, WebSocketClientHandler.WebSocketMessageHandler handler) { return new OkCoinNettyWebSocketClientHandler(handshaker, handler); } protected class OkCoinNettyWebSocketClientHandler extends NettyWebSocketClientHandler { private final Logger LOG = LoggerFactory.getLogger(OkCoinNettyWebSocketClientHandler.class); protected OkCoinNettyWebSocketClientHandler(WebSocketClientHandshaker handshaker, WebSocketMessageHandler handler) { super(handshaker, handler); } @Override public void channelInactive(ChannelHandlerContext ctx) { super.channelInactive(ctx); } @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (!handshaker.isHandshakeComplete()) { super.channelRead0(ctx, msg); return; } super.channelRead0(ctx, msg); WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame; ByteBuf byteBuf = binaryFrame.content(); byte[] temp = new byte[byteBuf.readableBytes()]; ByteBufInputStream bis = new ByteBufInputStream(byteBuf); StringBuilder appender = new StringBuilder(); try { bis.read(temp); bis.close(); Inflater infl = new Inflater(true); infl.setInput(temp, 0, temp.length); byte[] result = new byte[1024]; while (!infl.finished()) { int length = infl.inflate(result); appender.append(new String(result, 0, length, "UTF-8")); } infl.end(); } catch (Exception e) { LOG.trace("Error when inflate websocket binary message"); } handler.onMessage(appender.toString()); } } } }
package io.quarkus.container.image.deployment; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Optional; import org.junit.jupiter.api.Test; class ContainerImageConfigEffectiveGroupTest { public static final String USER_NAME_SYSTEM_PROPERTY = "user.name"; private ContainerImageConfig sut = new ContainerImageConfig(); @Test void testFromLowercaseUsername() { testWithNewUsername("test", () -> { sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(sut.getEffectiveGroup(), Optional.of("test")); }); } @Test void testFromUppercaseUsername() { testWithNewUsername("TEST", () -> { sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(sut.getEffectiveGroup(), Optional.of("test")); }); } @Test void testFromSpaceInUsername() { testWithNewUsername("user name", () -> { sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(sut.getEffectiveGroup(), Optional.of("user-name")); }); } @Test void testFromOther() { testWithNewUsername("WhateveR", () -> { sut.group = Optional.of("OtheR"); assertEquals(sut.getEffectiveGroup(), Optional.of("OtheR")); }); } private void testWithNewUsername(String newUserName, Runnable test) { String previousUsernameValue = System.getProperty(USER_NAME_SYSTEM_PROPERTY); System.setProperty(USER_NAME_SYSTEM_PROPERTY, newUserName); test.run(); System.setProperty(USER_NAME_SYSTEM_PROPERTY, previousUsernameValue); } }
package mathsquared.resultswizard2; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Map; import java.util.Queue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Given an {@link ObjectInputStream} and an {@link ObjectOutputStream}, exposes {@link Queue}s that communicate with these streams. * * @author MathSquared * */ public class StreamQueueProxy implements Runnable { private final ObjectInputStream inS; private final ObjectOutputStream outS; private final Queue inQ; private final Queue outQ; // used to stop operation when needed private volatile boolean aborted = false; /** * Creates a StreamQueueProxy that communicates with the given streams. * * <p> * Note that the parameters <code>inS</code> and <code>outS</code> should be pre-initialized, since the <code>ObjectInputStream</code> constructor can block if it hasn't received a stream header from the other end of the connection. * </p> * * @param inS the <code>ObjectInputStream</code> that the client application will read from by way of the corresponding queue * @param outS the <code>ObjectOutputStream</code> that the client application will write to by way of the corresponding queue */ public StreamQueueProxy (ObjectInputStream inS, ObjectOutputStream outS) { this.inS = inS; this.outS = outS; inQ = new ConcurrentLinkedQueue(); outQ = new ConcurrentLinkedQueue(); } /** * Continually updates the <code>Queue</code>s with data from the streams until {@linkplain #abort() aborted}. */ public void run () { while (!aborted) { // Pop the output queue try { // Surround entire loop with try-catch so we don't get stuck trying to send one element while (!outQ.isEmpty()) { outS.writeObject(outQ.peek()); outQ.poll(); // separated into two calls so if a write fails, we don't simply lose the polled element } } catch (IOException e) { System.out.println("An I/O error has occurred during writing: " + e.getMessage()); e.printStackTrace(System.out); } // Continually retrieve objects from the input queue until a given time limit is exceeded ExecutorService pool = Executors.newCachedThreadPool(); try { while (true) { Future<Object> future = pool.submit(new Callable<Object>() { public Object call () { try { return inS.readObject(); } catch (ClassNotFoundException e) { System.out.println("Error: Class not found: " + e.getMessage()); e.printStackTrace(System.out); } catch (IOException e) { System.out.println("An I/O error has occurred during reading: " + e.getMessage()); e.printStackTrace(System.out); } // TODO rewrite this with an instance of a non-anonymous implementing class of Command, when I write an implementation return new Command() { public Message getType () { return Message.XMIT_ERROR_RESTART; } public String getStringPayload () { throw new UnsupportedOperationException("This message does not carry a String payload"); } public Map<String, Slide[]> getStringSlidesPayload () { throw new UnsupportedOperationException("This message does not carry a Map<String, Slide[]> payload"); } }; // if an exception is thrown; this queue chokes on null } }); inQ.add(future.get(1000, TimeUnit.MILLISECONDS)); } } catch (TimeoutException e) { // task timed out, so we exit the loop--probably no more data to read } catch (InterruptedException e) { } catch (ExecutionException e) { // Callable threw an exception System.out.println("Object retrieval failed: " + e.getMessage()); e.printStackTrace(System.out); } } } /** * Stops the update process previously initiated by {@link #run()}. After a StreamQueueProxy has been aborted, it cannot be used further; the client must create a new StreamQueueProxy. */ public void abort () { aborted = true; } /** * Returns a <code>Queue</code> that will be continually updated to contain objects from the given <code>ObjectInputStream</code> while this StreamQueueProxy is running. The <code>Queue</code> will be thread-safe. * * <p> * Note that if the <code>Queue</code> ever returns a value of {@link Message#XMIT_ERROR_RESTART}, the client application should discard this StreamQueueProxy, both <code>Queue</code>s from it, and the <code>Object__Streams</code> passed into the constructor, and, after error-correction behavior of the application's choosing, construct a new StreamQueueProxy with <code>Object__Streams</code> newly constructed from the original raw binary streams. * </p> * * @return a <code>Queue</code> for input into the client program */ public Queue getInQ () { return inQ; } /** * Returns a <code>Queue</code> whose contents will be continually sent over the given <code>ObjectOutputStream</code> while this StreamQueueProxy is running. The <code>Queue</code> will be thread-safe. * * @return a <code>Queue</code> for output from the client program */ public Queue getOutQ () { return outQ; } }
package me.modmuss50.rm; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.util.JsonUtils; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.common.crafting.JsonContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.registry.ForgeRegistries; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import javax.annotation.Nullable; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; @Mod(name = RecipeManipulator.MOD_NAME, modid = RecipeManipulator.MOD_ID) public class RecipeManipulator { public static final String MOD_ID = "recipemanipulator"; public static final String MOD_NAME = "RecipeManipulator"; public static File recipeDir; public static File removalFile; private static Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); private static Method loadConstantsMethod = null; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { recipeDir = new File(event.getModConfigurationDirectory().getParent(), "recipes"); if (!recipeDir.exists()) { recipeDir.mkdir(); } removalFile = new File(recipeDir, "removal.json"); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { try { removeRecipes(); } catch (IOException e) { e.printStackTrace(); } readDirectory(recipeDir); } private static void readDirectory(File recipeDir) { for (File file : recipeDir.listFiles()) { if (file.isDirectory()) { readDirectory(file); continue; } if (file.getName().equals(removalFile.getName()) || file.getName().startsWith("_")) { continue; } if (file.getName().endsWith(".json")) { readRecipeJson(file); } } } //Loosly based off the forge code private static void readRecipeJson(File recipeFile) { String name = FilenameUtils.removeExtension(recipeFile.getName()); ResourceLocation key = new ResourceLocation(MOD_ID, name); try { JsonContext ctx = new JsonContext(MOD_ID); BufferedReader reader; File constantsFile = new File(recipeFile.getParent(), "_constants.json"); reader = Files.newBufferedReader(constantsFile.toPath()); JsonObject[] constantsJson = JsonUtils.fromJson(GSON, reader, JsonObject[].class); loadConstants(ctx, constantsJson); reader = Files.newBufferedReader(recipeFile.toPath()); JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class); IRecipe recipe = CraftingHelper.getRecipe(json, ctx); ForgeRegistries.RECIPES.register(recipe.setRegistryName(key)); } catch (JsonParseException e) { throw new Error("Parsing error loading recipe " + key, e); } catch (IOException e) { throw new Error("Couldn't read recipe " + key + " from " + recipeFile.getName(), e); } } private static void loadConstants(JsonContext context, JsonObject[] json) { try { if (loadConstantsMethod == null) { for (Method method : context.getClass().getDeclaredMethods()) { if (method.getName().equals("loadConstants")) { loadConstantsMethod = method; loadConstantsMethod.setAccessible(true); } } } loadConstantsMethod.invoke(context, new Object[] { json }); } catch (IllegalAccessException | InvocationTargetException e) { throw new Error("Failed to read constants", e); } } private static void removeRecipes() throws IOException { if (!removalFile.exists()) { RemovalFormat format = new RemovalFormat(); format.recipesToRemove = new ArrayList<>(); FileUtils.writeStringToFile(removalFile, GSON.toJson(format), Charset.forName("UTF-8")); } String json = FileUtils.readFileToString(removalFile, Charset.forName("UTF-8")); RemovalFormat format = GSON.fromJson(json, RemovalFormat.class); for (String string : format.recipesToRemove) { if (string.startsWith("item@") || string.startsWith("block@") && string.contains(":")) { ResourceLocation resourceLocation = new ResourceLocation(string.replace("block@","").replace("item@", "")); removeRecipe(recipe -> { if (recipe.getRecipeOutput().isEmpty()) { return false; } if (recipe.getRecipeOutput().getItem().getRegistryName() == null) { return false; } if (recipe.getRecipeOutput().getItem().getRegistryName().equals(resourceLocation)) { return true; } return false; }); } } } public static void removeRecipe(Predicate<IRecipe> recipePredicate) { for (IRecipe recipe : CraftingManager.REGISTRY) { if (recipePredicate.test(recipe)) { removeRecipe(recipe); } } } public static void removeRecipe(IRecipe recipe){ ForgeRegistries.RECIPES.register(new BlankRecipe(recipe)); } private static class BlankRecipe implements IRecipe { IRecipe oldRecipe; public BlankRecipe(IRecipe oldRecipe) { this.oldRecipe = oldRecipe; } @Override public boolean matches(InventoryCrafting inv, World worldIn) { return false; } @Override public ItemStack getCraftingResult(InventoryCrafting inv) { return ItemStack.EMPTY; } @Override public boolean canFit(int width, int height) { return false; } @Override public ItemStack getRecipeOutput() { return ItemStack.EMPTY; } @Override public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) { return NonNullList.create(); } @Override public IRecipe setRegistryName(ResourceLocation name) { return oldRecipe.setRegistryName(name); } @Nullable @Override public ResourceLocation getRegistryName() { return oldRecipe.getRegistryName(); } @Override public Class<IRecipe> getRegistryType() { return oldRecipe.getRegistryType(); } } private static class RemovalFormat { public List<String> recipesToRemove; } public static boolean isItemEqual(final ItemStack a, final ItemStack b) { if (a == ItemStack.EMPTY || b == ItemStack.EMPTY) return false; if (a.getItem() != b.getItem()) return false; if (!ItemStack.areItemStackTagsEqual(a, b)) return false; if (a.getHasSubtypes()) { if (a.getItemDamage() != b.getItemDamage()) return false; } return true; } }
package io.quarkus.funqy.runtime.bindings.knative.events; import static io.quarkus.funqy.runtime.bindings.knative.events.KnativeEventsBindingRecorder.RESPONSE_SOURCE; import static io.quarkus.funqy.runtime.bindings.knative.events.KnativeEventsBindingRecorder.RESPONSE_TYPE; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.Executor; import java.util.function.Consumer; import javax.enterprise.inject.Instance; import javax.enterprise.inject.spi.CDI; import org.jboss.logging.Logger; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import io.netty.buffer.ByteBufInputStream; import io.quarkus.arc.ManagedContext; import io.quarkus.arc.runtime.BeanContainer; import io.quarkus.funqy.knative.events.CloudEvent; import io.quarkus.funqy.runtime.FunctionInvoker; import io.quarkus.funqy.runtime.FunctionRecorder; import io.quarkus.funqy.runtime.FunqyServerResponse; import io.quarkus.funqy.runtime.RequestContextImpl; import io.quarkus.security.identity.CurrentIdentityAssociation; import io.quarkus.security.identity.SecurityIdentity; import io.quarkus.vertx.http.runtime.CurrentVertxRequest; import io.quarkus.vertx.http.runtime.security.QuarkusHttpUser; import io.smallrye.mutiny.Uni; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerResponse; import io.vertx.ext.web.RoutingContext; public class VertxRequestHandler implements Handler<RoutingContext> { private static final Logger log = Logger.getLogger("io.quarkus.funqy"); protected final Vertx vertx; protected final ObjectMapper mapper; protected final BeanContainer beanContainer; protected final CurrentIdentityAssociation association; protected final CurrentVertxRequest currentVertxRequest; protected final Executor executor; protected final FunctionInvoker defaultInvoker; protected final Map<String, FunctionInvoker> typeTriggers; public VertxRequestHandler(Vertx vertx, BeanContainer beanContainer, ObjectMapper mapper, FunqyKnativeEventsConfig config, FunctionInvoker defaultInvoker, Map<String, FunctionInvoker> typeTriggers, Executor executor) { this.defaultInvoker = defaultInvoker; this.vertx = vertx; this.beanContainer = beanContainer; this.executor = executor; this.mapper = mapper; this.typeTriggers = typeTriggers; Instance<CurrentIdentityAssociation> association = CDI.current().select(CurrentIdentityAssociation.class); this.association = association.isResolvable() ? association.get() : null; this.currentVertxRequest = CDI.current().select(CurrentVertxRequest.class).get(); } private boolean checkHttpMethod(RoutingContext routingContext, FunctionInvoker invoker) { if (invoker.hasInput()) { if (routingContext.request().method() != HttpMethod.POST) { routingContext.fail(405); log.error("Must be POST for: " + invoker.getName()); return false; } } if (routingContext.request().method() != HttpMethod.POST && routingContext.request().method() != HttpMethod.GET) { routingContext.fail(405); log.error("Must be POST or GET for: " + invoker.getName()); return false; } return true; } @Override public void handle(RoutingContext routingContext) { String mediaType = routingContext.request().getHeader("Content-Type"); if (mediaType == null || mediaType.startsWith("application/json") || mediaType.trim().equals("")) { if (routingContext.request().getHeader("ce-id") != null) { binaryContentMode(routingContext); } else { regularFunqyHttp(routingContext); } } else if (mediaType.startsWith("application/cloudevents+json")) { structuredMode(routingContext); } else if (mediaType.startsWith("application/cloudevents-batch+json")) { routingContext.fail(406); log.error("Batch mode not supported yet"); return; } else { routingContext.fail(406); log.error("Illegal media type:" + mediaType); return; } } private void regularFunqyHttp(RoutingContext routingContext) { FunctionInvoker invoker = defaultInvoker; if (invoker == null) { String path = routingContext.request().path(); if (path.startsWith("/")) path = path.substring(1); invoker = FunctionRecorder.registry.matchInvoker(path); if (invoker == null) { routingContext.fail(404); log.error("Could not vanilla http request to function: " + path); return; } } processHttpRequest(null, routingContext, () -> { }, invoker); } private void binaryContentMode(RoutingContext routingContext) { String ceType = routingContext.request().getHeader("ce-type"); FunctionInvoker invoker = defaultInvoker; if (invoker == null) { // map by type trigger invoker = typeTriggers.get(ceType); if (invoker == null) { routingContext.fail(404); log.error("Could not map ce-type header: " + ceType + " to a function"); return; } } final FunctionInvoker targetInvoker = invoker; processHttpRequest(new HeaderCloudEventImpl(routingContext.request()), routingContext, () -> { routingContext.response().putHeader("ce-id", getResponseId()); routingContext.response().putHeader("ce-specversion", "1.0"); routingContext.response().putHeader("ce-source", (String) targetInvoker.getBindingContext().get(RESPONSE_SOURCE)); routingContext.response().putHeader("ce-type", (String) targetInvoker.getBindingContext().get(RESPONSE_TYPE)); }, invoker); } @FunctionalInterface interface ResponseProcessing { void handle(); } private void processHttpRequest(CloudEvent event, RoutingContext routingContext, ResponseProcessing handler, FunctionInvoker invoker) { if (!checkHttpMethod(routingContext, invoker)) { return; } routingContext.request().bodyHandler(buff -> { try { Object input = null; if (buff.length() > 0) { ByteBufInputStream in = new ByteBufInputStream(buff.getByteBuf()); ObjectReader reader = (ObjectReader) invoker.getBindingContext().get(ObjectReader.class.getName()); try { input = reader.readValue((InputStream) in); } catch (JsonProcessingException e) { log.error("Failed to unmarshal input", e); routingContext.fail(400); return; } } Object finalInput = input; executor.execute(() -> { try { final HttpServerResponse httpResponse = routingContext.response(); FunqyServerResponse response = dispatch(event, routingContext, invoker, finalInput); response.getOutput().emitOn(executor).subscribe().with( obj -> { if (invoker.hasOutput()) { try { httpResponse.setStatusCode(200); handler.handle(); ObjectWriter writer = (ObjectWriter) invoker.getBindingContext() .get(ObjectWriter.class.getName()); httpResponse.putHeader("Content-Type", "application/json"); httpResponse.end(writer.writeValueAsString(obj)); } catch (JsonProcessingException jpe) { log.error("Failed to unmarshal input", jpe); routingContext.fail(400); } catch (Throwable e) { routingContext.fail(e); } } else { httpResponse.setStatusCode(204); httpResponse.end(); } }, t -> routingContext.fail(t)); } catch (Throwable t) { log.error(t); routingContext.fail(500, t); } }); } catch (Throwable t) { log.error(t); routingContext.fail(500, t); } }); } private void structuredMode(RoutingContext routingContext) { if (routingContext.request().method() != HttpMethod.POST) { routingContext.fail(405); log.error("Must be POST method"); return; } routingContext.request().bodyHandler(buff -> { try { ByteBufInputStream in = new ByteBufInputStream(buff.getByteBuf()); Object input = null; JsonNode event; try { event = mapper.reader().readTree((InputStream) in); } catch (JsonProcessingException e) { log.error("Failed to unmarshal input", e); routingContext.fail(400); return; } FunctionInvoker invoker = defaultInvoker; if (invoker == null) { String eventType = event.get("type").asText(); invoker = typeTriggers.get(eventType); if (invoker == null) { routingContext.fail(404); log.error("Could not map json cloud event to function: " + eventType); return; } } final FunctionInvoker targetInvoker = invoker; if (invoker.hasInput()) { JsonNode dct = event.get("datacontenttype"); if (dct == null) { routingContext.fail(400); return; } String type = dct.asText(); if (type != null) { if (!type.equals("application/json")) { routingContext.fail(406); log.error("Illegal datacontenttype"); return; } JsonNode data = event.get("data"); if (data != null) { ObjectReader reader = (ObjectReader) invoker.getBindingContext().get(ObjectReader.class.getName()); try { input = reader.readValue(data); } catch (JsonProcessingException e) { log.error("Failed to unmarshal input", e); routingContext.fail(400); return; } } } } Object finalInput = input; executor.execute(() -> { try { final HttpServerResponse httpResponse = routingContext.response(); final FunqyServerResponse response = dispatch(new JsonCloudEventImpl(event), routingContext, targetInvoker, finalInput); response.getOutput().emitOn(executor).subscribe().with( obj -> { if (targetInvoker.hasOutput()) { httpResponse.setStatusCode(200); final Map<String, Object> responseEvent = new HashMap<>(); responseEvent.put("id", getResponseId()); responseEvent.put("specversion", "1.0"); responseEvent.put("source", targetInvoker.getBindingContext().get(RESPONSE_SOURCE)); responseEvent.put("type", targetInvoker.getBindingContext().get(RESPONSE_TYPE)); responseEvent.put("datacontenttype", "application/json"); responseEvent.put("data", obj); try { httpResponse.end(mapper.writer().writeValueAsString(responseEvent)); } catch (JsonProcessingException e) { log.error("Failed to marshal", e); routingContext.fail(400); } } else { httpResponse.setStatusCode(204); httpResponse.end(); } }, t -> routingContext.fail(t)); } catch (Throwable t) { log.error(t); routingContext.fail(500, t); } }); } catch (Throwable t) { log.error(t); routingContext.fail(500, t); } }); } private String getResponseId() { return UUID.randomUUID().toString(); } private FunqyServerResponse dispatch(CloudEvent event, RoutingContext routingContext, FunctionInvoker invoker, Object input) { ManagedContext requestContext = beanContainer.requestContext(); requestContext.activate(); if (association != null) { ((Consumer<Uni<SecurityIdentity>>) association).accept(QuarkusHttpUser.getSecurityIdentity(routingContext, null)); } currentVertxRequest.setCurrent(routingContext); try { RequestContextImpl funqContext = new RequestContextImpl(); if (event != null) { funqContext.setContextData(CloudEvent.class, event); } FunqyRequestImpl funqyRequest = new FunqyRequestImpl(funqContext, input); FunqyResponseImpl funqyResponse = new FunqyResponseImpl(); invoker.invoke(funqyRequest, funqyResponse); return funqyResponse; } finally { if (requestContext.isActive()) { requestContext.terminate(); } } } }
package org.xdi.oxauth.model.token; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import org.codehaus.jettison.json.JSONArray; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.contexts.Contexts; import org.jboss.seam.contexts.Lifecycle; import org.xdi.model.AuthenticationScriptUsageType; import org.xdi.model.GluuAttribute; import org.xdi.model.custom.script.conf.CustomScriptConfiguration; import org.xdi.model.custom.script.type.auth.PersonAuthenticationType; import org.xdi.oxauth.model.authorize.Claim; import org.xdi.oxauth.model.common.*; import org.xdi.oxauth.model.config.ConfigurationFactory; import org.xdi.oxauth.model.crypto.PublicKey; import org.xdi.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm; import org.xdi.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm; import org.xdi.oxauth.model.crypto.signature.RSAPublicKey; import org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm; import org.xdi.oxauth.model.exception.InvalidClaimException; import org.xdi.oxauth.model.exception.InvalidJweException; import org.xdi.oxauth.model.jwe.Jwe; import org.xdi.oxauth.model.jwe.JweEncrypter; import org.xdi.oxauth.model.jwe.JweEncrypterImpl; import org.xdi.oxauth.model.jwt.Jwt; import org.xdi.oxauth.model.jwt.JwtClaimName; import org.xdi.oxauth.model.jwt.JwtSubClaimObject; import org.xdi.oxauth.model.jwt.JwtType; import org.xdi.oxauth.model.ldap.PairwiseIdentifier; import org.xdi.oxauth.model.registration.Client; import org.xdi.oxauth.model.util.JwtUtil; import org.xdi.oxauth.model.util.Util; import org.xdi.oxauth.service.AttributeService; import org.xdi.oxauth.service.PairwiseIdentifierService; import org.xdi.oxauth.service.ScopeService; import org.xdi.oxauth.service.external.ExternalAuthenticationService; import org.xdi.oxauth.service.external.ExternalDynamicScopeService; import org.xdi.oxauth.service.external.context.DynamicScopeExternalContext; import org.xdi.util.security.StringEncrypter; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.*; /** * JSON Web Token (JWT) is a compact token format intended for space constrained * environments such as HTTP Authorization headers and URI query parameters. * JWTs encode claims to be transmitted as a JSON object (as defined in RFC * 4627) that is base64url encoded and digitally signed. Signing is accomplished * using a JSON Web Signature (JWS). JWTs may also be optionally encrypted using * JSON Web Encryption (JWE). * * @author Javier Rojas Blum * @author Yuriy Movchan * @version July 22, 2016 */ @Scope(ScopeType.STATELESS) @Name("idTokenFactory") @AutoCreate public class IdTokenFactory { @In private ExternalDynamicScopeService externalDynamicScopeService; @In private ExternalAuthenticationService externalAuthenticationService; @In private ScopeService scopeService; @In private AttributeService attributeService; @In private ConfigurationFactory configurationFactory; @In private PairwiseIdentifierService pairwiseIdentifierService; public Jwt generateSignedIdToken(IAuthorizationGrant authorizationGrant, String nonce, AuthorizationCode authorizationCode, AccessToken accessToken, Set<String> scopes) throws Exception { JwtSigner jwtSigner = JwtSigner.newJwtSigner(authorizationGrant.getClient()); Jwt jwt = jwtSigner.newJwt(); int lifeTime = ConfigurationFactory.instance().getConfiguration().getIdTokenLifetime(); Calendar calendar = Calendar.getInstance(); Date issuedAt = calendar.getTime(); calendar.add(Calendar.SECOND, lifeTime); Date expiration = calendar.getTime(); jwt.getClaims().setExpirationTime(expiration); jwt.getClaims().setIssuedAt(issuedAt); if (authorizationGrant.getAcrValues() != null) { jwt.getClaims().setClaim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, authorizationGrant.getAcrValues()); setAmrClaim(jwt, authorizationGrant.getAcrValues()); } if (StringUtils.isNotBlank(nonce)) { jwt.getClaims().setClaim(JwtClaimName.NONCE, nonce); } if (authorizationGrant.getAuthenticationTime() != null) { jwt.getClaims().setClaim(JwtClaimName.AUTHENTICATION_TIME, authorizationGrant.getAuthenticationTime()); } if (authorizationCode != null) { String codeHash = authorizationCode.getHash(jwtSigner.getSignatureAlgorithm()); jwt.getClaims().setClaim(JwtClaimName.CODE_HASH, codeHash); } if (accessToken != null) { String accessTokenHash = accessToken.getHash(jwtSigner.getSignatureAlgorithm()); jwt.getClaims().setClaim(JwtClaimName.ACCESS_TOKEN_HASH, accessTokenHash); } jwt.getClaims().setClaim("oxValidationURI", ConfigurationFactory.instance().getConfiguration().getCheckSessionIFrame()); jwt.getClaims().setClaim("oxOpenIDConnectVersion", ConfigurationFactory.instance().getConfiguration().getOxOpenIdConnectVersion()); List<String> dynamicScopes = new ArrayList<String>(); for (String scopeName : scopes) { org.xdi.oxauth.model.common.Scope scope = scopeService.getScopeByDisplayName(scopeName); if ((scope != null) && (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType())) { dynamicScopes.add(scope.getDisplayName()); continue; } if (scope != null && scope.getOxAuthClaims() != null) { if (scope.getIsOxAuthGroupClaims()) { JwtSubClaimObject groupClaim = new JwtSubClaimObject(); groupClaim.setName(scope.getDisplayName()); for (String claimDn : scope.getOxAuthClaims()) { GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn); String claimName = gluuAttribute.getOxAuthClaimName(); String ldapName = gluuAttribute.getName(); String attributeValue; if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) { if (ldapName.equals("uid")) { attributeValue = authorizationGrant.getUser().getUserId(); } else { attributeValue = authorizationGrant.getUser().getAttribute(gluuAttribute.getName()); } groupClaim.setClaim(claimName, attributeValue); } } jwt.getClaims().setClaim(scope.getDisplayName(), groupClaim); } else { for (String claimDn : scope.getOxAuthClaims()) { GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn); String claimName = gluuAttribute.getOxAuthClaimName(); String ldapName = gluuAttribute.getName(); String attributeValue; if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) { if (ldapName.equals("uid")) { attributeValue = authorizationGrant.getUser().getUserId(); } else { attributeValue = authorizationGrant.getUser().getAttribute(gluuAttribute.getName()); } jwt.getClaims().setClaim(claimName, attributeValue); } } } } } if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember() != null) { for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember().getClaims()) { boolean optional = true; // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType()); GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName()); if (gluuAttribute != null) { String ldapClaimName = gluuAttribute.getName(); Object attribute = authorizationGrant.getUser().getAttribute(ldapClaimName, optional); if (attribute != null) { if (attribute instanceof JSONArray) { JSONArray jsonArray = (JSONArray) attribute; List<String> values = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { String value = jsonArray.optString(i); if (value != null) { values.add(value); } } jwt.getClaims().setClaim(claim.getName(), values); } else { String value = (String) attribute; jwt.getClaims().setClaim(claim.getName(), value); } } } } } // Check for Subject Identifier Type if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) { String sectorIdentifierUri = null; if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) { sectorIdentifierUri = authorizationGrant.getClient().getSectorIdentifierUri(); } else { sectorIdentifierUri = authorizationGrant.getClient().getRedirectUris()[0]; } String userInum = authorizationGrant.getUser().getAttribute("inum"); PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier( userInum, sectorIdentifierUri); if (pairwiseIdentifier == null) { pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifierUri); pairwiseIdentifier.setId(UUID.randomUUID().toString()); pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier( pairwiseIdentifier.getId(), userInum)); pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier); } jwt.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId()); } else { String openidSubAttribute = configurationFactory.getConfiguration().getOpenidSubAttribute(); jwt.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute)); } if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) { final UnmodifiableAuthorizationGrant unmodifiableAuthorizationGrant = new UnmodifiableAuthorizationGrant(authorizationGrant); DynamicScopeExternalContext dynamicScopeContext = new DynamicScopeExternalContext(dynamicScopes, jwt, unmodifiableAuthorizationGrant); externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopeContext); } return jwtSigner.sign(); } private void setAmrClaim(JsonWebResponse jwt, String acrValues) { List<String> amrList = Lists.newArrayList(); CustomScriptConfiguration script = externalAuthenticationService.getCustomScriptConfiguration( AuthenticationScriptUsageType.BOTH, acrValues); if (script != null) { amrList.add(Integer.toString(script.getLevel())); PersonAuthenticationType externalAuthenticator = (PersonAuthenticationType) script.getExternalType(); int apiVersion = externalAuthenticator.getApiVersion(); if (apiVersion > 2) { Map<String, String> additionalAmrsOrNull = externalAuthenticator.getAdditionalAmrsOrNull(); if (additionalAmrsOrNull != null) { for (String key : additionalAmrsOrNull.keySet()) { amrList.add(key + ":" + additionalAmrsOrNull.get(key)); } } } } jwt.getClaims().setClaim(JwtClaimName.AUTHENTICATION_METHOD_REFERENCES, amrList); } public Jwe generateEncryptedIdToken(IAuthorizationGrant authorizationGrant, String nonce, AuthorizationCode authorizationCode, AccessToken accessToken, Set<String> scopes) throws InvalidJweException, InvalidClaimException, NoSuchAlgorithmException, InvalidKeyException { Jwe jwe = new Jwe(); // Header KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseAlg()); BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseEnc()); jwe.getHeader().setType(JwtType.JWT); jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm); jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm); // Claims jwe.getClaims().setIssuer(ConfigurationFactory.instance().getConfiguration().getIssuer()); jwe.getClaims().setAudience(authorizationGrant.getClient().getClientId()); int lifeTime = ConfigurationFactory.instance().getConfiguration().getIdTokenLifetime(); Calendar calendar = Calendar.getInstance(); Date issuedAt = calendar.getTime(); calendar.add(Calendar.SECOND, lifeTime); Date expiration = calendar.getTime(); jwe.getClaims().setExpirationTime(expiration); jwe.getClaims().setIssuedAt(issuedAt); if (authorizationGrant.getAcrValues() != null) { jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, authorizationGrant.getAcrValues()); setAmrClaim(jwe, authorizationGrant.getAcrValues()); } if (StringUtils.isNotBlank(nonce)) { jwe.getClaims().setClaim(JwtClaimName.NONCE, nonce); } if (authorizationGrant.getAuthenticationTime() != null) { jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_TIME, authorizationGrant.getAuthenticationTime()); } if (authorizationCode != null) { String codeHash = authorizationCode.getHash(null); jwe.getClaims().setClaim(JwtClaimName.CODE_HASH, codeHash); } if (accessToken != null) { String accessTokenHash = accessToken.getHash(null); jwe.getClaims().setClaim(JwtClaimName.ACCESS_TOKEN_HASH, accessTokenHash); } jwe.getClaims().setClaim("oxValidationURI", ConfigurationFactory.instance().getConfiguration().getCheckSessionIFrame()); jwe.getClaims().setClaim("oxOpenIDConnectVersion", ConfigurationFactory.instance().getConfiguration().getOxOpenIdConnectVersion()); List<String> dynamicScopes = new ArrayList<String>(); for (String scopeName : scopes) { org.xdi.oxauth.model.common.Scope scope = scopeService.getScopeByDisplayName(scopeName); if (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType()) { dynamicScopes.add(scope.getDisplayName()); continue; } if (scope != null && scope.getOxAuthClaims() != null) { for (String claimDn : scope.getOxAuthClaims()) { GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn); String claimName = gluuAttribute.getOxAuthClaimName(); String ldapName = gluuAttribute.getName(); String attributeValue; if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) { if (ldapName.equals("uid")) { attributeValue = authorizationGrant.getUser().getUserId(); } else { attributeValue = authorizationGrant.getUser().getAttribute(gluuAttribute.getName()); } jwe.getClaims().setClaim(claimName, attributeValue); } } } } if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember() != null) { for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember().getClaims()) { boolean optional = true; // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType()); GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName()); if (gluuAttribute != null) { String ldapClaimName = gluuAttribute.getName(); Object attribute = authorizationGrant.getUser().getAttribute(ldapClaimName, optional); if (attribute != null) { if (attribute instanceof JSONArray) { JSONArray jsonArray = (JSONArray) attribute; List<String> values = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { String value = jsonArray.optString(i); if (value != null) { values.add(value); } } jwe.getClaims().setClaim(claim.getName(), values); } else { String value = (String) attribute; jwe.getClaims().setClaim(claim.getName(), value); } } } } } // Check for Subject Identifier Type if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) { String sectorIdentifierUri; if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) { sectorIdentifierUri = authorizationGrant.getClient().getSectorIdentifierUri(); } else { sectorIdentifierUri = authorizationGrant.getClient().getRedirectUris()[0]; } String userInum = authorizationGrant.getUser().getAttribute("inum"); PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier( userInum, sectorIdentifierUri); if (pairwiseIdentifier == null) { pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifierUri); pairwiseIdentifier.setId(UUID.randomUUID().toString()); pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier( pairwiseIdentifier.getId(), userInum)); pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier); } jwe.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId()); } else { String openidSubAttribute = configurationFactory.getConfiguration().getOpenidSubAttribute(); jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute)); } if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) { final UnmodifiableAuthorizationGrant unmodifiableAuthorizationGrant = new UnmodifiableAuthorizationGrant(authorizationGrant); DynamicScopeExternalContext dynamicScopeContext = new DynamicScopeExternalContext(dynamicScopes, jwe, unmodifiableAuthorizationGrant); externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopeContext); } // Encryption if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5) { PublicKey publicKey = JwtUtil.getPublicKey(authorizationGrant.getClient().getJwksUri(), null, SignatureAlgorithm.RS256, null); if (publicKey != null && publicKey instanceof RSAPublicKey) { JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, (RSAPublicKey) publicKey); jwe = jweEncrypter.encrypt(jwe); } else { throw new InvalidJweException("The public key is not valid"); } } else if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) { try { byte[] sharedSymmetricKey = authorizationGrant.getClient().getClientSecret().getBytes(Util.UTF8_STRING_ENCODING); JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedSymmetricKey); jwe = jweEncrypter.encrypt(jwe); } catch (UnsupportedEncodingException e) { throw new InvalidJweException(e); } catch (StringEncrypter.EncryptionException e) { throw new InvalidJweException(e); } catch (Exception e) { throw new InvalidJweException(e); } } return jwe; } /** * Get IdTokenFactory instance * * @return IdTokenFactory instance */ public static IdTokenFactory instance() { boolean createContexts = !Contexts.isEventContextActive() && !Contexts.isApplicationContextActive(); if (createContexts) { Lifecycle.beginCall(); } return (IdTokenFactory) Component.getInstance(IdTokenFactory.class); } public static JsonWebResponse createJwr( IAuthorizationGrant grant, String nonce, AuthorizationCode authorizationCode, AccessToken accessToken, Set<String> scopes) throws Exception { IdTokenFactory idTokenFactory = IdTokenFactory.instance(); final Client grantClient = grant.getClient(); if (grantClient != null && grantClient.getIdTokenEncryptedResponseAlg() != null && grantClient.getIdTokenEncryptedResponseEnc() != null) { return idTokenFactory.generateEncryptedIdToken(grant, nonce, authorizationCode, accessToken, scopes); } else { return idTokenFactory.generateSignedIdToken(grant, nonce, authorizationCode, accessToken, scopes); } } }
package com.xpn.xwiki.gwt.api.server; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.doc.XWikiLock; import com.xpn.xwiki.gwt.api.client.Attachment; import com.xpn.xwiki.gwt.api.client.Dictionary; import com.xpn.xwiki.gwt.api.client.Document; import com.xpn.xwiki.gwt.api.client.User; import com.xpn.xwiki.gwt.api.client.XObject; import com.xpn.xwiki.gwt.api.client.XWikiGWTException; import com.xpn.xwiki.gwt.api.client.XWikiService; import com.xpn.xwiki.objects.*; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.objects.classes.ListClass; import com.xpn.xwiki.render.XWikiVelocityRenderer; import com.xpn.xwiki.user.api.XWikiUser; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiEngineContext; import com.xpn.xwiki.web.XWikiMessageTool; import com.xpn.xwiki.web.XWikiRequest; import com.xpn.xwiki.web.XWikiResponse; import com.xpn.xwiki.web.XWikiServletContext; import com.xpn.xwiki.web.XWikiServletRequest; import com.xpn.xwiki.web.XWikiURLFactory; import com.xpn.xwiki.xmlrpc.MockXWikiServletContext; import com.xpn.xwiki.xmlrpc.XWikiXMLRPCResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.ServletContext; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; public class XWikiServiceImpl extends RemoteServiceServlet implements XWikiService { private static final Log log = LogFactory.getLog(XWiki.class); XWikiEngineContext engine; // Holding debug request and response objects XWikiRequest request; XWikiResponse response; public XWikiServiceImpl() { super(); } public XWikiServiceImpl(XWikiRequest request, XWikiResponse response, XWikiEngineContext engine) { this.request = request; this.response = response; this.engine = engine; } protected XWikiContext getXWikiContext() throws XWikiException { if (this.engine==null) { ServletContext sContext = null; try { sContext = getServletContext(); } catch (Exception ignore) { } if (sContext != null) { engine = new XWikiServletContext(sContext); } else { engine = new XWikiServletContext(new MockXWikiServletContext()); } } XWikiRequest request = (this.request!=null) ? this.request : new XWikiServletRequest(getThreadLocalRequest()); // use fake request XWikiResponse response = (this.response!=null) ? this.response : new XWikiXMLRPCResponse(getThreadLocalResponse()); // use fake response XWikiContext context = Utils.prepareContext("", request, response, engine); context.setMode(XWikiContext.MODE_GWT); context.setDatabase("xwiki"); XWiki xwiki = XWiki.getXWiki(context); XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context); context.setURLFactory(urlf); XWikiVelocityRenderer.prepareContext(context); xwiki.prepareResources(context); String username = "XWiki.XWikiGuest"; if (context.getMode() == XWikiContext.MODE_GWT_DEBUG) username = "XWiki.superadmin"; XWikiUser user = context.getWiki().checkAuth(context); if (user != null) username = user.getUser(); context.setUser(username); if (context.getDoc() == null) context.setDoc(new XWikiDocument("Fake", "Document")); context.put("ajax", new Boolean(true)); return context; } protected XWikiGWTException getXWikiGWTException(Exception e) { // let's make sure we are informed if (log.isErrorEnabled()) { log.error("Unhandled exception on the server", e); } if (e instanceof XWikiGWTException){ return (XWikiGWTException) e; } XWikiException exp; if (e instanceof XWikiException) exp = (XWikiException) e; else exp = new XWikiException(XWikiException.MODULE_XWIKI_GWT_API, XWikiException.ERROR_XWIKI_UNKNOWN, "Unknown GWT Exception", e); return new XWikiGWTException(exp.getMessage(), exp.getFullMessage(), exp.getCode(), exp.getModule()); } public Document getDocument(String fullName) throws XWikiGWTException { return getDocument(fullName, false, false, false, false); } public Document getDocument(String fullName, boolean full, boolean withRenderedContent) throws XWikiGWTException { return getDocument(fullName, full, false, false, withRenderedContent); } public String getUniquePageName(String space) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); return context.getWiki().getUniquePageName(space, context); } catch (Exception e) { throw getXWikiGWTException(e); } } public String getUniquePageName(String space, String pageName) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); return context.getWiki().getUniquePageName(space, pageName, context); } catch (Exception e) { throw getXWikiGWTException(e); } } public Document getUniqueDocument(String space, String pageName) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); String fullName = context.getWiki().getUniquePageName(space, pageName, context); return getDocument(fullName); } catch (Exception e) { throw getXWikiGWTException(e); } } public Document getUniqueDocument(String space) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); String fullName = context.getWiki().getUniquePageName(space, context); return getDocument(space + "." + fullName); } catch (Exception e) { throw getXWikiGWTException(e); } } public Document getDocument(String fullName, boolean full, boolean viewDisplayers, boolean editDisplayers) throws XWikiGWTException { return getDocument(fullName, full, viewDisplayers, editDisplayers, false); } public Document getDocument(String fullName, boolean full, boolean viewDisplayers, boolean editDisplayers, boolean withRenderedContent) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), fullName, context) == true) { XWikiDocument doc = context.getWiki().getDocument(fullName, context); return newDocument(new Document(), doc, full, viewDisplayers, editDisplayers, withRenderedContent, context); } else { return null; } } catch (Exception e) { throw getXWikiGWTException(e); } } public Boolean deleteDocument(String docName) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("delete", context.getUser(), docName, context)) { XWikiDocument doc = context.getWiki().getDocument(docName, context); context.getWiki().deleteDocument(doc, context); return Boolean.valueOf(true); } else { return Boolean.valueOf(false); } } catch (Exception e) { throw getXWikiGWTException(e); } } public int deleteDocuments(String sql) throws XWikiGWTException { int nb = 0; List newlist = new ArrayList(); try { XWikiContext context = getXWikiContext(); List list = context.getWiki().getStore().searchDocumentsNames(sql, context); if ((list==null)&&(list.size()==0)) return nb; for (int i=0;i<list.size();i++) { if (context.getWiki().getRightService().hasAccessLevel("delete", context.getUser(), (String) list.get(i), context)==true) { XWikiDocument doc = context.getWiki().getDocument((String) list.get(i), context); context.getWiki().deleteDocument(doc, context); nb++; } } return nb; } catch (Exception e) { throw getXWikiGWTException(e); } } public User getUser() throws XWikiGWTException { try { return getUser(getXWikiContext().getUser()); } catch (Exception e) { throw getXWikiGWTException(e); } } public User getUser(String fullName) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), fullName, context)==true) { XWikiDocument doc = context.getWiki().getDocument(fullName, context); return newUser(new User(), doc, context); } else { return null; } } catch (Exception e) { throw getXWikiGWTException(e); } } public User[] getUserList(int nb, int start) throws XWikiGWTException { User[] users = new User[nb]; try { XWikiContext context = getXWikiContext(); List list = searchDocuments(",BaseObject as obj where doc.fullName=obj.name and obj.className='XWiki.XWikiUsers'", nb, start, context); if (list==null) return new User[0]; for (int i=0;i<list.size();i++) { String username = (String) list.get(i); XWikiDocument userdoc = context.getWiki().getDocument(username, context); users[i] = newUser(new User(), userdoc, context); } return users; } catch (Exception e) { throw getXWikiGWTException(e); } } public List searchDocuments(String sql, int nb, int start) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); return searchDocuments(sql, nb, start, context); } catch (Exception e) { throw getXWikiGWTException(e); } } public List getDocuments(String sql, int nb, int start) throws XWikiGWTException { return getDocuments(sql, nb, start, false); } public List getDocuments(String sql, int nb, int start, boolean full) throws XWikiGWTException { return getDocuments(sql, nb, start, full, false, false); } public List getDocuments(String sql, int nb, int start, boolean full, boolean viewDisplayers, boolean editDisplayers) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); return getDocuments(sql, nb, start, full, viewDisplayers, editDisplayers, false, context); } catch (Exception e) { throw getXWikiGWTException(e); } } public boolean updateProperty(String docname, String className, String propertyname, String value) throws XWikiGWTException { XWikiContext context = null; try { context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), docname, context)==true) { XWikiDocument doc = context.getWiki().getDocument(docname, context); doc.setStringValue(className, propertyname, value); context.getWiki().saveDocument(doc, context.getMessageTool().get("core.comment.updateProperty"), context); return true; } else return false; } catch (Exception e) { throw getXWikiGWTException(e); } } public boolean updateProperty(String docname, String className, String propertyname, int value) throws XWikiGWTException { XWikiContext context = null; try { context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), docname, context)==true) { XWikiDocument doc = context.getWiki().getDocument(docname, context); doc.setIntValue(className, propertyname, value); context.getWiki().saveDocument(doc, context.getMessageTool().get("core.comment.updateProperty"), context); return true; } else return false; } catch (Exception e) { throw getXWikiGWTException(e); } } public boolean updateProperty(String docname, String className, String propertyname, List value) throws XWikiGWTException { XWikiContext context = null; try { context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), docname, context)==true) { XWikiDocument doc = context.getWiki().getDocument(docname, context); BaseClass bclass = context.getWiki().getClass(className, context); ListClass lclass = (ListClass) ((bclass==null) ? null : bclass.get(propertyname)); BaseProperty prop = lclass.fromValue(value); doc.setProperty(className, propertyname, prop); context.getWiki().saveDocument(doc, context.getMessageTool().get("core.comment.updateProperty"), context); return true; } else return false; } catch (Exception e) { throw getXWikiGWTException(e); } } private List getDocuments(String sql, int nb, int start, boolean full, boolean viewDisplayers, boolean editDisplayers, XWikiContext context) throws XWikiGWTException { return getDocuments(sql, nb, start, full, viewDisplayers, editDisplayers, false, context); } private List getDocuments(String sql, int nb, int start, boolean full, boolean viewDisplayers, boolean editDisplayers, boolean withRenderedContent, XWikiContext context) throws XWikiGWTException { List newlist = new ArrayList(); try { List list = context.getWiki().getStore().searchDocumentsNames(sql, nb, start, context); if ((list==null)&&(list.size()==0)) return newlist; for (int i=0;i<list.size();i++) { if (context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), (String) list.get(i), context)==true) { XWikiDocument doc = context.getWiki().getDocument((String) list.get(i), context); Document apidoc = newDocument(new Document(), doc, full, viewDisplayers, editDisplayers, withRenderedContent, context); newlist.add(apidoc); } } return newlist; } catch (Exception e) { throw getXWikiGWTException(e); } } private List searchDocuments(String sql, int nb, int start, XWikiContext context) throws XWikiGWTException { List newlist = new ArrayList(); try { List list = context.getWiki().getStore().searchDocumentsNames(sql, nb, start, context); if ((list==null)&&(list.size()==0)) return newlist; for (int i=0;i<list.size();i++) { if (context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), (String) list.get(i), context)==true) newlist.add(list.get(i)); } return newlist; } catch (Exception e) { throw getXWikiGWTException(e); } } public List getObjects(String sql, String className, int nb, int start) throws XWikiGWTException { List docs = getDocuments(sql, nb, start, true); List objects = new ArrayList(); Iterator it = docs.iterator(); while(it.hasNext()){ Document doc = (Document) it.next(); List docObjs = doc.getObjects(className); if (docObjs != null) objects.addAll(docObjs); } return objects; } public XObject getFirstObject(String sql, String className) throws XWikiGWTException { List objs = getObjects(sql, className, 1, 0); if (objs != null && objs.size() > 0) return (XObject) objs.get(0); return null; } public XObject addObject(XWikiDocument doc, String className) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); int index = doc.createNewObject(className, context); return newObject(new XObject(), doc.getObject(className, index), false, false, context); } catch (Exception e) { throw getXWikiGWTException(e); } } public XObject addObject(String fullName, String className) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), fullName, context)) { XWikiDocument doc = context.getWiki().getDocument(fullName, context); XObject obj = addObject(doc, className); context.getWiki().saveDocument(doc, context.getMessageTool().get("core.comment.updateProperty"), context); return obj; } return null; } catch (Exception e) { throw getXWikiGWTException(e); } } public List addObject(String fullName, List classesName) throws XWikiGWTException { try{ XWikiContext context = getXWikiContext(); XWikiDocument doc = context.getWiki().getDocument(fullName, context); Iterator it = classesName.iterator(); List objs = new ArrayList(); while(it.hasNext()){ objs.add(addObject(doc, (String) it.next())); } context.getWiki().saveDocument(doc, context.getMessageTool().get("core.comment.addObject"), context); return objs; } catch (Exception e) { throw getXWikiGWTException(e); } } public boolean addObject(String docname, XObject xobject) throws XWikiGWTException { XWikiContext context = null; try { context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), docname, context)==true) { XWikiDocument doc = context.getWiki().getDocument(docname, context); BaseObject newObject = doc.newObject(xobject.getClassName(), context); mergeObject(xobject, newObject, context); context.getWiki().saveDocument(doc, context.getMessageTool().get("core.comment.addObject"), context); return true; } else return false; } catch (Exception e) { throw getXWikiGWTException(e); } } /** * save only the content of a document * TODO manage translations * @param fullName * @param content * @return */ public Boolean saveDocumentContent(String fullName, String content) throws XWikiGWTException { return saveDocumentContent(fullName, content, null); } /** * save only the content of a document * TODO manage translations * @param fullName * @param content * @return */ public Boolean saveDocumentContent(String fullName, String content, String comment) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), fullName, context)) { XWikiDocument doc = context.getWiki().getDocument(fullName, context); doc.setContent(content); doc.setAuthor(context.getUser()); if (doc.isNew()) doc.setCreator(context.getUser()); context.getWiki().saveDocument(doc, (comment==null) ? context.getMessageTool().get("core.comment.updateContent") : comment, context); return Boolean.valueOf(true); } else { return Boolean.valueOf(false); } } catch (Exception e) { throw getXWikiGWTException(e); } } public Boolean saveObject(XObject object) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), object.getName(), context)) { XWikiDocument doc = context.getWiki().getDocument(object.getName(), context); BaseObject bObject = newBaseObject(doc.getObject(object.getClassName(), object.getNumber()),object, context); doc.setObject(object.getClassName(), object.getNumber(), bObject); doc.setAuthor(context.getUser()); if (doc.isNew()) doc.setCreator(context.getUser()); context.getWiki().saveDocument(doc, context.getMessageTool().get("core.comment.updateObject"), context); return Boolean.valueOf(true); } else { return Boolean.valueOf(false); } } catch (Exception e) { throw getXWikiGWTException(e); } } public Boolean deleteObject(XObject object) throws XWikiGWTException { return deleteObject(object.getName(), object.getClassName(), object.getNumber()); } public Boolean deleteObject(String docName, String className, int number) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), docName, context)) { XWikiDocument doc = context.getWiki().getDocument(docName, context); BaseObject bObj = doc.getObject(className, number); if (!doc.removeObject(bObj)) return Boolean.valueOf(false); doc.setAuthor(context.getUser()); if (doc.isNew()) doc.setCreator(context.getUser()); context.getWiki().saveDocument(doc, context.getMessageTool().get("core.comment.deleteObject"), context); return Boolean.valueOf(true); } else { return Boolean.valueOf(false); } } catch (Exception e) { throw getXWikiGWTException(e); } } public Boolean saveObjects(List objects) throws XWikiGWTException { Iterator it = objects.iterator(); boolean error = false; while(it.hasNext()){ error |= !saveObject((XObject) it.next()).booleanValue(); } return Boolean.valueOf(!error); } /** * return true if can be locked * return null in case of an error * return false in all the other cases * @param fullName * @param force * @return */ public Boolean lockDocument(String fullName, boolean force) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); XWikiDocument doc = context.getWiki().getDocument(fullName, context); if (context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), fullName, context)) { /* Setup a lock */ XWikiLock lock = doc.getLock(context); if ((lock == null) || (lock.getUserName().equals(context.getUser())) || force) { if (lock != null) doc.removeLock(context); doc.setLock(context.getUser(), context); return Boolean.valueOf(true); } else return Boolean.valueOf(false); } else return Boolean.valueOf(false); } catch (Exception e) { throw getXWikiGWTException(e); } } public void unlockDocument(String fullName) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); XWikiDocument doc = context.getWiki().getDocument(fullName, context); XWikiLock lock = doc.getLock(context); if (lock != null) doc.removeLock(context); } catch (Exception e) { throw getXWikiGWTException(e); } } public Boolean isLastDocumentVersion(String fullName, String version) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); return Boolean.valueOf(context.getWiki().getDocument(fullName, context).getVersion().equals(version)); } catch (Exception e) { throw getXWikiGWTException(e); } } public String getLoginURL() throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); return context.getWiki().getDocument("XWiki.XWikiLogin", context).getExternalURL("login", context); } catch (Exception e) { throw getXWikiGWTException(e); } } public String login(String username, String password, boolean rememberme) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); XWikiUser user = context.getWiki().getAuthService().checkAuth(username, password, rememberme ? "yes" : "no", context); if (user==null) return "XWiki.XWikiGuest"; else return user.getUser(); } catch (Exception e) { throw getXWikiGWTException(e); } } public boolean addComment(String docname, String message) throws XWikiGWTException { XWikiContext context = null; try { context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("comment", context.getUser(), docname, context)==true) { XWikiDocument doc = context.getWiki().getDocument(docname, context); BaseObject newObject = doc.newObject("XWiki.XWikiComments", context); newObject.set("author", context.getUser(), context); newObject.set("date", new Date(), context); newObject.set("comment", message, context); context.getWiki().saveDocument(doc, context.getMessageTool().get("core.comment.addComment"), context); return true; } else return false; } catch (Exception e) { throw getXWikiGWTException(e); } } public List customQuery(String queryPage) throws XWikiGWTException { return customQuery(queryPage, null, 0, 0); } public List customQuery(String queryPage, Map params) throws XWikiGWTException { return customQuery(queryPage, params, 0, 0); } public List customQuery(String queryPage, int nb, int start) throws XWikiGWTException { return customQuery(queryPage, null, nb, start); } public List customQuery(String queryPage, Map params, int nb, int start) throws XWikiGWTException { List newlist = new ArrayList(); try { XWikiContext context = getXWikiContext(); XWikiDocument queryDoc = context.getWiki().getDocument(queryPage, context); if (context.getWiki().getRightService().hasProgrammingRights(queryDoc, context)) { if (params!=null) { XWikiRequestWrapper srw = new XWikiRequestWrapper(context.getRequest()); Iterator it = params.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); Object value = params.get(key); if (key instanceof String) { // we clean params so that they cannot close a string params.put(key, ((String)value).replaceAll("'", "")); } else { params.remove(key); } } srw.setParameterMap(params); context.setRequest(srw); } List list = context.getWiki().getStore().search(queryDoc.getRenderedContent(context), nb, start, context); for (int i=0;i<list.size();i++) { Object[] item = (Object[]) list.get(i); List itemlist = new ArrayList(); for (int j=0;j<item.length;j++) { itemlist.add(item[j]); } newlist.add(itemlist); } return newlist; } return null; } catch (Exception e) { throw getXWikiGWTException(e); } } protected User newUser(User user, XWikiDocument xdoc, XWikiContext context) throws XWikiGWTException { newDocument(user, xdoc, context); user.setFirstName(xdoc.getStringValue("XWiki.XWikiUsers", "first_name")); user.setLastName(xdoc.getStringValue("XWiki.XWikiUsers", "last_name")); user.setEmail(xdoc.getStringValue("XWiki.XWikiUsers", "email")); XWiki xwiki = context.getWiki(); user.setAdmin(xwiki.getRightService().hasAdminRights(context)); return user; } protected Document newDocument(Document doc, XWikiDocument xdoc, XWikiContext context) throws XWikiGWTException { return newDocument(doc, xdoc, false, context); } protected Document newDocument(Document doc, XWikiDocument xdoc, boolean withObjects, XWikiContext context) throws XWikiGWTException { return newDocument(doc, xdoc, withObjects, false, false, false, context); } public boolean hasAccessLevel(String level, String fullName, XWikiContext context) throws XWikiGWTException { try { return getXWikiContext().getWiki().getRightService().hasAccessLevel(level, context.getUser(), fullName, context); } catch (Exception e) { throw getXWikiGWTException(e); } } protected void assertEditRight(XWikiDocument doc, XWikiContext context) throws XWikiGWTException, XWikiException { if (context.getMode() == XWikiContext.MODE_GWT_DEBUG) return; if (!hasAccessLevel("edit", doc.getFullName(), context)) raiseRightException(context); } protected void assertViewRight(String fullName, XWikiContext context) throws XWikiGWTException, XWikiException { if (context.getMode() == XWikiContext.MODE_GWT_DEBUG) return; if (!hasAccessLevel("view", fullName, context)) raiseRightException(context); } protected void raiseRightException(XWikiContext context) throws XWikiException { if (context.getUser().equals("XWiki.XWikiGuest")){ throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_TOKEN_INVALID, "User needs to be logged-in"); } else throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "User needs appropriate rights"); } protected void assertViewRight(XWikiDocument doc, XWikiContext context) throws XWikiGWTException, XWikiException { assertViewRight(doc.getFullName(), context); } protected Document newDocument(Document doc, XWikiDocument xdoc, boolean withObjects, boolean withViewDisplayers, boolean withEditDisplayers, boolean withRenderedContent, XWikiContext context) throws XWikiGWTException { doc.setId(xdoc.getId()); doc.setTitle(xdoc.getTitle()); doc.setFullName(xdoc.getFullName()); doc.setParent(xdoc.getParent()); doc.setSpace(xdoc.getSpace()); doc.setName(xdoc.getName()); doc.setContent(xdoc.getContent()); doc.setMeta(xdoc.getMeta()); doc.setFormat(xdoc.getFormat()); doc.setCreator(xdoc.getCreator()); doc.setAuthor(xdoc.getAuthor()); doc.setContentAuthor(xdoc.getContentAuthor()); doc.setCustomClass(xdoc.getCustomClass()); doc.setVersion(xdoc.getVersion()); doc.setContentUpdateDate(xdoc.getContentUpdateDate().getTime()); doc.setDate(xdoc.getDate().getTime()); doc.setCreationDate(xdoc.getCreationDate().getTime()); doc.setMostRecent(xdoc.isMostRecent()); doc.setNew(xdoc.isNew()); doc.setTemplate(xdoc.getTemplate()); doc.setLanguage(xdoc.getLanguage()); doc.setDefaultLanguage(xdoc.getDefaultLanguage()); doc.setTranslation(xdoc.getTranslation()); doc.setComment(xdoc.getComment()); List comments = xdoc.getComments(); doc.setCommentsNumber((comments==null) ? 0 : comments.size()); doc.setUploadURL(xdoc.getExternalURL("upload", "ajax=1", context)); // "ajax=1" doc.setViewURL(xdoc.getExternalURL("view", context)); try { doc.setSaveURL(context.getWiki().getExternalURL(xdoc.getFullName(), "save", "ajax=1", context)); //, "ajax=1" } catch (Exception e) { throw getXWikiGWTException(e); } doc.setHasElement(xdoc.getElements()); try { doc.setEditRight(context.getWiki().getRightService().hasAccessLevel("edit", context.getUser(), xdoc.getFullName(), context)); } catch (Exception e) { throw getXWikiGWTException(e); } try { doc.setCommentRight(context.getWiki().getRightService().hasAccessLevel("comment", context.getUser(), xdoc.getFullName(), context)); } catch (Exception e) { throw getXWikiGWTException(e); } if (withObjects) { Iterator it = xdoc.getxWikiObjects().values().iterator(); while (it.hasNext()) { List list = (List) it.next(); for(int i=0;i< list.size();i++) { BaseObject bobj = (BaseObject) list.get(i); if (bobj!=null) { XObject obj = newObject(new XObject(),bobj, withViewDisplayers, withEditDisplayers, context); doc.addObject(bobj.getClassName(), obj); } } } } if(xdoc.getAttachmentList() != null && xdoc.getAttachmentList().size() > 0){ Iterator it = xdoc.getAttachmentList().iterator(); while (it.hasNext()) { XWikiAttachment xAtt = (XWikiAttachment) it.next(); Attachment att = newAttachment(new Attachment(), xAtt, context); doc.addAttachments(att); } } if (withRenderedContent){ try { doc.setRenderedContent(xdoc.getRenderedContent(context)); } catch (Exception e) { throw getXWikiGWTException(e); } } return doc; } protected Attachment newAttachment(Attachment att, XWikiAttachment xAtt, XWikiContext context){ att.setAttDate(xAtt.getDate().getTime()); att.setAuthor(xAtt.getAuthor()); att.setFilename(xAtt.getFilename()); att.setId(xAtt.getId()); att.setImage(xAtt.isImage(context)); att.setMimeType(xAtt.getMimeType(context)); att.setFilesize(xAtt.getFilesize()); att.setDownloadUrl(context.getWiki().getExternalAttachmentURL(xAtt.getDoc().getFullName(), xAtt.getFilename(), context)); return att; } protected XObject newObject(XObject xObject, BaseObject baseObject, boolean withViewDisplayers, boolean withEditDisplayers,XWikiContext context) { xObject.setName(baseObject.getName()); xObject.setNumber(baseObject.getNumber()); xObject.setClassName(baseObject.getClassName()); String prefix = baseObject.getxWikiClass(context).getName() + "_" + baseObject.getNumber() + "_"; Object[] propnames = baseObject.getxWikiClass(context).getFieldList().toArray(); for (int i=0;i<propnames.length;i++) { String propname = ((PropertyInterface)propnames[i]).getName(); // TODO: this needs to be a param if (!propname.equals("fullcontent")) { try { BaseProperty prop = (BaseProperty) baseObject.get(propname); if (prop!=null) { Object value = prop.getValue(); if (value instanceof Date) xObject.set(propname, new Date(((Date)prop.getValue()).getTime())); else if (value instanceof List) { List newlist = new ArrayList(); for (int j=0;j<((List)value).size();j++) { newlist.add(((List)value).get(j)); } xObject.set(propname, newlist); } else xObject.set(propname, prop.getValue()); } } catch (Exception e) {} try { if (withViewDisplayers) xObject.setViewProperty(propname, baseObject.displayView(propname, prefix, context)); } catch (Exception e) {} try { if (withEditDisplayers) { xObject.setEditProperty(propname, baseObject.displayEdit(propname, prefix, context)); xObject.setEditPropertyFieldName(propname, prefix + propname); } } catch (Exception e) {} } } return xObject; } protected void mergeObject(XObject xobject, BaseObject baseObject, XWikiContext context) { BaseClass bclass = baseObject.getxWikiClass(context); Object[] propnames = bclass.getPropertyNames(); for (int i=0;i<propnames.length;i++) { String propname = (String) propnames[i]; Object propdata = xobject.getProperty(propname); baseObject.set(propname, propdata, context); } } public String getDocumentContent(String fullName) throws XWikiGWTException { return getDocumentContent(fullName, false, null); } protected BaseObject newBaseObject(BaseObject baseObject, XObject xObject, XWikiContext context) throws XWikiException { if (baseObject==null) { baseObject = (BaseObject) context.getWiki().getClass(xObject.getClassName(), context).newObject(context); baseObject.setName(xObject.getName()); baseObject.setNumber(xObject.getNumber()); } Object[] propnames = xObject.getPropertyNames().toArray(); for (int i = 0; i < propnames.length; i++) { String propname = (String) propnames[i]; try { //TODO will not work for a date baseObject.set(propname, xObject.get(propname), context); } catch (Exception e) { } } return baseObject; } public String getDocumentContent(String fullName, boolean rendered) throws XWikiGWTException { return getDocumentContent(fullName, rendered, null); } public String getDocumentContent(String fullName, boolean rendered, Map params) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); if (context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), fullName, context)==true) { XWikiDocument doc = context.getWiki().getDocument(fullName, context); context.setDoc(doc); if (!rendered) return doc.getContent(); else { XWikiRequestWrapper srw = new XWikiRequestWrapper(context.getRequest()); srw.setParameterMap(params); context.setRequest(srw); return doc.getRenderedContent(context); } } else { return null; } } catch (Exception e) { throw getXWikiGWTException(e); } } public void logJSError(Map infos){ log.warn("[GWT-JS] useragent:" + infos.get("useragent") + "\n" + "module:" + infos.get("module") + "\n"); // + "stacktrace" + infos.get("stacktrace")); } public Dictionary getTranslation(String translationPage, String locale) throws XWikiGWTException { try { XWikiContext context = getXWikiContext(); XWikiMessageTool msg = context.getMessageTool(); // Get the translated version of the translation page document XWikiDocument docBundle = context.getWiki().getDocument(translationPage, context); docBundle = docBundle.getTranslatedDocument(context); Properties encproperties = (msg==null) ? null : msg.getDocumentBundleProperties(docBundle); Properties properties = new Properties(); // Let's convert properties from internal encoding to xwiki encoding Iterator it = encproperties.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = encproperties.getProperty(key); String newvalue = new String(value.getBytes(), XWikiMessageTool.BYTE_ENCODING); properties.setProperty(key, newvalue); } if (properties==null) return new Dictionary(); else return new Dictionary(properties); } catch (Exception e) { throw getXWikiGWTException(e); } } }
package org.springframework.ide.vscode.manifest.yaml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import org.junit.Test; import org.springframework.ide.vscode.commons.util.Renderables; import org.springframework.ide.vscode.commons.util.StringUtil; import org.springframework.ide.vscode.commons.yaml.schema.YTypedProperty; import org.springframework.ide.vscode.commons.yaml.schema.YValueHint; import org.springframework.ide.vscode.commons.yaml.schema.YTypeFactory.AbstractType; import org.springframework.ide.vscode.commons.yaml.schema.YTypeFactory.YSeqType; import org.springframework.ide.vscode.manifest.yaml.ManifestYmlSchema; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; /** * @author Kris De Volder */ public class ManifestYmlSchemaTest { private static final String[] NESTED_PROP_NAMES = { // "applications", "buildpack", "buildpacks", "command", "disk_quota", "domain", "domains", "env", "health-check-http-endpoint", "health-check-type", "host", "hosts", // "inherit", "instances", "memory", "name", "no-hostname", "no-route", "path", "random-route", "routes", "services", "stack", "timeout" }; private static final String[] TOPLEVEL_PROP_NAMES = { "applications", "buildpack", "buildpacks", "command", "disk_quota", "domain", "domains", "env", "health-check-http-endpoint", "health-check-type", // "host", // "hosts", "inherit", "instances", "memory", // "name", "no-hostname", "no-route", "path", "random-route", // "routes", "services", "stack", "timeout" }; ManifestYmlSchema schema = new ManifestYmlSchema(EMPTY_PROVIDERS); @Test public void toplevelProperties() throws Exception { assertPropNames(schema.getTopLevelType().getProperties(), TOPLEVEL_PROP_NAMES); assertPropNames(schema.getTopLevelType().getPropertiesMap(), TOPLEVEL_PROP_NAMES); } @Test public void nestedProperties() throws Exception { assertPropNames(getNestedProps(), NESTED_PROP_NAMES); } @Test public void toplevelPropertiesHaveDescriptions() { for (YTypedProperty p : schema.getTopLevelType().getProperties()) { if (!p.getName().equals("applications")) { assertHasRealDescription(p); } } } @Test public void nestedPropertiesHaveDescriptions() { for (YTypedProperty p : getNestedProps()) { assertHasRealDescription(p); } } private void assertHasRealDescription(YTypedProperty p) { { String noDescriptionText = Renderables.NO_DESCRIPTION.toHtml(); String actual = p.getDescription().toHtml(); String msg = "Description missing for '"+p.getName()+"'"; assertTrue(msg, StringUtil.hasText(actual)); assertFalse(msg, noDescriptionText.equals(actual)); } { String noDescriptionText = Renderables.NO_DESCRIPTION.toMarkdown(); String actual = p.getDescription().toMarkdown(); String msg = "Description missing for '"+p.getName()+"'"; assertTrue(msg, StringUtil.hasText(actual)); assertFalse(msg, noDescriptionText.equals(actual)); } } private List<YTypedProperty> getNestedProps() { YSeqType applications = (YSeqType) schema.getTopLevelType().getPropertiesMap().get("applications").getType(); AbstractType application = (AbstractType) applications.getDomainType(); return application.getProperties(); } private void assertPropNames(List<YTypedProperty> properties, String... expectedNames) { assertEquals(ImmutableSet.copyOf(expectedNames), getNames(properties)); } private void assertPropNames(Map<String, YTypedProperty> propertiesMap, String[] toplevelPropNames) { assertEquals(ImmutableSet.copyOf(toplevelPropNames), ImmutableSet.copyOf(propertiesMap.keySet())); } private ImmutableSet<String> getNames(Iterable<YTypedProperty> properties) { Builder<String> builder = ImmutableSet.builder(); for (YTypedProperty p : properties) { builder.add(p.getName()); } return builder.build(); } private static final ManifestYmlHintProviders EMPTY_PROVIDERS = new ManifestYmlHintProviders() { @Override public Callable<Collection<YValueHint>> getServicesProvider() { return null; } @Override public Callable<Collection<YValueHint>> getDomainsProvider() { return null; } @Override public Callable<Collection<YValueHint>> getBuildpackProviders() { return null; } @Override public Callable<Collection<YValueHint>> getStacksProvider() { return null; } }; }
package org.bullbots.visionprocessing; import org.bullbots.visionprocessing.processor.AutoInfo; import org.bullbots.visionprocessing.processor.BallFinderQueue; import org.bullbots.visionprocessing.processor.ImgInfo; import org.opencv.core.Mat; public class VisionProcessor extends AbstractVisionProcessor { BallFinderQueue bfQueue = new BallFinderQueue(5); // processor void run() { init(); int n = 0; while (true) { Mode mode = networkTable.getRobotMode(); switch (mode) { case AUTO: handleAuto(); break; case TELEOP: handleTeleOp(); break; default: logger.error("Mode is:" + mode + " - not doing anything...."); } } } private void handleTeleOp() { Mat img = camera.getImage(); ImgInfo info = ballfinder.processImage(img); if (info == null) { bfQueue.clear(); networkTable.setTeleopInfo(info); } else { bfQueue.add(info); if (bfQueue.isFull()) { networkTable.setTeleopInfo(bfQueue); } } } private void handleAuto() { Mat img = camera.getImage(); AutoInfo info = autonomousProcessor.processImage(img); networkTable.setAutoInfo(info); logger.info(info); } // Main file public static void main(String[] args) { new VisionProcessor().run(); } }
package innovimax.mixthem; import innovimax.mixthem.arguments.*; import innovimax.mixthem.io.*; import innovimax.mixthem.operation.*; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Map; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; /** * <p>Mix files together using variety of rules.</p> * @author Innovimax * @version 1.0 */ public class MixThem { public final static Logger LOGGER = Logger.getLogger(MixThem.class.getName()); private final List<InputResource> inputs; private final OutputStream output; /** * Constructor * @param inputs The list of input resource to be mixed * @param out The output stream to write mixing result */ public MixThem(List<InputResource> inputs, OutputStream output) { this.inputs = inputs; this.output = output; } static void setLogging(Level level) { if (LOGGER.getHandlers().length == 0) { //System.setProperty("java.util.logging.SimpleFormatter.format", "[%4$s] MixThem: %5$s [%1$tc]%n"); System.setProperty("java.util.logging.SimpleFormatter.format", "[%4$s] MixThem: %5$s%n"); LOGGER.setUseParentHandlers(false); LOGGER.setLevel(Level.ALL); Handler handler = new ConsoleHandler(); LOGGER.addHandler(handler); handler.setLevel(Level.OFF); String prop = System.getProperty("mixthem.logging"); if (prop == null || prop.equals("true")) { handler.setLevel(level); } } } /** * Main entry. * @param args The command line arguments */ public static void main(String[] args) { run(args); } private static void run(String[] args) { try { setLogging(Level.INFO); LOGGER.info("Started application"); Arguments mixArgs = Arguments.checkArguments(args); MixThem mixThem = new MixThem(mixArgs.getInputs(), System.out); mixThem.process(mixArgs.getMode(), mixArgs.getRule(), mixArgs.getRuleParameters()); LOGGER.info("Exited application with no errors"); } catch (ArgumentException e) { LOGGER.severe("Exited application with errors..."); LOGGER.severe("Files mixing can't be run due to following reason:"); LOGGER.severe(e.getMessage()); Arguments.printUsage(); } catch (MixException e) { LOGGER.severe("Exited application with errors..."); LOGGER.severe("Files mixing has been aborted due to following reason:"); LOGGER.severe(e.getMessage()); } catch (Exception e) { LOGGER.severe("Exited application with errors..."); LOGGER.severe("An unexpected error occurs:"); e.printStackTrace(); } } /** * Mix files together using rules. * @param mode The mode to be used for mixing * @param rule The rule to be used for mixing * @param params The rule parameters to be used for mixing * @throws MixException - If any error occurs during mixing * @see innovimax.mixthem.Mode * @see innovimax.mixthem.Rule * @see innovimax.mixthem.RuleParam * @see innovimax.mixthem.ParamValue */ public void process(Mode mode, Rule rule, Map<RuleParam, ParamValue> params) throws MixException { try { LOGGER.info("Started mixing for [" + mode.getName() + "] rule '" + rule.getName() + "'..."); switch(rule) { case FILE_1: final ICopy file1Copy = CopyFactory.newInstance(mode); file1Copy.processFile(this.inputs.get(0), this.output); break; case FILE_2: final ICopy file2Copy = CopyFactory.newInstance(mode); file2Copy.processFile(this.inputs.get(1), this.output); break; case ADD: final ICopy fileAddCopy = CopyFactory.newInstance(mode); this.inputs.stream().forEach(input -> { try { fileAddCopy.processFile(input, this.output); } catch (IOException e) { throw new RuntimeException(e); } }); break; case ALT_CHAR: final IOperation altCharOp = new DefaultCharAlternation(AltMode.NORMAL, params); altCharOp.processFiles(this.inputs, this.output); break; case ALT_BYTE: final IOperation altByteOp = new DefaultByteAlternation(AltMode.NORMAL, params); altByteOp.processFiles(this.inputs, this.output); break; case ALT_LINE: final IOperation altLineOp = new DefaultLineAlternation(AltMode.NORMAL, params); altLineOp.processFiles(this.inputs, this.output); break; case RANDOM_ALT_BYTE: final IOperation randomAltByteOp = new DefaultByteAlternation(AltMode.RANDOM, params); randomAltByteOp.processFiles(this.inputs, this.output); break; case RANDOM_ALT_CHAR: final IOperation randomAltCharOp = new DefaultCharAlternation(AltMode.RANDOM, params); randomAltCharOp.processFiles(this.inputs, this.output); break; case RANDOM_ALT_LINE: final IOperation randomAltLineOp = new DefaultLineAlternation(AltMode.RANDOM, params); randomAltLineOp.processFiles(this.inputs, this.output); break; case JOIN: final IOperation joinLineOp = new DefaultLineJoining(params); joinLineOp.processFiles(this.inputs, this.output); break; case ZIP_LINE: final IOperation zipLineOp = new DefaultLineZipping(ZipType.LINE, params); zipLineOp.processFiles(this.inputs, this.output); break; case ZIP_CELL: final IOperation zipCellOp = new DefaultLineZipping(ZipType.CELL, params); zipCellOp.processFiles(this.inputs, this.output); break; case ZIP_CHAR: final IOperation zipCharOp = new DefaultCharZipping(params); zipCharOp.processFiles(this.inputs, this.output); /*break; default: System.out.println("This rule has not been implemented yet.");*/ } LOGGER.info("Ended mixing for [" + mode.getName() + "] rule '" + rule.getName() + "'."); } catch (IOException e) { throw new MixException("Unexpected file error", e); } } }
package net.fortuna.ical4j.model; import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.Dates; import net.fortuna.ical4j.util.TimeZones; import org.apache.commons.lang3.builder.EqualsBuilder; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; /** * A representation of the DATE-TIME object defined in RFC5445. * <p/> * <em>Extract from RFC5545:</em> * <p/> * <pre> * 3.3.5. Date-Time * * Value Name: DATE-TIME * * Purpose: This value type is used to identify values that specify a * precise calendar date and time of day. * * Format Definition: This value type is defined by the following * notation: * * date-time = date "T" time ;As specified in the DATE and TIME * ;value definitions * * Description: If the property permits, multiple "DATE-TIME" values * are specified as a COMMA-separated list of values. No additional * content value encoding (i.e., BACKSLASH character encoding, see * Section 3.3.11) is defined for this value type. * * The "DATE-TIME" value type is used to identify values that contain * a precise calendar date and time of day. The format is based on * the [ISO.8601.2004] complete representation, basic format for a * calendar date and time of day. The text format is a concatenation * of the "date", followed by the LATIN CAPITAL LETTER T character, * the time designator, followed by the "time" format. * * The "DATE-TIME" value type expresses time values in three forms: * * The form of date and time with UTC offset MUST NOT be used. For * example, the following is not valid for a DATE-TIME value: * * 19980119T230000-0800 ;Invalid time format * * FORM #1: DATE WITH LOCAL TIME * * The date with local time form is simply a DATE-TIME value that * does not contain the UTC designator nor does it reference a time * zone. For example, the following represents January 18, 1998, at * 11 PM: * * 19980118T230000 * * DATE-TIME values of this type are said to be "floating" and are * not bound to any time zone in particular. They are used to * represent the same hour, minute, and second value regardless of * which time zone is currently being observed. For example, an * event can be defined that indicates that an individual will be * busy from 11:00 AM to 1:00 PM every day, no matter which time zone * the person is in. In these cases, a local time can be specified. * The recipient of an iCalendar object with a property value * consisting of a local time, without any relative time zone * information, SHOULD interpret the value as being fixed to whatever * time zone the "ATTENDEE" is in at any given moment. This means * that two "Attendees", in different time zones, receiving the same * event definition as a floating time, may be participating in the * event at different actual times. Floating time SHOULD only be * used where that is the reasonable behavior. * * In most cases, a fixed time is desired. To properly communicate a * fixed time in a property value, either UTC time or local time with * time zone reference MUST be specified. * * The use of local time in a DATE-TIME value without the "TZID" * property parameter is to be interpreted as floating time, * regardless of the existence of "VTIMEZONE" calendar components in * the iCalendar object. * * FORM #2: DATE WITH UTC TIME * * The date with UTC time, or absolute time, is identified by a LATIN * CAPITAL LETTER Z suffix character, the UTC designator, appended to * the time value. For example, the following represents January 19, * 1998, at 0700 UTC: * * 19980119T070000Z * * The "TZID" property parameter MUST NOT be applied to DATE-TIME * properties whose time values are specified in UTC. * * FORM #3: DATE WITH LOCAL TIME AND TIME ZONE REFERENCE * * The date and local time with reference to time zone information is * identified by the use the "TZID" property parameter to reference * the appropriate time zone definition. "TZID" is discussed in * detail in Section 3.2.19. For example, the following represents * 2:00 A.M. in New York on January 19, 1998: * * TZID=America/New_York:19980119T020000 * * If, based on the definition of the referenced time zone, the local * time described occurs more than once (when changing from daylight * to standard time), the DATE-TIME value refers to the first * occurrence of the referenced time. Thus, TZID=America/ * New_York:20071104T013000 indicates November 4, 2007 at 1:30 A.M. * EDT (UTC-04:00). If the local time described does not occur (when * changing from standard to daylight time), the DATE-TIME value is * interpreted using the UTC offset before the gap in local times. * Thus, TZID=America/New_York:20070311T023000 indicates March 11, * 2007 at 3:30 A.M. EDT (UTC-04:00), one hour after 1:30 A.M. EST * (UTC-05:00). * * A time value MUST only specify the second 60 when specifying a * positive leap second. For example: * * 19970630T235960Z * * Implementations that do not support leap seconds SHOULD interpret * the second 60 as equivalent to the second 59. * * Example: The following represents July 14, 1997, at 1:30 PM in New * York City in each of the three time formats, using the "DTSTART" * property. * * DTSTART:19970714T133000 ; Local time * DTSTART:19970714T173000Z ; UTC time * DTSTART;TZID=America/New_York:19970714T133000 * ; Local time and time * ; zone reference * </pre> * * @author Ben Fortuna * @version 2.0 */ public class DateTime extends Date { private static final long serialVersionUID = -6407231357919440387L; private static final String DEFAULT_PATTERN = "yyyyMMdd'T'HHmmss"; private static final String UTC_PATTERN = "yyyyMMdd'T'HHmmss'Z'"; private static final String VCARD_PATTERN = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"; private static final String RELAXED_PATTERN = "yyyyMMdd"; /** * Used for parsing times in a UTC date-time representation. */ private static final DateFormatCache UTC_FORMAT; static { final DateFormat format = new SimpleDateFormat(UTC_PATTERN); format.setTimeZone(TimeZones.getUtcTimeZone()); format.setLenient(false); UTC_FORMAT = new DateFormatCache(format); } /** * Used for parsing times in a local date-time representation. */ private static final DateFormatCache DEFAULT_FORMAT; static { final DateFormat format = new SimpleDateFormat(DEFAULT_PATTERN); format.setLenient(false); DEFAULT_FORMAT = new DateFormatCache(format); } private static final DateFormatCache LENIENT_DEFAULT_FORMAT; static { final DateFormat format = new SimpleDateFormat(DEFAULT_PATTERN); LENIENT_DEFAULT_FORMAT = new DateFormatCache(format); } private static final DateFormatCache RELAXED_FORMAT; static { final DateFormat format = new SimpleDateFormat(RELAXED_PATTERN); format.setLenient(true); RELAXED_FORMAT = new DateFormatCache(format); } private static final DateFormatCache VCARD_FORMAT; static { final DateFormat format = new SimpleDateFormat(VCARD_PATTERN); VCARD_FORMAT = new DateFormatCache(format); } private Time time; private TimeZone timezone; /** * Default constructor. */ public DateTime() { super(Dates.PRECISION_SECOND, java.util.TimeZone.getDefault()); this.time = new Time(getTime(), getFormat().getTimeZone()); } /** * @param utc * indicates if the date is in UTC time */ public DateTime(final boolean utc) { this(); setUtc(utc); } /** * @param time * a date-time value in milliseconds */ public DateTime(final long time) { super(time, Dates.PRECISION_SECOND, java.util.TimeZone.getDefault()); this.time = new Time(time, getFormat().getTimeZone()); } /** * @param date * a date-time value */ public DateTime(final java.util.Date date) { super(date.getTime(), Dates.PRECISION_SECOND, java.util.TimeZone.getDefault()); this.time = new Time(date.getTime(), getFormat().getTimeZone()); // copy timezone information if applicable.. if (date instanceof DateTime) { final DateTime dateTime = (DateTime) date; if (dateTime.isUtc()) { setUtc(true); } else { setTimeZone(dateTime.getTimeZone()); } } } /** * Constructs a new DateTime instance from parsing the specified string * representation in the default (local) timezone. * * @param value * a string representation of a date-time * @throws ParseException * where the specified string is not a valid date-time */ public DateTime(final String value) throws ParseException { this(value, null); /* * long time = 0; try { synchronized (UTC_FORMAT) { time = * UTC_FORMAT.parse(value).getTime(); } setUtc(true); } catch * (ParseException pe) { synchronized (DEFAULT_FORMAT) { * DEFAULT_FORMAT.setTimeZone(getFormat().getTimeZone()); time = * DEFAULT_FORMAT.parse(value).getTime(); } this.time = new Time(time, * getFormat().getTimeZone()); } setTime(time); */ } /** * Creates a new date-time instance from the specified value in the given * timezone. If a timezone is not specified, the default timezone (as * returned by {@link java.util.TimeZone#getDefault()}) is used. * * @param value * a string representation of a date-time * @param timezone * the timezone for the date-time instance * @throws ParseException * where the specified string is not a valid date-time */ public DateTime(final String value, final TimeZone timezone) throws ParseException { // setting the time to 0 since we are going to reset it anyway super(0, Dates.PRECISION_SECOND, timezone != null ? timezone : java.util.TimeZone.getDefault()); this.time = new Time(getTime(), getFormat().getTimeZone()); try { if (value.endsWith("Z")) { setTime(value, UTC_FORMAT.get(), null); setUtc(true); } else { if (timezone != null) { setTime(value, DEFAULT_FORMAT.get(), timezone); } else { // Use lenient parsing for floating times. This is to // overcome // the problem of parsing VTimeZone dates that specify dates // that the strict parser does not accept. setTime(value, LENIENT_DEFAULT_FORMAT.get(), getFormat().getTimeZone()); } setTimeZone(timezone); } } catch (ParseException pe) { if (CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_VCARD_COMPATIBILITY)) { try { setTime(value, VCARD_FORMAT.get(), timezone); setTimeZone(timezone); } catch (ParseException pe2) { if (CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING)) { setTime(value, RELAXED_FORMAT.get(), timezone); setTimeZone(timezone); } } } else if (CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING)) { setTime(value, RELAXED_FORMAT.get(), timezone); setTimeZone(timezone); } else { throw pe; } } } /** * @param value * a string representation of a date-time * @param pattern * a pattern to apply when parsing the date-time value * @param timezone * the timezone for the date-time instance * @throws ParseException * where the specified string is not a valid date-time */ public DateTime(String value, String pattern, TimeZone timezone) throws ParseException { // setting the time to 0 since we are going to reset it anyway super(0, Dates.PRECISION_SECOND, timezone != null ? timezone : java.util.TimeZone.getDefault()); this.time = new Time(getTime(), getFormat().getTimeZone()); final DateFormat format = CalendarDateFormatFactory .getInstance(pattern); setTime(value, format, timezone); } /** * @param value * a string representation of a date-time * @param pattern * a pattern to apply when parsing the date-time value * @param utc * indicates whether the date-time is in UTC time * @throws ParseException * where the specified string is not a valid date-time */ public DateTime(String value, String pattern, boolean utc) throws ParseException { // setting the time to 0 since we are going to reset it anyway this(0); final DateFormat format = CalendarDateFormatFactory .getInstance(pattern); if (utc) { setTime(value, format, UTC_FORMAT.get().getTimeZone()); } else { setTime(value, format, null); } setUtc(utc); } /** * Internal set of time by parsing value string. * * @param value * @param format * a {@code DateFormat}, protected by the use of a ThreadLocal. * @param tz * @throws ParseException */ private void setTime(final String value, final DateFormat format, final java.util.TimeZone tz) throws ParseException { if (tz != null) { format.setTimeZone(tz); } setTime(format.parse(value).getTime()); } /** * {@inheritDoc} */ public final void setTime(final long time) { super.setTime(time); // need to check for null time due to Android java.util.Date(long) // constructor // calling this method.. if (this.time != null) { this.time.setTime(time); } } /** * @return Returns the utc. */ public final boolean isUtc() { return time.isUtc(); } /** * Updates this date-time to display in UTC time if the argument is true. * Otherwise, resets to the default timezone. * * @param utc * The utc to set. */ public final void setUtc(final boolean utc) { // reset the timezone associated with this instance.. this.timezone = null; if (utc) { getFormat().setTimeZone(TimeZones.getUtcTimeZone()); } else { resetTimeZone(); } time = new Time(time, getFormat().getTimeZone(), utc); } /** * Sets the timezone associated with this date-time instance. If the * specified timezone is null, it will reset to the default timezone. If the * date-time instance is utc, it will turn into either a floating (no * timezone) date-time, or a date-time with a timezone. * * @param timezone * a timezone to apply to the instance */ public final void setTimeZone(final TimeZone timezone) { this.timezone = timezone; if (timezone != null) { getFormat().setTimeZone(timezone); } else { resetTimeZone(); } time = new Time(time, getFormat().getTimeZone(), false); } /** * Reset the timezone to default. */ private void resetTimeZone() { // use GMT timezone to avoid daylight savings rules affecting floating // time values.. getFormat().setTimeZone(TimeZone.getDefault()); // getFormat().setTimeZone(TimeZone.getTimeZone(TimeZones.GMT_ID)); } /** * Returns the current timezone associated with this date-time value. * * @return a Java timezone */ public final TimeZone getTimeZone() { return timezone; } /** * {@inheritDoc} */ public final String toString() { String b = super.toString() + 'T' + time.toString(); return b; } /** * {@inheritDoc} */ public boolean equals(final Object arg0) { // TODO: what about compareTo, before, after, etc.? if (arg0 instanceof DateTime) { return new EqualsBuilder().append(time, ((DateTime) arg0).time) .isEquals(); } return super.equals(arg0); } /** * {@inheritDoc} */ public int hashCode() { return super.hashCode(); } /** * This cache class is a workaround for DateFormat not being threadsafe. * We maintain map from Thread to DateFormat instance so that the instances * are not shared between threads (effectively a ThreadLocal). * TODO: once the project targets Java 8+, the new date utilities are * thread-safe and we should remove this code. */ private static class DateFormatCache { /** * This map needs to keep weak references (to avoid memory leaks - see r1.37) * and be thread-safe (since it may be concurrently modified in get() below). */ private final Map<Thread, DateFormat> threadMap = Collections.synchronizedMap(new WeakHashMap<Thread, DateFormat>()); private final DateFormat templateFormat; private DateFormatCache(DateFormat dateFormat) { this.templateFormat = dateFormat; } public DateFormat get() { DateFormat dateFormat = threadMap.get(Thread.currentThread()); if (dateFormat == null) { dateFormat = (DateFormat) templateFormat.clone(); threadMap.put(Thread.currentThread(), dateFormat); } return dateFormat; } } }